blob: 5dd7bdfcbfa109cc35f565dbf2da87788e3f71d1 [file] [log] [blame]
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattnere99c8322007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnere99c8322007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Eli Friedman9f30fc32009-05-18 22:50:54 +000014#include "clang/Frontend/ASTConsumers.h"
Chris Lattner16a0de42007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattnere99c8322007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Steve Naroff1042ff32008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.h"
Chris Lattner16a0de42007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner4431a1b2007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattnerf3a59a12007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Benjamin Kramer89b422c2009-08-23 12:08:50 +000023#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
Chris Lattner211f8b82007-10-25 17:07:24 +000025#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian99e96b02007-10-26 19:46:17 +000026#include "llvm/ADT/SmallPtrSet.h"
Ted Kremenek2d470fc2008-09-13 05:16:45 +000027#include "llvm/ADT/OwningPtr.h"
Fariborz Jahaniane3891582010-01-05 18:04:40 +000028#include "llvm/ADT/DenseSet.h"
Fariborz Jahanianf4609d42010-03-01 23:36:21 +000029
Chris Lattnere99c8322007-10-11 00:43:27 +000030using namespace clang;
Chris Lattner211f8b82007-10-25 17:07:24 +000031using llvm::utostr;
Chris Lattnere99c8322007-10-11 00:43:27 +000032
Chris Lattnere99c8322007-10-11 00:43:27 +000033namespace {
Steve Naroff1dc53ef2008-04-14 22:03:09 +000034 class RewriteObjC : public ASTConsumer {
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000035 enum {
36 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
37 block, ... */
38 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
39 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
40 __block variable */
41 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
42 helpers */
43 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
44 support routines */
45 BLOCK_BYREF_CURRENT_MAX = 256
46 };
47
48 enum {
49 BLOCK_NEEDS_FREE = (1 << 24),
50 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
51 BLOCK_HAS_CXX_OBJ = (1 << 26),
52 BLOCK_IS_GC = (1 << 27),
53 BLOCK_IS_GLOBAL = (1 << 28),
54 BLOCK_HAS_DESCRIPTOR = (1 << 29)
55 };
56
Chris Lattner0bd1c972007-10-16 21:07:07 +000057 Rewriter Rewrite;
Chris Lattnere9c810c2007-11-30 22:25:36 +000058 Diagnostic &Diags;
Steve Naroff945a3b12008-03-10 20:43:59 +000059 const LangOptions &LangOpts;
Steve Naroff7b3579b2008-01-30 19:17:43 +000060 unsigned RewriteFailedDiag;
Steve Naroff6d6da252008-12-05 17:03:39 +000061 unsigned TryFinallyContainsReturnDiag;
Mike Stump11289f42009-09-09 15:08:12 +000062
Chris Lattnerc6d91c02007-10-17 22:35:30 +000063 ASTContext *Context;
Chris Lattnere99c8322007-10-11 00:43:27 +000064 SourceManager *SM;
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +000065 TranslationUnitDecl *TUDecl;
Chris Lattnerd32480d2009-01-17 06:22:33 +000066 FileID MainFileID;
Chris Lattnerf3a59a12007-12-02 01:13:47 +000067 const char *MainFileStart, *MainFileEnd;
Chris Lattner0bd1c972007-10-16 21:07:07 +000068 SourceLocation LastIncLoc;
Mike Stump11289f42009-09-09 15:08:12 +000069
Ted Kremenek1b0ea822008-01-07 19:49:32 +000070 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
71 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
72 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Naroff13e74872008-05-06 18:26:51 +000073 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremenek1b0ea822008-01-07 19:49:32 +000074 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
75 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +000076 llvm::SmallVector<Stmt *, 32> Stmts;
77 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffd9803712009-04-29 16:37:50 +000078 // Remember all the @protocol(<expr>) expressions.
79 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahaniane3891582010-01-05 18:04:40 +000080
81 llvm::DenseSet<uint64_t> CopyDestroyCache;
82
Steve Naroffce8e8862008-03-15 00:55:56 +000083 unsigned NumObjCStringLiterals;
Mike Stump11289f42009-09-09 15:08:12 +000084
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000085 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff7fa2f042007-11-15 10:28:18 +000086 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +000087 FunctionDecl *MsgSendStretFunctionDecl;
88 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanian4f76f222007-12-03 21:26:48 +000089 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000090 FunctionDecl *GetClassFunctionDecl;
Steve Naroffb2f8ff12007-12-07 03:50:46 +000091 FunctionDecl *GetMetaClassFunctionDecl;
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.
142 llvm::DenseMap<ObjCPropertyRefExpr *, 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).
145 llvm::DenseMap<ObjCPropertyRefExpr *, 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
Fariborz Jahanian93191af2007-10-18 19:23:00 +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) {
198 // Measaure the old text.
199 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 RemoveText(SourceLocation Loc, unsigned StrLen) {
233 // If removal succeeded or warning disabled return with no warning.
234 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
235 return;
Mike Stump11289f42009-09-09 15:08:12 +0000236
Chris Lattner9cc55f52008-01-31 19:51:04 +0000237 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
238 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000239
Chris Lattner9cc55f52008-01-31 19:51:04 +0000240 void ReplaceText(SourceLocation Start, unsigned OrigLength,
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000241 llvm::StringRef Str) {
Chris Lattner9cc55f52008-01-31 19:51:04 +0000242 // If removal succeeded or warning disabled return with no warning.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000243 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
Chris Lattner9cc55f52008-01-31 19:51:04 +0000244 SilenceRewriteMacroWarning)
245 return;
Mike Stump11289f42009-09-09 15:08:12 +0000246
Chris Lattner9cc55f52008-01-31 19:51:04 +0000247 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
248 }
Mike Stump11289f42009-09-09 15:08:12 +0000249
Chris Lattner3c799d72007-10-24 17:06:59 +0000250 // Syntactic Rewriting.
Steve Narofff36987c2007-11-04 22:37:50 +0000251 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000252 void RewriteInclude();
Chris Lattner3c799d72007-10-24 17:06:59 +0000253 void RewriteTabs();
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000254 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffc038b3a2008-12-02 17:36:43 +0000255 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
256 ObjCImplementationDecl *IMD,
257 ObjCCategoryImplDecl *CID);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000258 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000259 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000260 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000261 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
262 const FunctionType *&FPRetType);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +0000263 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
264 ValueDecl *VD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000265 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
266 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
267 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
268 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000269 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000270 void RewriteFunctionDecl(FunctionDecl *FD);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000271 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000272 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +0000273 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff873bd842008-07-29 18:15:38 +0000274 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroff50d42052007-11-01 13:24:47 +0000275 bool needToScanForQualifiers(QualType T);
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +0000276 bool isSuperReceiver(Expr *recExpr);
Steve Naroff7fa2f042007-11-15 10:28:18 +0000277 QualType getSuperStructType();
Steve Naroffce8e8862008-03-15 00:55:56 +0000278 QualType getConstantStringStructType();
Fariborz Jahanian19c62402010-05-25 15:56:08 +0000279 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
Steve Naroffcd92aeb2008-05-31 14:15:04 +0000280 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump11289f42009-09-09 15:08:12 +0000281
Chris Lattner3c799d72007-10-24 17:06:59 +0000282 // Expression Rewriting.
Steve Naroff20113382007-11-09 15:20:18 +0000283 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroff4588d0f2008-12-04 16:24:46 +0000284 void CollectPropertySetters(Stmt *S);
Mike Stump11289f42009-09-09 15:08:12 +0000285
Steve Naroff1042ff32008-12-08 16:43:47 +0000286 Stmt *CurrentBody;
287 ParentMap *PropParentMap; // created lazily.
Mike Stump11289f42009-09-09 15:08:12 +0000288
Chris Lattner69534692007-10-24 16:57:36 +0000289 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +0000290 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart,
291 bool &replaced);
292 Stmt *RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced);
Steve Naroff4588d0f2008-12-04 16:24:46 +0000293 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Mike Stump11289f42009-09-09 15:08:12 +0000294 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroff08628db2008-12-09 12:56:34 +0000295 SourceRange SrcRange);
Steve Naroffe4f9b232007-11-05 14:50:49 +0000296 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner69534692007-10-24 16:57:36 +0000297 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffa397efd2007-11-03 11:27:19 +0000298 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian33c0e812007-12-07 18:47:10 +0000299 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffec60b432009-12-05 21:43:12 +0000300 void WarnAboutReturnGotoStmts(Stmt *S);
301 void HasReturnStmts(Stmt *S, bool &hasReturns);
302 void RewriteTryReturnStmts(Stmt *S);
303 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000304 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian284011b2008-01-29 22:59:37 +0000305 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000306 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
307 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
308 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattnera779d692008-01-31 05:10:40 +0000309 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
310 SourceLocation OrigEnd);
Mike Stump11289f42009-09-09 15:08:12 +0000311 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +0000312 Expr **args, unsigned nargs,
313 SourceLocation StartLoc=SourceLocation(),
314 SourceLocation EndLoc=SourceLocation());
315 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
316 SourceLocation StartLoc=SourceLocation(),
317 SourceLocation EndLoc=SourceLocation());
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +0000318 Stmt *RewriteBreakStmt(BreakStmt *S);
319 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian965a8962008-01-08 22:06:28 +0000320 void SynthCountByEnumWithState(std::string &buf);
Mike Stump11289f42009-09-09 15:08:12 +0000321
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000322 void SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +0000323 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000324 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +0000325 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000326 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000327 void SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +0000328 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +0000329 void SynthGetSuperClassFunctionDecl();
Fariborz Jahanian31e18502007-12-04 21:47:40 +0000330 void SynthSelGetUidFunctionDecl();
Steve Naroff17978c42008-03-11 17:37:02 +0000331 void SynthSuperContructorFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000332
Chris Lattner3c799d72007-10-24 17:06:59 +0000333 // Metadata emission.
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000334 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000335 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000336
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000337 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000338 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000339
Douglas Gregor29bd76f2009-04-23 01:02:12 +0000340 template<typename MethodIterator>
341 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
342 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +0000343 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +0000344 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +0000345 const char *ClassName,
346 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000347
Steve Naroffd9803712009-04-29 16:37:50 +0000348 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
349 const char *prefix,
350 const char *ClassName,
351 std::string &Result);
352 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Mike Stump11289f42009-09-09 15:08:12 +0000353 const char *prefix,
Steve Naroffd9803712009-04-29 16:37:50 +0000354 const char *ClassName,
355 std::string &Result);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000356 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000357 std::string &Result);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000358 void SynthesizeIvarOffsetComputation(ObjCContainerDecl *IDecl,
Mike Stump11289f42009-09-09 15:08:12 +0000359 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000360 std::string &Result);
Steve Narofff8cfd162008-11-13 20:07:04 +0000361 void RewriteImplementations();
362 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000363
Steve Naroff677ab3a2008-10-27 17:20:55 +0000364 // Block rewriting.
Mike Stump11289f42009-09-09 15:08:12 +0000365 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000366 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump11289f42009-09-09 15:08:12 +0000367
Steve Naroff677ab3a2008-10-27 17:20:55 +0000368 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
369 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump11289f42009-09-09 15:08:12 +0000370
371 // Block specific rewrite rules.
Steve Naroff677ab3a2008-10-27 17:20:55 +0000372 void RewriteBlockCall(CallExpr *Exp);
373 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000374 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahaniane3891582010-01-05 18:04:40 +0000375 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +0000376 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +0000377 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000378 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump11289f42009-09-09 15:08:12 +0000379
380 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Steve Naroff677ab3a2008-10-27 17:20:55 +0000381 const char *funcName, std::string Tag);
Mike Stump11289f42009-09-09 15:08:12 +0000382 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Steve Naroff677ab3a2008-10-27 17:20:55 +0000383 const char *funcName, std::string Tag);
Steve Naroff30484702009-12-06 21:14:13 +0000384 std::string SynthesizeBlockImpl(BlockExpr *CE,
385 std::string Tag, std::string Desc);
386 std::string SynthesizeBlockDescriptor(std::string DescTag,
387 std::string ImplTag,
388 int i, const char *funcName,
389 unsigned hasCopy);
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +0000390 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000391 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000392 const char *FunName);
Steve Naroffe70a52a2009-12-05 15:55:59 +0000393 void RewriteRecordBody(RecordDecl *RD);
Mike Stump11289f42009-09-09 15:08:12 +0000394
Steve Naroff677ab3a2008-10-27 17:20:55 +0000395 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000396 void GetBlockDeclRefExprs(Stmt *S);
Fariborz Jahanian8652be02010-02-24 22:48:18 +0000397 void GetInnerBlockDeclRefExprs(Stmt *S,
398 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +0000399 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
Mike Stump11289f42009-09-09 15:08:12 +0000400
Steve Naroff677ab3a2008-10-27 17:20:55 +0000401 // We avoid calling Type::isBlockPointerType(), since it operates on the
402 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek5a201952009-02-07 01:47:29 +0000403 bool isTopLevelBlockPointerType(QualType T) {
404 return isa<BlockPointerType>(T);
405 }
Mike Stump11289f42009-09-09 15:08:12 +0000406
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +0000407 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
408 /// to a function pointer type and upon success, returns true; false
409 /// otherwise.
410 bool convertBlockPointerToFunctionPointer(QualType &T) {
411 if (isTopLevelBlockPointerType(T)) {
412 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
413 T = Context->getPointerType(BPT->getPointeeType());
414 return true;
415 }
416 return false;
417 }
418
Steve Naroff677ab3a2008-10-27 17:20:55 +0000419 // FIXME: This predicate seems like it would be useful to add to ASTContext.
420 bool isObjCType(QualType T) {
421 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
422 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000423
Steve Naroff677ab3a2008-10-27 17:20:55 +0000424 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000425
Steve Naroff677ab3a2008-10-27 17:20:55 +0000426 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
427 OCT == Context->getCanonicalType(Context->getObjCClassType()))
428 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000429
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000430 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +0000431 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Narofffb4330f2009-06-17 22:40:22 +0000432 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff677ab3a2008-10-27 17:20:55 +0000433 return true;
434 }
435 return false;
436 }
437 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek5a201952009-02-07 01:47:29 +0000438 void GetExtentOfArgList(const char *Name, const char *&LParen,
439 const char *&RParen);
Steve Naroffc989a7b2008-11-03 23:29:32 +0000440 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump11289f42009-09-09 15:08:12 +0000441
Steve Narofff4b992a2008-10-28 20:29:00 +0000442 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Fariborz Jahanian8652be02010-02-24 22:48:18 +0000443 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
444 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs);
Mike Stump11289f42009-09-09 15:08:12 +0000445
Steve Naroffd9803712009-04-29 16:37:50 +0000446 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump11289f42009-09-09 15:08:12 +0000447 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroffd9803712009-04-29 16:37:50 +0000448 if (From[i] == '"')
449 To += "\\\"";
450 else
451 To += From[i];
452 }
453 }
Chris Lattnere99c8322007-10-11 00:43:27 +0000454 };
John McCall97513962010-01-15 18:39:57 +0000455
456 // Helper function: create a CStyleCastExpr with trivial type source info.
457 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
458 CastExpr::CastKind Kind, Expr *E) {
459 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
Anders Carlsson5d270e82010-04-24 18:38:56 +0000460 return new (Ctx) CStyleCastExpr(Ty, Kind, E, CXXBaseSpecifierArray(), TInfo,
John McCall97513962010-01-15 18:39:57 +0000461 SourceLocation(), SourceLocation());
462 }
Chris Lattnere99c8322007-10-11 00:43:27 +0000463}
464
Mike Stump11289f42009-09-09 15:08:12 +0000465void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
466 NamedDecl *D) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000467 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000468 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +0000469 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +0000470 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +0000471 // All the args are checked/rewritten. Don't call twice!
472 RewriteBlockPointerDecl(D);
473 break;
474 }
475 }
476}
477
478void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000479 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +0000480 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000481 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000482}
483
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000484static bool IsHeaderFile(const std::string &Filename) {
485 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump11289f42009-09-09 15:08:12 +0000486
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000487 if (DotPos == std::string::npos) {
488 // no file extension
Mike Stump11289f42009-09-09 15:08:12 +0000489 return false;
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000490 }
Mike Stump11289f42009-09-09 15:08:12 +0000491
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000492 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
493 // C header: .h
494 // C++ header: .hh or .H;
495 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump11289f42009-09-09 15:08:12 +0000496}
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000497
Eli Friedman94cf21e2009-05-18 22:20:00 +0000498RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000499 Diagnostic &D, const LangOptions &LOpts,
500 bool silenceMacroWarn)
501 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
502 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Narofff9e7c902008-03-28 22:26:09 +0000503 IsHeader = IsHeaderFile(inFile);
Mike Stump11289f42009-09-09 15:08:12 +0000504 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Narofff9e7c902008-03-28 22:26:09 +0000505 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump11289f42009-09-09 15:08:12 +0000506 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek5a201952009-02-07 01:47:29 +0000507 "rewriter doesn't support user-specified control flow semantics "
508 "for @try/@finally (code may not execute properly)");
Steve Narofff9e7c902008-03-28 22:26:09 +0000509}
510
Eli Friedmana63ab2d2009-05-18 22:29:17 +0000511ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
512 llvm::raw_ostream* OS,
Mike Stump11289f42009-09-09 15:08:12 +0000513 Diagnostic &Diags,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000514 const LangOptions &LOpts,
515 bool SilenceRewriteMacroWarning) {
516 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere9c810c2007-11-30 22:25:36 +0000517}
Chris Lattnere99c8322007-10-11 00:43:27 +0000518
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000519void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner187f6262008-01-31 19:38:44 +0000520 Context = &context;
521 SM = &Context->getSourceManager();
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +0000522 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner187f6262008-01-31 19:38:44 +0000523 MsgSendFunctionDecl = 0;
524 MsgSendSuperFunctionDecl = 0;
525 MsgSendStretFunctionDecl = 0;
526 MsgSendSuperStretFunctionDecl = 0;
527 MsgSendFpretFunctionDecl = 0;
528 GetClassFunctionDecl = 0;
529 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +0000530 GetSuperClassFunctionDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000531 SelGetUidFunctionDecl = 0;
532 CFStringFunctionDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000533 ConstantStringClassReference = 0;
534 NSStringRecord = 0;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000535 CurMethodDef = 0;
536 CurFunctionDef = 0;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000537 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000538 GlobalVarDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000539 SuperStructDecl = 0;
Steve Naroffd9803712009-04-29 16:37:50 +0000540 ProtocolTypeDecl = 0;
Steve Naroff60a9ef62008-03-27 22:59:54 +0000541 ConstantStringDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000542 BcLabelCount = 0;
Steve Naroff17978c42008-03-11 17:37:02 +0000543 SuperContructorFunctionDecl = 0;
Steve Naroffce8e8862008-03-15 00:55:56 +0000544 NumObjCStringLiterals = 0;
Steve Narofff1ab6002008-12-08 20:01:41 +0000545 PropParentMap = 0;
546 CurrentBody = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000547 DisableReplaceStmt = false;
Fariborz Jahanianbc6811c2010-01-07 22:51:18 +0000548 objc_impl_method = false;
Mike Stump11289f42009-09-09 15:08:12 +0000549
Chris Lattner187f6262008-01-31 19:38:44 +0000550 // Get the ID and start/end of the main file.
551 MainFileID = SM->getMainFileID();
552 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
553 MainFileStart = MainBuf->getBufferStart();
554 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000555
Chris Lattner184e65d2009-04-14 23:22:57 +0000556 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump11289f42009-09-09 15:08:12 +0000557
Chris Lattner187f6262008-01-31 19:38:44 +0000558 // declaring objc_selector outside the parameter list removes a silly
559 // scope related warning...
Steve Naroff00a31762008-03-27 22:29:16 +0000560 if (IsHeader)
Steve Narofffcc6fd52009-02-03 20:39:18 +0000561 Preamble = "#pragma once\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000562 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff6ab6dc72008-12-23 20:11:22 +0000563 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroff00a31762008-03-27 22:29:16 +0000564 Preamble += "struct objc_object *superClass; ";
Steve Naroff17978c42008-03-11 17:37:02 +0000565 if (LangOpts.Microsoft) {
566 // Add a constructor for creating temporary objects.
Ted Kremenek5a201952009-02-07 01:47:29 +0000567 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
568 ": ";
Steve Naroff00a31762008-03-27 22:29:16 +0000569 Preamble += "object(o), superClass(s) {} ";
Steve Naroff17978c42008-03-11 17:37:02 +0000570 }
Steve Naroff00a31762008-03-27 22:29:16 +0000571 Preamble += "};\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000572 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
573 Preamble += "typedef struct objc_object Protocol;\n";
574 Preamble += "#define _REWRITER_typedef_Protocol\n";
575 Preamble += "#endif\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000576 if (LangOpts.Microsoft) {
577 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
578 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
579 } else
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000580 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000581 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroff00a31762008-03-27 22:29:16 +0000582 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000583 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroff00a31762008-03-27 22:29:16 +0000584 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000585 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000586 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000587 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000588 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000589 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroff00a31762008-03-27 22:29:16 +0000590 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000591 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000592 Preamble += "(const char *);\n";
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +0000593 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
594 Preamble += "(struct objc_class *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000595 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000596 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000597 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
598 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
599 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
600 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
601 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroffd30f8c52008-05-09 21:17:56 +0000602 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff8dd15252008-07-16 18:58:11 +0000603 // @synchronized hooks.
Steve Narofff122ff02008-12-08 17:30:33 +0000604 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
605 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
606 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000607 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
608 Preamble += "struct __objcFastEnumerationState {\n\t";
609 Preamble += "unsigned long state;\n\t";
Steve Naroff4dbab8a2008-04-04 22:58:22 +0000610 Preamble += "void **itemsPtr;\n\t";
Steve Naroff00a31762008-03-27 22:29:16 +0000611 Preamble += "unsigned long *mutationsPtr;\n\t";
612 Preamble += "unsigned long extra[5];\n};\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000613 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000614 Preamble += "#define __FASTENUMERATIONSTATE\n";
615 Preamble += "#endif\n";
616 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
617 Preamble += "struct __NSConstantStringImpl {\n";
618 Preamble += " int *isa;\n";
619 Preamble += " int flags;\n";
620 Preamble += " char *str;\n";
621 Preamble += " long length;\n";
622 Preamble += "};\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000623 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
624 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
625 Preamble += "#else\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000626 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000627 Preamble += "#endif\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000628 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
629 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000630 // Blocks preamble.
631 Preamble += "#ifndef BLOCK_IMPL\n";
632 Preamble += "#define BLOCK_IMPL\n";
633 Preamble += "struct __block_impl {\n";
634 Preamble += " void *isa;\n";
635 Preamble += " int Flags;\n";
Steve Naroff30484702009-12-06 21:14:13 +0000636 Preamble += " int Reserved;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000637 Preamble += " void *FuncPtr;\n";
638 Preamble += "};\n";
Steve Naroff61d879e2008-12-16 15:50:30 +0000639 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroff287a2bf2009-12-06 01:52:22 +0000640 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000641 Preamble += "extern \"C\" __declspec(dllexport) "
642 "void _Block_object_assign(void *, const void *, const int);\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000643 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
644 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
645 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
646 Preamble += "#else\n";
Steve Naroff7bf01ea2010-01-05 18:09:31 +0000647 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
648 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000649 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
650 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
651 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000652 Preamble += "#endif\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000653 if (LangOpts.Microsoft) {
Steve Narofff122ff02008-12-08 17:30:33 +0000654 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
655 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Chris Lattner8d269dc2010-04-13 17:33:56 +0000656 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
Steve Naroffcb04e882008-10-27 18:50:14 +0000657 Preamble += "#define __attribute__(X)\n";
Chris Lattner8d269dc2010-04-13 17:33:56 +0000658 Preamble += "#endif\n";
Fariborz Jahanianf0462ff2010-01-15 22:29:39 +0000659 Preamble += "#define __weak\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000660 }
Fariborz Jahanian7fac6552010-01-05 19:21:35 +0000661 else {
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000662 Preamble += "#define __block\n";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +0000663 Preamble += "#define __weak\n";
664 }
Fariborz Jahaniandb217c42010-03-02 01:19:04 +0000665 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
666 // as this avoids warning in any 64bit/32bit compilation model.
667 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
Chris Lattner187f6262008-01-31 19:38:44 +0000668}
669
670
Chris Lattner3c799d72007-10-24 17:06:59 +0000671//===----------------------------------------------------------------------===//
672// Top Level Driver Code
673//===----------------------------------------------------------------------===//
674
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000675void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremenek31e7f0f2010-02-05 21:28:51 +0000676 if (Diags.hasErrorOccurred())
677 return;
678
Chris Lattner0bd1c972007-10-16 21:07:07 +0000679 // Two cases: either the decl could be in the main file, or it could be in a
680 // #included file. If the former, rewrite it now. If the later, check to see
681 // if we rewrote the #include/#import.
682 SourceLocation Loc = D->getLocation();
Chris Lattner8a425862009-01-16 07:36:28 +0000683 Loc = SM->getInstantiationLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000684
Chris Lattner0bd1c972007-10-16 21:07:07 +0000685 // If this is for a builtin, ignore it.
686 if (Loc.isInvalid()) return;
687
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000688 // Look for built-in declarations that we need to refer during the rewrite.
689 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000690 RewriteFunctionDecl(FD);
Steve Naroff08899ff2008-04-15 22:42:06 +0000691 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000692 // declared in <Foundation/NSString.h>
Chris Lattner86d7d912008-11-24 03:54:41 +0000693 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000694 ConstantStringClassReference = FVD;
695 return;
696 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000697 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff161a92b2007-10-26 20:53:56 +0000698 RewriteInterfaceDecl(MD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000699 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000700 RewriteCategoryDecl(CD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000701 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff921385f2007-10-30 16:42:30 +0000702 RewriteProtocolDecl(PD);
Mike Stump11289f42009-09-09 15:08:12 +0000703 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000704 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000705 RewriteForwardProtocolDecl(FP);
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000706 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
707 // Recurse into linkage specifications
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000708 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
709 DIEnd = LSD->decls_end();
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000710 DI != DIEnd; ++DI)
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000711 HandleTopLevelSingleDecl(*DI);
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000712 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000713 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekd61ed3b2008-04-14 21:24:13 +0000714 if (SM->isFromMainFile(Loc))
Chris Lattner0bd1c972007-10-16 21:07:07 +0000715 return HandleDeclInMainFile(D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000716}
717
Chris Lattner3c799d72007-10-24 17:06:59 +0000718//===----------------------------------------------------------------------===//
719// Syntactic (non-AST) Rewriting Code
720//===----------------------------------------------------------------------===//
721
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000722void RewriteObjC::RewriteInclude() {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000723 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000724 llvm::StringRef MainBuf = SM->getBufferData(MainFileID);
725 const char *MainBufStart = MainBuf.begin();
726 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian80258362008-01-19 00:30:35 +0000727 size_t ImportLen = strlen("import");
Mike Stump11289f42009-09-09 15:08:12 +0000728
Fariborz Jahanian137d6932008-01-19 01:03:17 +0000729 // Loop over the whole file, looking for includes.
Fariborz Jahanian80258362008-01-19 00:30:35 +0000730 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
731 if (*BufPtr == '#') {
732 if (++BufPtr == MainBufEnd)
733 return;
734 while (*BufPtr == ' ' || *BufPtr == '\t')
735 if (++BufPtr == MainBufEnd)
736 return;
737 if (!strncmp(BufPtr, "import", ImportLen)) {
738 // replace import with include
Mike Stump11289f42009-09-09 15:08:12 +0000739 SourceLocation ImportLoc =
Fariborz Jahanian80258362008-01-19 00:30:35 +0000740 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000741 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian80258362008-01-19 00:30:35 +0000742 BufPtr += ImportLen;
743 }
744 }
745 }
Chris Lattner0bd1c972007-10-16 21:07:07 +0000746}
747
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000748void RewriteObjC::RewriteTabs() {
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000749 llvm::StringRef MainBuf = SM->getBufferData(MainFileID);
750 const char *MainBufStart = MainBuf.begin();
751 const char *MainBufEnd = MainBuf.end();
Mike Stump11289f42009-09-09 15:08:12 +0000752
Chris Lattner3c799d72007-10-24 17:06:59 +0000753 // Loop over the whole file, looking for tabs.
754 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
755 if (*BufPtr != '\t')
756 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000757
Chris Lattner3c799d72007-10-24 17:06:59 +0000758 // Okay, we found a tab. This tab will turn into at least one character,
759 // but it depends on which 'virtual column' it is in. Compute that now.
760 unsigned VCol = 0;
761 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
762 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
763 ++VCol;
Mike Stump11289f42009-09-09 15:08:12 +0000764
Chris Lattner3c799d72007-10-24 17:06:59 +0000765 // Okay, now that we know the virtual column, we know how many spaces to
766 // insert. We assume 8-character tab-stops.
767 unsigned Spaces = 8-(VCol & 7);
Mike Stump11289f42009-09-09 15:08:12 +0000768
Chris Lattner3c799d72007-10-24 17:06:59 +0000769 // Get the location of the tab.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000770 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
771 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Mike Stump11289f42009-09-09 15:08:12 +0000772
Chris Lattner3c799d72007-10-24 17:06:59 +0000773 // Rewrite the single tab character into a sequence of spaces.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000774 ReplaceText(TabLoc, 1, llvm::StringRef(" ", Spaces));
Chris Lattner3c799d72007-10-24 17:06:59 +0000775 }
Chris Lattner16a0de42007-10-11 18:38:32 +0000776}
777
Steve Naroff9af94912008-12-02 15:48:25 +0000778static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
779 ObjCIvarDecl *OID) {
780 std::string S;
781 S = "((struct ";
782 S += ClassDecl->getIdentifier()->getName();
783 S += "_IMPL *)self)->";
Daniel Dunbar70e7ead2009-10-18 20:26:27 +0000784 S += OID->getName();
Steve Naroff9af94912008-12-02 15:48:25 +0000785 return S;
786}
787
Steve Naroffc038b3a2008-12-02 17:36:43 +0000788void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
789 ObjCImplementationDecl *IMD,
790 ObjCCategoryImplDecl *CID) {
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000791 static bool objcGetPropertyDefined = false;
792 static bool objcSetPropertyDefined = false;
Steve Naroffe1908e32008-12-01 20:33:01 +0000793 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000794 InsertText(startLoc, "// ");
Steve Naroff9af94912008-12-02 15:48:25 +0000795 const char *startBuf = SM->getCharacterData(startLoc);
796 assert((*startBuf == '@') && "bogus @synthesize location");
797 const char *semiBuf = strchr(startBuf, ';');
798 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek5a201952009-02-07 01:47:29 +0000799 SourceLocation onePastSemiLoc =
800 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroff9af94912008-12-02 15:48:25 +0000801
802 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
803 return; // FIXME: is this correct?
Mike Stump11289f42009-09-09 15:08:12 +0000804
Steve Naroff9af94912008-12-02 15:48:25 +0000805 // Generate the 'getter' function.
Steve Naroff9af94912008-12-02 15:48:25 +0000806 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroff9af94912008-12-02 15:48:25 +0000807 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroff9af94912008-12-02 15:48:25 +0000808 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000809
Steve Naroff003d00e2008-12-02 16:05:55 +0000810 if (!OID)
811 return;
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000812 unsigned Attributes = PD->getPropertyAttributes();
813 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
814 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
815 ObjCPropertyDecl::OBJC_PR_copy));
Steve Naroff003d00e2008-12-02 16:05:55 +0000816 std::string Getr;
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000817 if (GenGetProperty && !objcGetPropertyDefined) {
818 objcGetPropertyDefined = true;
819 // FIXME. Is this attribute correct in all cases?
820 Getr = "\nextern \"C\" __declspec(dllimport) "
821 "id objc_getProperty(id, SEL, long, bool);\n";
822 }
Steve Naroff003d00e2008-12-02 16:05:55 +0000823 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
824 Getr += "{ ";
825 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroff06297042008-12-02 17:54:50 +0000826 // See objc-act.c:objc_synthesize_new_getter() for details.
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000827 if (GenGetProperty) {
828 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
829 Getr += "typedef ";
830 const FunctionType *FPRetType = 0;
831 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
832 FPRetType);
833 Getr += " _TYPE";
834 if (FPRetType) {
835 Getr += ")"; // close the precedence "scope" for "*".
836
837 // Now, emit the argument types (if any).
838 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
839 Getr += "(";
840 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
841 if (i) Getr += ", ";
842 std::string ParamStr = FT->getArgType(i).getAsString();
843 Getr += ParamStr;
844 }
845 if (FT->isVariadic()) {
846 if (FT->getNumArgs()) Getr += ", ";
847 Getr += "...";
848 }
849 Getr += ")";
850 } else
851 Getr += "()";
852 }
853 Getr += ";\n";
854 Getr += "return (_TYPE)";
855 Getr += "objc_getProperty(self, _cmd, ";
856 SynthesizeIvarOffsetComputation(ClassDecl, OID, Getr);
857 Getr += ", 1)";
858 }
859 else
860 Getr += "return " + getIvarAccessString(ClassDecl, OID);
Steve Naroff003d00e2008-12-02 16:05:55 +0000861 Getr += "; }";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000862 InsertText(onePastSemiLoc, Getr);
Steve Naroff9af94912008-12-02 15:48:25 +0000863 if (PD->isReadOnly())
864 return;
Mike Stump11289f42009-09-09 15:08:12 +0000865
Steve Naroff9af94912008-12-02 15:48:25 +0000866 // Generate the 'setter' function.
867 std::string Setr;
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000868 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
869 ObjCPropertyDecl::OBJC_PR_copy);
870 if (GenSetProperty && !objcSetPropertyDefined) {
871 objcSetPropertyDefined = true;
872 // FIXME. Is this attribute correct in all cases?
873 Setr = "\nextern \"C\" __declspec(dllimport) "
874 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
875 }
876
Steve Naroff9af94912008-12-02 15:48:25 +0000877 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroff9af94912008-12-02 15:48:25 +0000878 Setr += "{ ";
Steve Naroff003d00e2008-12-02 16:05:55 +0000879 // Synthesize an explicit cast to initialize the ivar.
Steve Narofff326f402008-12-03 00:56:33 +0000880 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000881 if (GenSetProperty) {
882 Setr += "objc_setProperty (self, _cmd, ";
883 SynthesizeIvarOffsetComputation(ClassDecl, OID, Setr);
884 Setr += ", (id)";
885 Setr += PD->getNameAsCString();
886 Setr += ", ";
887 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
888 Setr += "0, ";
889 else
890 Setr += "1, ";
891 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
892 Setr += "1)";
893 else
894 Setr += "0)";
895 }
896 else {
897 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
898 Setr += PD->getNameAsCString();
899 }
Steve Naroff003d00e2008-12-02 16:05:55 +0000900 Setr += "; }";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000901 InsertText(onePastSemiLoc, Setr);
Steve Naroffe1908e32008-12-01 20:33:01 +0000902}
Chris Lattner16a0de42007-10-11 18:38:32 +0000903
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000904void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattner3c799d72007-10-24 17:06:59 +0000905 // Get the start location and compute the semi location.
906 SourceLocation startLoc = ClassDecl->getLocation();
907 const char *startBuf = SM->getCharacterData(startLoc);
908 const char *semiPtr = strchr(startBuf, ';');
Mike Stump11289f42009-09-09 15:08:12 +0000909
Chris Lattner3c799d72007-10-24 17:06:59 +0000910 // Translate to typedef's that forward reference structs with the same name
911 // as the class. As a convenience, we include the original declaration
912 // as a comment.
913 std::string typedefString;
Fariborz Jahanian1c2cb6d2010-01-11 22:48:40 +0000914 typedefString += "// @class ";
915 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
916 I != E; ++I) {
917 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
918 typedefString += ForwardDecl->getNameAsString();
919 if (I+1 != E)
920 typedefString += ", ";
921 else
922 typedefString += ";\n";
923 }
924
Chris Lattner9ee23b72009-02-20 18:04:31 +0000925 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
926 I != E; ++I) {
Ted Kremenek9b124e12009-11-18 00:28:11 +0000927 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff1b232132007-11-09 12:50:28 +0000928 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000929 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000930 typedefString += "\n";
931 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000932 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000933 typedefString += "\n";
Steve Naroff98eb8d12007-11-05 14:36:37 +0000934 typedefString += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000935 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000936 typedefString += ";\n#endif\n";
Steve Naroff574440f2007-10-24 22:48:43 +0000937 }
Mike Stump11289f42009-09-09 15:08:12 +0000938
Steve Naroff574440f2007-10-24 22:48:43 +0000939 // Replace the @class with typedefs corresponding to the classes.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000940 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
Chris Lattner3c799d72007-10-24 17:06:59 +0000941}
942
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000943void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000944 // When method is a synthesized one, such as a getter/setter there is
945 // nothing to rewrite.
946 if (Method->isSynthesized())
947 return;
Steve Naroff3ce37a62007-12-14 23:37:57 +0000948 SourceLocation LocStart = Method->getLocStart();
949 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000950
Chris Lattner88ea93e2009-02-04 01:06:56 +0000951 if (SM->getInstantiationLineNumber(LocEnd) >
952 SM->getInstantiationLineNumber(LocStart)) {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000953 InsertText(LocStart, "#if 0\n");
954 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff3ce37a62007-12-14 23:37:57 +0000955 } else {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000956 InsertText(LocStart, "// ");
Steve Naroff5448cf62007-10-30 13:30:57 +0000957 }
958}
959
Mike Stump11289f42009-09-09 15:08:12 +0000960void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000961 SourceLocation Loc = prop->getAtLoc();
Mike Stump11289f42009-09-09 15:08:12 +0000962
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000963 ReplaceText(Loc, 0, "// ");
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000964 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahaniane8a30162007-11-07 00:09:37 +0000965}
966
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000967void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000968 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000969
Steve Naroff5448cf62007-10-30 13:30:57 +0000970 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000971 ReplaceText(LocStart, 0, "// ");
Mike Stump11289f42009-09-09 15:08:12 +0000972
Fariborz Jahanian68ebe632010-02-10 01:15:09 +0000973 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
974 E = CatDecl->prop_end(); I != E; ++I)
975 RewriteProperty(*I);
976
Mike Stump11289f42009-09-09 15:08:12 +0000977 for (ObjCCategoryDecl::instmeth_iterator
978 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000979 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000980 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +0000981 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000982 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000983 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000984 RewriteMethodDeclaration(*I);
985
Steve Naroff5448cf62007-10-30 13:30:57 +0000986 // Lastly, comment out the @end.
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +0000987 ReplaceText(CatDecl->getAtEndRange().getBegin(),
988 strlen("@end"), "/* @end */");
Steve Naroff5448cf62007-10-30 13:30:57 +0000989}
990
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000991void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Narofff921385f2007-10-30 16:42:30 +0000992 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000993
Steve Narofff921385f2007-10-30 16:42:30 +0000994 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000995 ReplaceText(LocStart, 0, "// ");
Mike Stump11289f42009-09-09 15:08:12 +0000996
997 for (ObjCProtocolDecl::instmeth_iterator
998 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000999 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001000 RewriteMethodDeclaration(*I);
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001001 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001002 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001003 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001004 RewriteMethodDeclaration(*I);
1005
Steve Narofff921385f2007-10-30 16:42:30 +00001006 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +00001007 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +00001008 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroffa509f042007-11-14 15:03:57 +00001009
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +00001010 // Must comment out @optional/@required
1011 const char *startBuf = SM->getCharacterData(LocStart);
1012 const char *endBuf = SM->getCharacterData(LocEnd);
1013 for (const char *p = startBuf; p < endBuf; p++) {
1014 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Steve Naroffa509f042007-11-14 15:03:57 +00001015 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001016 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump11289f42009-09-09 15:08:12 +00001017
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +00001018 }
1019 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Steve Naroffa509f042007-11-14 15:03:57 +00001020 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001021 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump11289f42009-09-09 15:08:12 +00001022
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +00001023 }
1024 }
Steve Narofff921385f2007-10-30 16:42:30 +00001025}
1026
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001027void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanianda6165c2007-11-14 00:42:16 +00001028 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffc17b0562007-11-14 03:37:28 +00001029 if (LocStart.isInvalid())
1030 assert(false && "Invalid SourceLocation");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +00001031 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001032 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +00001033}
1034
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001035void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1036 const FunctionType *&FPRetType) {
1037 if (T->isObjCQualifiedIdType())
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +00001038 ResultStr += "id";
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001039 else if (T->isFunctionPointerType() ||
1040 T->isBlockPointerType()) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001041 // needs special handling, since pointer-to-functions have special
1042 // syntax (where a decaration models use).
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001043 QualType retType = T;
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001044 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001045 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001046 PointeeTy = PT->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001047 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001048 PointeeTy = BPT->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00001049 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001050 ResultStr += FPRetType->getResultType().getAsString();
1051 ResultStr += "(*";
Steve Naroffb067bbd2008-07-16 14:40:40 +00001052 }
1053 } else
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001054 ResultStr += T.getAsString();
1055}
1056
1057void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
1058 std::string &ResultStr) {
1059 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1060 const FunctionType *FPRetType = 0;
1061 ResultStr += "\nstatic ";
1062 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001063 ResultStr += " ";
Mike Stump11289f42009-09-09 15:08:12 +00001064
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001065 // Unique method name
Fariborz Jahanian56338352007-11-13 21:02:00 +00001066 std::string NameStr;
Mike Stump11289f42009-09-09 15:08:12 +00001067
Douglas Gregorffca3a22009-01-09 17:18:27 +00001068 if (OMD->isInstanceMethod())
Fariborz Jahanian56338352007-11-13 21:02:00 +00001069 NameStr += "_I_";
1070 else
1071 NameStr += "_C_";
Mike Stump11289f42009-09-09 15:08:12 +00001072
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001073 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +00001074 NameStr += "_";
Mike Stump11289f42009-09-09 15:08:12 +00001075
1076 if (ObjCCategoryImplDecl *CID =
Steve Naroff11b387f2009-01-08 19:41:02 +00001077 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001078 NameStr += CID->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +00001079 NameStr += "_";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001080 }
Mike Stump11289f42009-09-09 15:08:12 +00001081 // Append selector names, replacing ':' with '_'
Chris Lattnere4b95692008-11-24 03:33:13 +00001082 {
1083 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001084 int len = selString.size();
1085 for (int i = 0; i < len; i++)
1086 if (selString[i] == ':')
1087 selString[i] = '_';
Fariborz Jahanian56338352007-11-13 21:02:00 +00001088 NameStr += selString;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001089 }
Fariborz Jahanian56338352007-11-13 21:02:00 +00001090 // Remember this name for metadata emission
1091 MethodInternalNames[OMD] = NameStr;
1092 ResultStr += NameStr;
Mike Stump11289f42009-09-09 15:08:12 +00001093
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001094 // Rewrite arguments
1095 ResultStr += "(";
Mike Stump11289f42009-09-09 15:08:12 +00001096
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001097 // invisible arguments
Douglas Gregorffca3a22009-01-09 17:18:27 +00001098 if (OMD->isInstanceMethod()) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001099 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001100 selfTy = Context->getPointerType(selfTy);
Steve Naroffdc5b6b22008-03-12 00:25:36 +00001101 if (!LangOpts.Microsoft) {
1102 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
1103 ResultStr += "struct ";
1104 }
1105 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001106 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00001107 ResultStr += " *";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001108 }
1109 else
Steve Naroffd9803712009-04-29 16:37:50 +00001110 ResultStr += Context->getObjCClassType().getAsString();
Mike Stump11289f42009-09-09 15:08:12 +00001111
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001112 ResultStr += " self, ";
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001113 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001114 ResultStr += " _cmd";
Mike Stump11289f42009-09-09 15:08:12 +00001115
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001116 // Method arguments.
Chris Lattnera4997152009-02-20 18:43:26 +00001117 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1118 E = OMD->param_end(); PI != E; ++PI) {
1119 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001120 ResultStr += ", ";
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001121 if (PDecl->getType()->isObjCQualifiedIdType()) {
1122 ResultStr += "id ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001123 ResultStr += PDecl->getNameAsString();
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001124 } else {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001125 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00001126 QualType QT = PDecl->getType();
1127 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1128 if (convertBlockPointerToFunctionPointer(QT))
1129 QT.getAsStringInternal(Name, Context->PrintingPolicy);
1130 else
Douglas Gregor7de59662009-05-29 20:38:28 +00001131 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001132 ResultStr += Name;
1133 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001134 }
Fariborz Jahanianeab81cd2008-01-21 20:14:23 +00001135 if (OMD->isVariadic())
1136 ResultStr += ", ...";
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001137 ResultStr += ") ";
Mike Stump11289f42009-09-09 15:08:12 +00001138
Steve Naroffb067bbd2008-07-16 14:40:40 +00001139 if (FPRetType) {
1140 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump11289f42009-09-09 15:08:12 +00001141
Steve Naroffb067bbd2008-07-16 14:40:40 +00001142 // Now, emit the argument types (if any).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001143 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001144 ResultStr += "(";
1145 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1146 if (i) ResultStr += ", ";
1147 std::string ParamStr = FT->getArgType(i).getAsString();
1148 ResultStr += ParamStr;
1149 }
1150 if (FT->isVariadic()) {
1151 if (FT->getNumArgs()) ResultStr += ", ";
1152 ResultStr += "...";
1153 }
1154 ResultStr += ")";
1155 } else {
1156 ResultStr += "()";
1157 }
1158 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001159}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001160void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001161 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1162 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump11289f42009-09-09 15:08:12 +00001163
Fariborz Jahanian02d964b2010-02-15 21:11:41 +00001164 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump11289f42009-09-09 15:08:12 +00001165
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001166 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001167 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1168 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001169 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001170 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001171 ObjCMethodDecl *OMD = *I;
1172 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001173 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001174 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redla7b98a72009-04-26 20:35:05 +00001175
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001176 const char *startBuf = SM->getCharacterData(LocStart);
1177 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001178 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001179 }
Mike Stump11289f42009-09-09 15:08:12 +00001180
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001181 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001182 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1183 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001184 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001185 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001186 ObjCMethodDecl *OMD = *I;
1187 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001188 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001189 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +00001190
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001191 const char *startBuf = SM->getCharacterData(LocStart);
1192 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001193 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001194 }
Steve Naroffe1908e32008-12-01 20:33:01 +00001195 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001196 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001197 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001198 I != E; ++I) {
Steve Naroffc038b3a2008-12-02 17:36:43 +00001199 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffe1908e32008-12-01 20:33:01 +00001200 }
1201
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001202 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001203}
1204
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001205void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffc5484042007-10-30 02:23:23 +00001206 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001207 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff2f55b982007-11-01 03:35:41 +00001208 // we haven't seen a forward decl - generate a typedef.
Steve Naroff03f27672007-11-14 23:02:56 +00001209 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001210 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001211 ResultStr += "\n";
1212 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001213 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001214 ResultStr += "\n";
Steve Naroffa1e115e2008-03-10 23:16:54 +00001215 ResultStr += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001216 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001217 ResultStr += ";\n#endif\n";
Steve Naroff2f55b982007-11-01 03:35:41 +00001218 // Mark this typedef as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001219 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff2f55b982007-11-01 03:35:41 +00001220 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001221 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump11289f42009-09-09 15:08:12 +00001222
1223 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001224 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff0c0f5ba2009-01-11 01:06:09 +00001225 RewriteProperty(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001226 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001227 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001228 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001229 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001230 for (ObjCInterfaceDecl::classmeth_iterator
1231 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001232 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001233 RewriteMethodDeclaration(*I);
1234
Steve Naroff4cd61ac2007-10-30 03:43:13 +00001235 // Lastly, comment out the @end.
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +00001236 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1237 "/* @end */");
Steve Naroff161a92b2007-10-26 20:53:56 +00001238}
1239
Steve Naroff08628db2008-12-09 12:56:34 +00001240Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1241 SourceRange SrcRange) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00001242 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1243 // This allows us to reuse all the fun and games in SynthMessageExpr().
1244 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1245 ObjCMessageExpr *MsgExpr;
1246 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1247 llvm::SmallVector<Expr *, 1> ExprVec;
1248 ExprVec.push_back(newStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001249
Steve Naroff1042ff32008-12-08 16:43:47 +00001250 Stmt *Receiver = PropRefExpr->getBase();
1251 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1252 if (PRE && PropGetters[PRE]) {
1253 // This allows us to handle chain/nested property getters.
1254 Receiver = PropGetters[PRE];
1255 }
Douglas Gregor9a129192010-04-21 00:45:42 +00001256 if (isa<ObjCSuperExpr>(Receiver))
1257 MsgExpr = ObjCMessageExpr::Create(*Context,
1258 PDecl->getType().getNonReferenceType(),
1259 /*FIXME?*/SourceLocation(),
1260 Receiver->getLocStart(),
1261 /*IsInstanceSuper=*/true,
1262 cast<Expr>(Receiver)->getType(),
1263 PDecl->getSetterName(),
1264 PDecl->getSetterMethodDecl(),
1265 &ExprVec[0], 1,
1266 /*FIXME:*/SourceLocation());
1267 else
1268 MsgExpr = ObjCMessageExpr::Create(*Context,
1269 PDecl->getType().getNonReferenceType(),
1270 /*FIXME: */SourceLocation(),
1271 cast<Expr>(Receiver),
1272 PDecl->getSetterName(),
1273 PDecl->getSetterMethodDecl(),
1274 &ExprVec[0], 1,
1275 /*FIXME:*/SourceLocation());
Steve Naroff4588d0f2008-12-04 16:24:46 +00001276 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001277
Steve Naroff4588d0f2008-12-04 16:24:46 +00001278 // Now do the actual rewrite.
Steve Naroff08628db2008-12-09 12:56:34 +00001279 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffdf705772008-12-10 14:53:27 +00001280 //delete BinOp;
Ted Kremenek5a201952009-02-07 01:47:29 +00001281 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1282 // to things that stay around.
1283 Context->Deallocate(MsgExpr);
Steve Naroff4588d0f2008-12-04 16:24:46 +00001284 return ReplacingStmt;
Steve Narofff326f402008-12-03 00:56:33 +00001285}
1286
Steve Naroff4588d0f2008-12-04 16:24:46 +00001287Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Narofff326f402008-12-03 00:56:33 +00001288 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1289 // This allows us to reuse all the fun and games in SynthMessageExpr().
1290 ObjCMessageExpr *MsgExpr;
1291 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
Mike Stump11289f42009-09-09 15:08:12 +00001292
Steve Naroff1042ff32008-12-08 16:43:47 +00001293 Stmt *Receiver = PropRefExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00001294
Steve Naroff1042ff32008-12-08 16:43:47 +00001295 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1296 if (PRE && PropGetters[PRE]) {
1297 // This allows us to handle chain/nested property getters.
1298 Receiver = PropGetters[PRE];
1299 }
Douglas Gregor9a129192010-04-21 00:45:42 +00001300
1301 if (isa<ObjCSuperExpr>(Receiver))
1302 MsgExpr = ObjCMessageExpr::Create(*Context,
1303 PDecl->getType().getNonReferenceType(),
1304 /*FIXME:*/SourceLocation(),
1305 Receiver->getLocStart(),
1306 /*IsInstanceSuper=*/true,
1307 cast<Expr>(Receiver)->getType(),
1308 PDecl->getGetterName(),
1309 PDecl->getGetterMethodDecl(),
1310 0, 0,
1311 /*FIXME:*/SourceLocation());
1312 else
1313 MsgExpr = ObjCMessageExpr::Create(*Context,
1314 PDecl->getType().getNonReferenceType(),
1315 /*FIXME:*/SourceLocation(),
1316 cast<Expr>(Receiver),
1317 PDecl->getGetterName(),
1318 PDecl->getGetterMethodDecl(),
1319 0, 0,
1320 /*FIXME:*/SourceLocation());
Steve Narofff326f402008-12-03 00:56:33 +00001321
Steve Naroff22216db2008-12-04 23:50:32 +00001322 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001323
1324 if (!PropParentMap)
1325 PropParentMap = new ParentMap(CurrentBody);
1326
1327 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1328 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1329 // We stash away the ReplacingStmt since actually doing the
1330 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1331 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek5a201952009-02-07 01:47:29 +00001332 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1333 // to things that stay around.
1334 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001335 return PropRefExpr; // return the original...
1336 } else {
1337 ReplaceStmt(PropRefExpr, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001338 // delete PropRefExpr; elsewhere...
Ted Kremenek5a201952009-02-07 01:47:29 +00001339 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1340 // to things that stay around.
1341 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001342 return ReplacingStmt;
1343 }
Steve Narofff326f402008-12-03 00:56:33 +00001344}
1345
Mike Stump11289f42009-09-09 15:08:12 +00001346Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001347 SourceLocation OrigStart,
1348 bool &replaced) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001349 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001350 const Expr *BaseExpr = IV->getBase();
Steve Naroff677ab3a2008-10-27 17:20:55 +00001351 if (CurMethodDef) {
Fariborz Jahanianf9e8c2b2010-01-26 18:28:51 +00001352 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001353 ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001354 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianf0ed69c2010-01-26 20:37:44 +00001355 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Naroffb1c02372008-05-08 17:52:16 +00001356 // lookup which class implements the instance variable.
1357 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001358 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001359 clsDeclared);
Steve Naroffb1c02372008-05-08 17:52:16 +00001360 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001361
Steve Naroffb1c02372008-05-08 17:52:16 +00001362 // Synthesize an explicit cast to gain access to the ivar.
1363 std::string RecName = clsDeclared->getIdentifier()->getName();
1364 RecName += "_IMPL";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001365 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara6150c882010-05-11 21:36:43 +00001366 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001367 SourceLocation(), II);
Steve Naroffb1c02372008-05-08 17:52:16 +00001368 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1369 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall97513962010-01-15 18:39:57 +00001370 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1371 CastExpr::CK_Unknown,
1372 IV->getBase());
Steve Naroffb1c02372008-05-08 17:52:16 +00001373 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001374 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1375 IV->getBase()->getLocEnd(),
1376 castExpr);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001377 replaced = true;
Mike Stump11289f42009-09-09 15:08:12 +00001378 if (IV->isFreeIvar() &&
Steve Naroff677ab3a2008-10-27 17:20:55 +00001379 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001380 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1381 IV->getLocation(),
1382 D->getType());
Steve Naroff22216db2008-12-04 23:50:32 +00001383 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb1c02372008-05-08 17:52:16 +00001384 return ME;
Steve Naroff05caa482007-11-15 11:33:00 +00001385 }
Fariborz Jahanian81310812010-01-28 01:41:20 +00001386 // Get the new text
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001387 // Cannot delete IV->getBase(), since PE points to it.
1388 // Replace the old base with the cast. This is important when doing
1389 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001390 IV->setBase(PE);
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001391 return IV;
Steve Naroff05caa482007-11-15 11:33:00 +00001392 }
Steve Naroff24840f62008-04-18 21:55:08 +00001393 } else { // we are outside a method.
Steve Naroff29ce4e52008-05-06 23:20:07 +00001394 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump11289f42009-09-09 15:08:12 +00001395
Steve Naroff29ce4e52008-05-06 23:20:07 +00001396 // Explicit ivar refs need to have a cast inserted.
1397 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian12e2e862010-01-12 17:31:23 +00001398 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Fariborz Jahanian9146e442010-01-11 17:50:35 +00001399 ObjCInterfaceType *iFaceDecl =
1400 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001401 // lookup which class implements the instance variable.
1402 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001403 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001404 clsDeclared);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001405 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001406
Steve Naroff29ce4e52008-05-06 23:20:07 +00001407 // Synthesize an explicit cast to gain access to the ivar.
1408 std::string RecName = clsDeclared->getIdentifier()->getName();
1409 RecName += "_IMPL";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001410 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara6150c882010-05-11 21:36:43 +00001411 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001412 SourceLocation(), II);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001413 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1414 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall97513962010-01-15 18:39:57 +00001415 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1416 CastExpr::CK_Unknown,
1417 IV->getBase());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001418 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001419 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner34873d22008-05-28 16:38:23 +00001420 IV->getBase()->getLocEnd(), castExpr);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001421 replaced = true;
Steve Naroff29ce4e52008-05-06 23:20:07 +00001422 // Cannot delete IV->getBase(), since PE points to it.
1423 // Replace the old base with the cast. This is important when doing
1424 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001425 IV->setBase(PE);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001426 return IV;
1427 }
Steve Naroff05caa482007-11-15 11:33:00 +00001428 }
Steve Naroff24840f62008-04-18 21:55:08 +00001429 return IV;
Steve Narofff60782b2007-11-15 02:58:25 +00001430}
1431
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001432Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
1433 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1434 CI != E; ++CI) {
1435 if (*CI) {
1436 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1437 if (newStmt)
1438 *CI = newStmt;
1439 }
1440 }
1441 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1442 SourceRange OrigStmtRange = S->getSourceRange();
1443 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1444 replaced);
1445 return newStmt;
Fariborz Jahanian31433382010-02-05 17:48:10 +00001446 }
1447 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1448 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1449 return newStmt;
1450 }
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001451 return S;
1452}
1453
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001454/// SynthCountByEnumWithState - To print:
1455/// ((unsigned int (*)
1456/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001457/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001458/// sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001459/// "countByEnumeratingWithState:objects:count:"),
1460/// &enumState,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001461/// (id *)items, (unsigned int)16)
1462///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001463void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001464 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1465 "id *, unsigned int))(void *)objc_msgSend)";
1466 buf += "\n\t\t";
1467 buf += "((id)l_collection,\n\t\t";
1468 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1469 buf += "\n\t\t";
1470 buf += "&enumState, "
1471 "(id *)items, (unsigned int)16)";
1472}
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001473
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001474/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1475/// statement to exit to its outer synthesized loop.
1476///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001477Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001478 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1479 return S;
1480 // replace break with goto __break_label
1481 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001482
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001483 SourceLocation startLoc = S->getLocStart();
1484 buf = "goto __break_label_";
1485 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001486 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001487
1488 return 0;
1489}
1490
1491/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1492/// statement to continue with its inner synthesized loop.
1493///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001494Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001495 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1496 return S;
1497 // replace continue with goto __continue_label
1498 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001499
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001500 SourceLocation startLoc = S->getLocStart();
1501 buf = "goto __continue_label_";
1502 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001503 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump11289f42009-09-09 15:08:12 +00001504
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001505 return 0;
1506}
1507
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001508/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001509/// It rewrites:
1510/// for ( type elem in collection) { stmts; }
Mike Stump11289f42009-09-09 15:08:12 +00001511
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001512/// Into:
1513/// {
Mike Stump11289f42009-09-09 15:08:12 +00001514/// type elem;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001515/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001516/// id items[16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001517/// id l_collection = (id)collection;
Mike Stump11289f42009-09-09 15:08:12 +00001518/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001519/// objects:items count:16];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001520/// if (limit) {
1521/// unsigned long startMutations = *enumState.mutationsPtr;
1522/// do {
1523/// unsigned long counter = 0;
1524/// do {
Mike Stump11289f42009-09-09 15:08:12 +00001525/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001526/// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001527/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001528/// stmts;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001529/// __continue_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001530/// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001531/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001532/// objects:items count:16]);
1533/// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001534/// __break_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001535/// }
1536/// else
1537/// elem = nil;
1538/// }
1539///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001540Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattnera779d692008-01-31 05:10:40 +00001541 SourceLocation OrigEnd) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001542 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001543 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001544 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump11289f42009-09-09 15:08:12 +00001545 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001546 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001547
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001548 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001549 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001550 const char *elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001551 std::string elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001552 std::string buf;
1553 buf = "\n{\n\t";
1554 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1555 // type elem;
Chris Lattner529efc72009-03-28 06:33:19 +00001556 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek292b3842008-10-06 22:16:13 +00001557 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001558 if (ElementType->isObjCQualifiedIdType() ||
1559 ElementType->isObjCQualifiedInterfaceType())
1560 // Simply use 'id' for all qualified types.
1561 elementTypeAsString = "id";
1562 else
1563 elementTypeAsString = ElementType.getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001564 buf += elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001565 buf += " ";
Chris Lattner86d7d912008-11-24 03:54:41 +00001566 elementName = D->getNameAsCString();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001567 buf += elementName;
1568 buf += ";\n\t";
1569 }
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001570 else {
1571 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner86d7d912008-11-24 03:54:41 +00001572 elementName = DR->getDecl()->getNameAsCString();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001573 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1574 if (VD->getType()->isObjCQualifiedIdType() ||
1575 VD->getType()->isObjCQualifiedInterfaceType())
1576 // Simply use 'id' for all qualified types.
1577 elementTypeAsString = "id";
1578 else
1579 elementTypeAsString = VD->getType().getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001580 }
Mike Stump11289f42009-09-09 15:08:12 +00001581
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001582 // struct __objcFastEnumerationState enumState = { 0 };
1583 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1584 // id items[16];
1585 buf += "id items[16];\n\t";
1586 // id l_collection = (id)
1587 buf += "id l_collection = (id)";
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001588 // Find start location of 'collection' the hard way!
1589 const char *startCollectionBuf = startBuf;
1590 startCollectionBuf += 3; // skip 'for'
1591 startCollectionBuf = strchr(startCollectionBuf, '(');
1592 startCollectionBuf++; // skip '('
1593 // find 'in' and skip it.
1594 while (*startCollectionBuf != ' ' ||
1595 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1596 (*(startCollectionBuf+3) != ' ' &&
1597 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1598 startCollectionBuf++;
1599 startCollectionBuf += 3;
Mike Stump11289f42009-09-09 15:08:12 +00001600
1601 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001602 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001603 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001604 SourceLocation rightParenLoc = S->getRParenLoc();
1605 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1606 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001607 buf = ";\n\t";
Mike Stump11289f42009-09-09 15:08:12 +00001608
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001609 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1610 // objects:items count:16];
1611 // which is synthesized into:
Mike Stump11289f42009-09-09 15:08:12 +00001612 // unsigned int limit =
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001613 // ((unsigned int (*)
1614 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001615 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001616 // sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001617 // "countByEnumeratingWithState:objects:count:"),
1618 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001619 // (id *)items, (unsigned int)16);
1620 buf += "unsigned long limit =\n\t\t";
1621 SynthCountByEnumWithState(buf);
1622 buf += ";\n\t";
1623 /// if (limit) {
1624 /// unsigned long startMutations = *enumState.mutationsPtr;
1625 /// do {
1626 /// unsigned long counter = 0;
1627 /// do {
Mike Stump11289f42009-09-09 15:08:12 +00001628 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001629 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001630 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001631 buf += "if (limit) {\n\t";
1632 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1633 buf += "do {\n\t\t";
1634 buf += "unsigned long counter = 0;\n\t\t";
1635 buf += "do {\n\t\t\t";
1636 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1637 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1638 buf += elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001639 buf += " = (";
1640 buf += elementTypeAsString;
1641 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001642 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001643 ReplaceText(lparenLoc, 1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001644
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001645 /// __continue_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001646 /// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001647 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001648 /// objects:items count:16]);
1649 /// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001650 /// __break_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001651 /// }
1652 /// else
1653 /// elem = nil;
1654 /// }
Mike Stump11289f42009-09-09 15:08:12 +00001655 ///
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001656 buf = ";\n\t";
1657 buf += "__continue_label_";
1658 buf += utostr(ObjCBcLabelNo.back());
1659 buf += ": ;";
1660 buf += "\n\t\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001661 buf += "} while (counter < limit);\n\t";
1662 buf += "} while (limit = ";
1663 SynthCountByEnumWithState(buf);
1664 buf += ");\n\t";
1665 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001666 buf += " = ((";
1667 buf += elementTypeAsString;
1668 buf += ")0);\n\t";
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001669 buf += "__break_label_";
1670 buf += utostr(ObjCBcLabelNo.back());
1671 buf += ": ;\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001672 buf += "}\n\t";
1673 buf += "else\n\t\t";
1674 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001675 buf += " = ((";
1676 buf += elementTypeAsString;
1677 buf += ")0);\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001678 buf += "}\n";
Mike Stump11289f42009-09-09 15:08:12 +00001679
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001680 // Insert all these *after* the statement body.
Sebastian Redla7b98a72009-04-26 20:35:05 +00001681 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Narofff0ff8792008-07-21 18:26:02 +00001682 if (isa<CompoundStmt>(S->getBody())) {
1683 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001684 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001685 } else {
1686 /* Need to treat single statements specially. For example:
1687 *
1688 * for (A *a in b) if (stuff()) break;
1689 * for (A *a in b) xxxyy;
1690 *
1691 * The following code simply scans ahead to the semi to find the actual end.
1692 */
1693 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1694 const char *semiBuf = strchr(stmtBuf, ';');
1695 assert(semiBuf && "Can't find ';'");
1696 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001697 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001698 }
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001699 Stmts.pop_back();
1700 ObjCBcLabelNo.pop_back();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001701 return 0;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001702}
1703
Mike Stump11289f42009-09-09 15:08:12 +00001704/// RewriteObjCSynchronizedStmt -
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001705/// This routine rewrites @synchronized(expr) stmt;
1706/// into:
1707/// objc_sync_enter(expr);
1708/// @try stmt @finally { objc_sync_exit(expr); }
1709///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001710Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001711 // Get the start location and compute the semi location.
1712 SourceLocation startLoc = S->getLocStart();
1713 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001714
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001715 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump11289f42009-09-09 15:08:12 +00001716
1717 std::string buf;
Steve Naroffb2fc0522008-08-21 13:03:03 +00001718 buf = "objc_sync_enter((id)";
1719 const char *lparenBuf = startBuf;
1720 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001721 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001722 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1723 // the sync expression is typically a message expression that's already
Steve Naroffad7013b2008-08-19 13:04:19 +00001724 // been rewritten! (which implies the SourceLocation's are invalid).
1725 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001726 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffad7013b2008-08-19 13:04:19 +00001727 while (*endBuf != ')') endBuf--;
1728 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001729 buf = ");\n";
1730 // declare a new scope with two variables, _stack and _rethrow.
1731 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1732 buf += "int buf[18/*32-bit i386*/];\n";
1733 buf += "char *pointers[4];} _stack;\n";
1734 buf += "id volatile _rethrow = 0;\n";
1735 buf += "objc_exception_try_enter(&_stack);\n";
1736 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001737 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001738 startLoc = S->getSynchBody()->getLocEnd();
1739 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001740
Steve Naroffad7013b2008-08-19 13:04:19 +00001741 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001742 SourceLocation lastCurlyLoc = startLoc;
1743 buf = "}\nelse {\n";
1744 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroffd9803712009-04-29 16:37:50 +00001745 buf += "}\n";
1746 buf += "{ /* implicit finally clause */\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001747 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffec60b432009-12-05 21:43:12 +00001748
1749 std::string syncBuf;
1750 syncBuf += " objc_sync_exit(";
John McCall97513962010-01-15 18:39:57 +00001751 Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1752 CastExpr::CK_Unknown,
1753 S->getSynchExpr());
Ted Kremenek2d470fc2008-09-13 05:16:45 +00001754 std::string syncExprBufS;
1755 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00001756 syncExpr->printPretty(syncExprBuf, *Context, 0,
1757 PrintingPolicy(LangOpts));
Steve Naroffec60b432009-12-05 21:43:12 +00001758 syncBuf += syncExprBuf.str();
1759 syncBuf += ");";
1760
1761 buf += syncBuf;
1762 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001763 buf += "}\n";
1764 buf += "}";
Mike Stump11289f42009-09-09 15:08:12 +00001765
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001766 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00001767
1768 bool hasReturns = false;
1769 HasReturnStmts(S->getSynchBody(), hasReturns);
1770 if (hasReturns)
1771 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1772
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001773 return 0;
1774}
1775
Steve Naroffec60b432009-12-05 21:43:12 +00001776void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1777{
Steve Naroff6d6da252008-12-05 17:03:39 +00001778 // Perform a bottom up traversal of all children.
1779 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1780 CI != E; ++CI)
1781 if (*CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001782 WarnAboutReturnGotoStmts(*CI);
Steve Naroff6d6da252008-12-05 17:03:39 +00001783
Steve Naroffec60b432009-12-05 21:43:12 +00001784 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump11289f42009-09-09 15:08:12 +00001785 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff6d6da252008-12-05 17:03:39 +00001786 TryFinallyContainsReturnDiag);
1787 }
1788 return;
1789}
1790
Steve Naroffec60b432009-12-05 21:43:12 +00001791void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1792{
1793 // Perform a bottom up traversal of all children.
1794 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1795 CI != E; ++CI)
1796 if (*CI)
1797 HasReturnStmts(*CI, hasReturns);
1798
1799 if (isa<ReturnStmt>(S))
1800 hasReturns = true;
1801 return;
1802}
1803
1804void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1805 // Perform a bottom up traversal of all children.
1806 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1807 CI != E; ++CI)
1808 if (*CI) {
1809 RewriteTryReturnStmts(*CI);
1810 }
1811 if (isa<ReturnStmt>(S)) {
1812 SourceLocation startLoc = S->getLocStart();
1813 const char *startBuf = SM->getCharacterData(startLoc);
1814
1815 const char *semiBuf = strchr(startBuf, ';');
1816 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1817 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1818
1819 std::string buf;
1820 buf = "{ objc_exception_try_exit(&_stack); return";
1821
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001822 ReplaceText(startLoc, 6, buf);
1823 InsertText(onePastSemiLoc, "}");
Steve Naroffec60b432009-12-05 21:43:12 +00001824 }
1825 return;
1826}
1827
1828void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1829 // Perform a bottom up traversal of all children.
1830 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1831 CI != E; ++CI)
1832 if (*CI) {
1833 RewriteSyncReturnStmts(*CI, syncExitBuf);
1834 }
1835 if (isa<ReturnStmt>(S)) {
1836 SourceLocation startLoc = S->getLocStart();
1837 const char *startBuf = SM->getCharacterData(startLoc);
1838
1839 const char *semiBuf = strchr(startBuf, ';');
1840 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1841 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1842
1843 std::string buf;
1844 buf = "{ objc_exception_try_exit(&_stack);";
1845 buf += syncExitBuf;
1846 buf += " return";
1847
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001848 ReplaceText(startLoc, 6, buf);
1849 InsertText(onePastSemiLoc, "}");
Steve Naroffec60b432009-12-05 21:43:12 +00001850 }
1851 return;
1852}
1853
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001854Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001855 // Get the start location and compute the semi location.
1856 SourceLocation startLoc = S->getLocStart();
1857 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001858
Steve Naroffbf478ec2007-11-07 04:08:17 +00001859 assert((*startBuf == '@') && "bogus @try location");
1860
1861 std::string buf;
1862 // declare a new scope with two variables, _stack and _rethrow.
1863 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1864 buf += "int buf[18/*32-bit i386*/];\n";
1865 buf += "char *pointers[4];} _stack;\n";
1866 buf += "id volatile _rethrow = 0;\n";
1867 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff16018582007-11-07 18:43:40 +00001868 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffbf478ec2007-11-07 04:08:17 +00001869
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001870 ReplaceText(startLoc, 4, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001871
Steve Naroffbf478ec2007-11-07 04:08:17 +00001872 startLoc = S->getTryBody()->getLocEnd();
1873 startBuf = SM->getCharacterData(startLoc);
1874
1875 assert((*startBuf == '}') && "bogus @try block");
Mike Stump11289f42009-09-09 15:08:12 +00001876
Steve Naroffbf478ec2007-11-07 04:08:17 +00001877 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor96c79492010-04-23 22:50:49 +00001878 if (S->getNumCatchStmts()) {
Steve Naroffce2dca12008-07-16 15:31:30 +00001879 startLoc = startLoc.getFileLocWithOffset(1);
1880 buf = " /* @catch begin */ else {\n";
1881 buf += " id _caught = objc_exception_extract(&_stack);\n";
1882 buf += " objc_exception_try_enter (&_stack);\n";
1883 buf += " if (_setjmp(_stack.buf))\n";
1884 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1885 buf += " else { /* @catch continue */";
Mike Stump11289f42009-09-09 15:08:12 +00001886
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001887 InsertText(startLoc, buf);
Steve Narofffac18fe2008-09-09 19:59:12 +00001888 } else { /* no catch list */
1889 buf = "}\nelse {\n";
1890 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1891 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001892 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffce2dca12008-07-16 15:31:30 +00001893 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001894 bool sawIdTypedCatch = false;
1895 Stmt *lastCatchBody = 0;
Douglas Gregor96c79492010-04-23 22:50:49 +00001896 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1897 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregor46a572b2010-04-26 16:46:50 +00001898 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001899
Douglas Gregor96c79492010-04-23 22:50:49 +00001900 if (I == 0)
Steve Naroffbf478ec2007-11-07 04:08:17 +00001901 buf = "if ("; // we are generating code for the first catch clause
1902 else
1903 buf = "else if (";
Douglas Gregor96c79492010-04-23 22:50:49 +00001904 startLoc = Catch->getLocStart();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001905 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001906
Steve Naroffbf478ec2007-11-07 04:08:17 +00001907 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump11289f42009-09-09 15:08:12 +00001908
Steve Naroffbf478ec2007-11-07 04:08:17 +00001909 const char *lParenLoc = strchr(startBuf, '(');
1910
Douglas Gregor96c79492010-04-23 22:50:49 +00001911 if (Catch->hasEllipsis()) {
Steve Naroffedb5bc62008-02-01 20:02:07 +00001912 // Now rewrite the body...
Douglas Gregor96c79492010-04-23 22:50:49 +00001913 lastCatchBody = Catch->getCatchBody();
Steve Naroffedb5bc62008-02-01 20:02:07 +00001914 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1915 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor96c79492010-04-23 22:50:49 +00001916 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001917 "bogus @catch paren location");
Steve Naroffedb5bc62008-02-01 20:02:07 +00001918 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001919
Steve Naroffedb5bc62008-02-01 20:02:07 +00001920 buf += "1) { id _tmp = _caught;";
Daniel Dunbardec484a2009-08-19 19:10:30 +00001921 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff371b8fb2009-03-03 19:52:17 +00001922 } else if (catchDecl) {
1923 QualType t = catchDecl->getType();
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001924 if (t == Context->getObjCIdType()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001925 buf += "1) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001926 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroffbf478ec2007-11-07 04:08:17 +00001927 sawIdTypedCatch = true;
John McCall96fa4842010-05-17 21:00:27 +00001928 } else if (const ObjCObjectPointerType *Ptr =
1929 t->getAs<ObjCObjectPointerType>()) {
1930 // Should be a pointer to a class.
1931 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1932 if (IDecl) {
Steve Naroff16018582007-11-07 18:43:40 +00001933 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall96fa4842010-05-17 21:00:27 +00001934 buf += IDecl->getNameAsString();
Steve Naroff16018582007-11-07 18:43:40 +00001935 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001936 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroffbf478ec2007-11-07 04:08:17 +00001937 }
1938 }
1939 // Now rewrite the body...
Douglas Gregor96c79492010-04-23 22:50:49 +00001940 lastCatchBody = Catch->getCatchBody();
1941 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001942 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1943 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1944 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1945 assert((*rParenBuf == ')') && "bogus @catch paren location");
1946 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001947
Mike Stump11289f42009-09-09 15:08:12 +00001948 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroffbf478ec2007-11-07 04:08:17 +00001949 // declares the @catch parameter).
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001950 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff371b8fb2009-03-03 19:52:17 +00001951 } else {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001952 assert(false && "@catch rewrite bug");
Steve Naroffa733c7f2007-11-07 15:32:26 +00001953 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001954 }
1955 // Complete the catch list...
1956 if (lastCatchBody) {
1957 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001958 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1959 "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001960
Steve Naroff4adbe312008-09-11 15:29:03 +00001961 // Insert the last (implicit) else clause *before* the right curly brace.
1962 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1963 buf = "} /* last catch end */\n";
1964 buf += "else {\n";
1965 buf += " _rethrow = _caught;\n";
1966 buf += " objc_exception_try_exit(&_stack);\n";
1967 buf += "} } /* @catch end */\n";
1968 if (!S->getFinallyStmt())
1969 buf += "}\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001970 InsertText(bodyLoc, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001971
Steve Naroffbf478ec2007-11-07 04:08:17 +00001972 // Set lastCurlyLoc
1973 lastCurlyLoc = lastCatchBody->getLocEnd();
1974 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001975 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001976 startLoc = finalStmt->getLocStart();
1977 startBuf = SM->getCharacterData(startLoc);
1978 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump11289f42009-09-09 15:08:12 +00001979
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001980 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump11289f42009-09-09 15:08:12 +00001981
Steve Naroffbf478ec2007-11-07 04:08:17 +00001982 Stmt *body = finalStmt->getFinallyBody();
1983 SourceLocation startLoc = body->getLocStart();
1984 SourceLocation endLoc = body->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001985 assert(*SM->getCharacterData(startLoc) == '{' &&
1986 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001987 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001988 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001989
Steve Naroffbf478ec2007-11-07 04:08:17 +00001990 startLoc = startLoc.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001991 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Steve Naroffbf478ec2007-11-07 04:08:17 +00001992 endLoc = endLoc.getFileLocWithOffset(-1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001993 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump11289f42009-09-09 15:08:12 +00001994
Steve Naroffbf478ec2007-11-07 04:08:17 +00001995 // Set lastCurlyLoc
1996 lastCurlyLoc = body->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00001997
Steve Naroff6d6da252008-12-05 17:03:39 +00001998 // Now check for any return/continue/go statements within the @try.
Steve Naroffec60b432009-12-05 21:43:12 +00001999 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff4adbe312008-09-11 15:29:03 +00002000 } else { /* no finally clause - make sure we synthesize an implicit one */
2001 buf = "{ /* implicit finally clause */\n";
2002 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
2003 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
2004 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002005 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00002006
2007 // Now check for any return/continue/go statements within the @try.
2008 // The implicit finally clause won't called if the @try contains any
2009 // jump statements.
2010 bool hasReturns = false;
2011 HasReturnStmts(S->getTryBody(), hasReturns);
2012 if (hasReturns)
2013 RewriteTryReturnStmts(S->getTryBody());
Steve Naroffbf478ec2007-11-07 04:08:17 +00002014 }
2015 // Now emit the final closing curly brace...
2016 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002017 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00002018 return 0;
2019}
2020
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002021Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00002022 return 0;
2023}
2024
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002025Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00002026 return 0;
2027}
2028
Mike Stump11289f42009-09-09 15:08:12 +00002029// This can't be done with ReplaceStmt(S, ThrowExpr), since
2030// the throw expression is typically a message expression that's already
Steve Naroffa733c7f2007-11-07 15:32:26 +00002031// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002032Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroffa733c7f2007-11-07 15:32:26 +00002033 // Get the start location and compute the semi location.
2034 SourceLocation startLoc = S->getLocStart();
2035 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002036
Steve Naroffa733c7f2007-11-07 15:32:26 +00002037 assert((*startBuf == '@') && "bogus @throw location");
2038
2039 std::string buf;
2040 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffc7d2df22008-01-19 00:42:38 +00002041 if (S->getThrowExpr())
2042 buf = "objc_exception_throw(";
2043 else // add an implicit argument
2044 buf = "objc_exception_throw(_caught";
Mike Stump11289f42009-09-09 15:08:12 +00002045
Steve Naroff29788342008-07-25 15:41:30 +00002046 // handle "@ throw" correctly.
2047 const char *wBuf = strchr(startBuf, 'w');
2048 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002049 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00002050
Steve Naroffa733c7f2007-11-07 15:32:26 +00002051 const char *semiBuf = strchr(startBuf, ';');
2052 assert((*semiBuf == ';') && "@throw: can't find ';'");
2053 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002054 ReplaceText(semiLoc, 1, ");");
Steve Naroffa733c7f2007-11-07 15:32:26 +00002055 return 0;
2056}
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00002057
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002058Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerc6d91c02007-10-17 22:35:30 +00002059 // Create a new string expression.
2060 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlssond8499822007-10-29 05:01:08 +00002061 std::string StrEncoding;
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00002062 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002063 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
2064 StrEncoding.length(), false,StrType,
2065 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002066 ReplaceStmt(Exp, Replacement);
Mike Stump11289f42009-09-09 15:08:12 +00002067
Chris Lattner4431a1b2007-11-30 22:53:43 +00002068 // Replace this subexpr in the parent.
Steve Naroff22216db2008-12-04 23:50:32 +00002069 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattner69534692007-10-24 16:57:36 +00002070 return Replacement;
Chris Lattnera7c19fe2007-10-16 22:36:42 +00002071}
2072
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002073Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff2654e182008-12-22 22:16:07 +00002074 if (!SelGetUidFunctionDecl)
2075 SynthSelGetUidFunctionDecl();
Steve Naroffe4f9b232007-11-05 14:50:49 +00002076 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2077 // Create a call to sel_registerName("selName").
2078 llvm::SmallVector<Expr*, 8> SelExprs;
2079 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002080 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002081 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002082 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00002083 false, argType, SourceLocation()));
Steve Naroffe4f9b232007-11-05 14:50:49 +00002084 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2085 &SelExprs[0], SelExprs.size());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002086 ReplaceStmt(Exp, SelExp);
Steve Naroff22216db2008-12-04 23:50:32 +00002087 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffe4f9b232007-11-05 14:50:49 +00002088 return SelExp;
2089}
2090
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002091CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002092 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2093 SourceLocation EndLoc) {
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002094 // Get the type, we will need to reference it in a couple spots.
Steve Naroff574440f2007-10-24 22:48:43 +00002095 QualType msgSendType = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002096
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002097 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek5a201952009-02-07 01:47:29 +00002098 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002099
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002100 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattner3c799d72007-10-24 17:06:59 +00002101 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson975979382010-04-23 22:18:37 +00002102 ImplicitCastExpr *ICE =
2103 new (Context) ImplicitCastExpr(pToFunc, CastExpr::CK_Unknown,
Anders Carlsson0c509ee2010-04-24 16:57:13 +00002104 DRE, CXXBaseSpecifierArray(),
Anders Carlsson975979382010-04-23 22:18:37 +00002105 /*isLvalue=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002106
John McCall9dd450b2009-09-21 23:43:11 +00002107 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00002108
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002109 CallExpr *Exp =
2110 new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
2111 EndLoc);
2112 return Exp;
Steve Naroff574440f2007-10-24 22:48:43 +00002113}
2114
Steve Naroff50d42052007-11-01 13:24:47 +00002115static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2116 const char *&startRef, const char *&endRef) {
2117 while (startBuf < endBuf) {
2118 if (*startBuf == '<')
2119 startRef = startBuf; // mark the start.
2120 if (*startBuf == '>') {
Steve Naroff1b232132007-11-09 12:50:28 +00002121 if (startRef && *startRef == '<') {
2122 endRef = startBuf; // mark the end.
2123 return true;
2124 }
2125 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002126 }
2127 startBuf++;
2128 }
2129 return false;
2130}
2131
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002132static void scanToNextArgument(const char *&argRef) {
2133 int angle = 0;
2134 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2135 if (*argRef == '<')
2136 angle++;
2137 else if (*argRef == '>')
2138 angle--;
2139 argRef++;
2140 }
2141 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2142}
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002143
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002144bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian80c54b02010-02-03 21:29:28 +00002145 if (T->isObjCQualifiedIdType())
2146 return true;
Fariborz Jahanian06769f92010-02-02 18:35:07 +00002147 if (const PointerType *PT = T->getAs<PointerType>()) {
2148 if (PT->getPointeeType()->isObjCQualifiedIdType())
2149 return true;
2150 }
2151 if (T->isObjCObjectPointerType()) {
2152 T = T->getPointeeType();
2153 return T->isObjCQualifiedInterfaceType();
2154 }
2155 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002156}
2157
Steve Naroff873bd842008-07-29 18:15:38 +00002158void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2159 QualType Type = E->getType();
2160 if (needToScanForQualifiers(Type)) {
Steve Naroffdbfc6932008-11-19 21:15:47 +00002161 SourceLocation Loc, EndLoc;
Mike Stump11289f42009-09-09 15:08:12 +00002162
Steve Naroffdbfc6932008-11-19 21:15:47 +00002163 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2164 Loc = ECE->getLParenLoc();
2165 EndLoc = ECE->getRParenLoc();
2166 } else {
2167 Loc = E->getLocStart();
2168 EndLoc = E->getLocEnd();
2169 }
2170 // This will defend against trying to rewrite synthesized expressions.
2171 if (Loc.isInvalid() || EndLoc.isInvalid())
2172 return;
2173
Steve Naroff873bd842008-07-29 18:15:38 +00002174 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffdbfc6932008-11-19 21:15:47 +00002175 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff873bd842008-07-29 18:15:38 +00002176 const char *startRef = 0, *endRef = 0;
2177 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2178 // Get the locations of the startRef, endRef.
2179 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2180 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2181 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002182 InsertText(LessLoc, "/*");
2183 InsertText(GreaterLoc, "*/");
Steve Naroff873bd842008-07-29 18:15:38 +00002184 }
2185 }
2186}
2187
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002188void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002189 SourceLocation Loc;
2190 QualType Type;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002191 const FunctionProtoType *proto = 0;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002192 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2193 Loc = VD->getLocation();
2194 Type = VD->getType();
2195 }
2196 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2197 Loc = FD->getLocation();
2198 // Check for ObjC 'id' and class types that have been adorned with protocol
2199 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall9dd450b2009-09-21 23:43:11 +00002200 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002201 assert(funcType && "missing function type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002202 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002203 if (!proto)
2204 return;
2205 Type = proto->getResultType();
2206 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00002207 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2208 Loc = FD->getLocation();
2209 Type = FD->getType();
2210 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002211 else
2212 return;
Mike Stump11289f42009-09-09 15:08:12 +00002213
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002214 if (needToScanForQualifiers(Type)) {
Steve Naroff50d42052007-11-01 13:24:47 +00002215 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002216
Steve Naroff50d42052007-11-01 13:24:47 +00002217 const char *endBuf = SM->getCharacterData(Loc);
2218 const char *startBuf = endBuf;
Steve Naroff930e0992008-05-31 05:02:17 +00002219 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroff50d42052007-11-01 13:24:47 +00002220 startBuf--; // scan backward (from the decl location) for return type.
2221 const char *startRef = 0, *endRef = 0;
2222 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2223 // Get the locations of the startRef, endRef.
2224 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2225 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2226 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002227 InsertText(LessLoc, "/*");
2228 InsertText(GreaterLoc, "*/");
Steve Naroff37e011c2007-10-31 04:38:33 +00002229 }
2230 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002231 if (!proto)
2232 return; // most likely, was a variable
Steve Naroff50d42052007-11-01 13:24:47 +00002233 // Now check arguments.
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002234 const char *startBuf = SM->getCharacterData(Loc);
2235 const char *startFuncBuf = startBuf;
Steve Naroff50d42052007-11-01 13:24:47 +00002236 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2237 if (needToScanForQualifiers(proto->getArgType(i))) {
2238 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002239
Steve Naroff50d42052007-11-01 13:24:47 +00002240 const char *endBuf = startBuf;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002241 // scan forward (from the decl location) for argument types.
2242 scanToNextArgument(endBuf);
Steve Naroff50d42052007-11-01 13:24:47 +00002243 const char *startRef = 0, *endRef = 0;
2244 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2245 // Get the locations of the startRef, endRef.
Mike Stump11289f42009-09-09 15:08:12 +00002246 SourceLocation LessLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002247 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump11289f42009-09-09 15:08:12 +00002248 SourceLocation GreaterLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002249 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002250 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002251 InsertText(LessLoc, "/*");
2252 InsertText(GreaterLoc, "*/");
Steve Naroff50d42052007-11-01 13:24:47 +00002253 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002254 startBuf = ++endBuf;
2255 }
2256 else {
Steve Naroffc884aa82008-08-06 15:58:23 +00002257 // If the function name is derived from a macro expansion, then the
2258 // argument buffer will not follow the name. Need to speak with Chris.
2259 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002260 startBuf++; // scan forward (from the decl location) for argument types.
2261 startBuf++;
2262 }
Steve Naroff50d42052007-11-01 13:24:47 +00002263 }
Steve Naroff37e011c2007-10-31 04:38:33 +00002264}
2265
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002266void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2267 QualType QT = ND->getType();
2268 const Type* TypePtr = QT->getAs<Type>();
2269 if (!isa<TypeOfExprType>(TypePtr))
2270 return;
2271 while (isa<TypeOfExprType>(TypePtr)) {
2272 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2273 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2274 TypePtr = QT->getAs<Type>();
2275 }
2276 // FIXME. This will not work for multiple declarators; as in:
2277 // __typeof__(a) b,c,d;
2278 std::string TypeAsString(QT.getAsString());
2279 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2280 const char *startBuf = SM->getCharacterData(DeclLoc);
2281 if (ND->getInit()) {
2282 std::string Name(ND->getNameAsString());
2283 TypeAsString += " " + Name + " = ";
2284 Expr *E = ND->getInit();
2285 SourceLocation startLoc;
2286 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2287 startLoc = ECE->getLParenLoc();
2288 else
2289 startLoc = E->getLocStart();
2290 startLoc = SM->getInstantiationLoc(startLoc);
2291 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002292 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002293 }
2294 else {
2295 SourceLocation X = ND->getLocEnd();
2296 X = SM->getInstantiationLoc(X);
2297 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002298 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002299 }
2300}
2301
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002302// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002303void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002304 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2305 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002306 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002307 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002308 &ArgTys[0], ArgTys.size(),
2309 false /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002310 false, false, 0, 0,
2311 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002312 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002313 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002314 SelGetUidIdent, getFuncType, 0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002315 FunctionDecl::Extern,
2316 FunctionDecl::None, false);
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002317}
2318
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002319void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002320 // declared in <objc/objc.h>
Douglas Gregor1e21c192009-01-09 01:47:02 +00002321 if (FD->getIdentifier() &&
2322 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002323 SelGetUidFunctionDecl = FD;
Steve Naroff37e011c2007-10-31 04:38:33 +00002324 return;
2325 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002326 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002327}
2328
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002329static void RewriteBlockPointerType(std::string& Str, QualType Type) {
2330 std::string TypeString(Type.getAsString());
2331 const char *argPtr = TypeString.c_str();
2332 if (!strchr(argPtr, '^')) {
2333 Str += TypeString;
2334 return;
2335 }
2336 while (*argPtr) {
2337 Str += (*argPtr == '^' ? '*' : *argPtr);
2338 argPtr++;
2339 }
2340}
2341
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002342// FIXME. Consolidate this routine with RewriteBlockPointerType.
2343static void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD) {
2344 QualType Type = VD->getType();
2345 std::string TypeString(Type.getAsString());
2346 const char *argPtr = TypeString.c_str();
2347 int paren = 0;
2348 while (*argPtr) {
2349 switch (*argPtr) {
2350 case '(':
2351 Str += *argPtr;
2352 paren++;
2353 break;
2354 case ')':
2355 Str += *argPtr;
2356 paren--;
2357 break;
2358 case '^':
2359 Str += '*';
2360 if (paren == 1)
2361 Str += VD->getNameAsString();
2362 break;
2363 default:
2364 Str += *argPtr;
2365 break;
2366 }
2367 argPtr++;
2368 }
2369}
2370
2371
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002372void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2373 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2374 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2375 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2376 if (!proto)
2377 return;
2378 QualType Type = proto->getResultType();
2379 std::string FdStr = Type.getAsString();
2380 FdStr += " ";
2381 FdStr += FD->getNameAsCString();
2382 FdStr += "(";
2383 unsigned numArgs = proto->getNumArgs();
2384 for (unsigned i = 0; i < numArgs; i++) {
2385 QualType ArgType = proto->getArgType(i);
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002386 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002387 if (i+1 < numArgs)
2388 FdStr += ", ";
2389 }
2390 FdStr += ");\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002391 InsertText(FunLocStart, FdStr);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002392 CurFunctionDeclToDeclareForBlock = 0;
2393}
2394
Steve Naroff17978c42008-03-11 17:37:02 +00002395// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002396void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroff17978c42008-03-11 17:37:02 +00002397 if (SuperContructorFunctionDecl)
2398 return;
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002399 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroff17978c42008-03-11 17:37:02 +00002400 llvm::SmallVector<QualType, 16> ArgTys;
2401 QualType argT = Context->getObjCIdType();
2402 assert(!argT.isNull() && "Can't find 'id' type");
2403 ArgTys.push_back(argT);
2404 ArgTys.push_back(argT);
2405 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2406 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002407 false, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002408 false, false, 0, 0,
2409 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002410 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002411 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002412 msgSendIdent, msgSendType, 0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002413 FunctionDecl::Extern,
2414 FunctionDecl::None, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002415}
2416
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002417// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002418void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002419 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2420 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002421 QualType argT = Context->getObjCIdType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002422 assert(!argT.isNull() && "Can't find 'id' type");
2423 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002424 argT = Context->getObjCSelType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002425 assert(!argT.isNull() && "Can't find 'SEL' type");
2426 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002427 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002428 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002429 true /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002430 false, false, 0, 0,
2431 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002432 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002433 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002434 msgSendIdent, msgSendType, 0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002435 FunctionDecl::Extern,
2436 FunctionDecl::None, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002437}
2438
Steve Naroff7fa2f042007-11-15 10:28:18 +00002439// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002440void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002441 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2442 llvm::SmallVector<QualType, 16> ArgTys;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002443 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002444 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002445 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002446 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2447 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2448 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002449 argT = Context->getObjCSelType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002450 assert(!argT.isNull() && "Can't find 'SEL' type");
2451 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002452 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff7fa2f042007-11-15 10:28:18 +00002453 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002454 true /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002455 false, false, 0, 0,
2456 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002457 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002458 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002459 msgSendIdent, msgSendType, 0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002460 FunctionDecl::Extern,
2461 FunctionDecl::None, false);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002462}
2463
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002464// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002465void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002466 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2467 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002468 QualType argT = Context->getObjCIdType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002469 assert(!argT.isNull() && "Can't find 'id' type");
2470 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002471 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002472 assert(!argT.isNull() && "Can't find 'SEL' type");
2473 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002474 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002475 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002476 true /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002477 false, false, 0, 0,
2478 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002479 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002480 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002481 msgSendIdent, msgSendType, 0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002482 FunctionDecl::Extern,
2483 FunctionDecl::None, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002484}
2485
Mike Stump11289f42009-09-09 15:08:12 +00002486// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002487// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002488void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump11289f42009-09-09 15:08:12 +00002489 IdentifierInfo *msgSendIdent =
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002490 &Context->Idents.get("objc_msgSendSuper_stret");
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"));
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +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();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002499 assert(!argT.isNull() && "Can't find 'SEL' type");
2500 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002501 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002502 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002503 true /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002504 false, false, 0, 0,
2505 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002506 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002507 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002508 msgSendIdent, msgSendType, 0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002509 FunctionDecl::Extern,
2510 FunctionDecl::None, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002511}
2512
Steve Naroff2e4e3852008-05-08 22:02:18 +00002513// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002514void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002515 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2516 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002517 QualType argT = Context->getObjCIdType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002518 assert(!argT.isNull() && "Can't find 'id' type");
2519 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002520 argT = Context->getObjCSelType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002521 assert(!argT.isNull() && "Can't find 'SEL' type");
2522 ArgTys.push_back(argT);
Steve Naroff2e4e3852008-05-08 22:02:18 +00002523 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002524 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002525 true /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002526 false, false, 0, 0,
2527 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002528 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002529 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002530 msgSendIdent, msgSendType, 0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002531 FunctionDecl::Extern,
2532 FunctionDecl::None, false);
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002533}
2534
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002535// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002536void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002537 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2538 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002539 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002540 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002541 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002542 false /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002543 false, false, 0, 0,
2544 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002545 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002546 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002547 getClassIdent, getClassType, 0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002548 FunctionDecl::Extern,
2549 FunctionDecl::None, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002550}
2551
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002552// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2553void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2554 IdentifierInfo *getSuperClassIdent =
2555 &Context->Idents.get("class_getSuperclass");
2556 llvm::SmallVector<QualType, 16> ArgTys;
2557 ArgTys.push_back(Context->getObjCClassType());
2558 QualType getClassType = Context->getFunctionType(Context->getObjCClassType(),
2559 &ArgTys[0], ArgTys.size(),
2560 false /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002561 false, false, 0, 0,
2562 FunctionType::ExtInfo());
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002563 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002564 SourceLocation(),
2565 getSuperClassIdent,
2566 getClassType, 0,
2567 FunctionDecl::Extern,
2568 FunctionDecl::None,
2569 false);
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002570}
2571
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002572// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002573void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002574 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2575 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002576 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002577 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002578 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002579 false /*isVariadic*/, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002580 false, false, 0, 0,
2581 FunctionType::ExtInfo());
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002582 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002583 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002584 getClassIdent, getClassType, 0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002585 FunctionDecl::Extern,
2586 FunctionDecl::None, false);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002587}
2588
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002589Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffce8e8862008-03-15 00:55:56 +00002590 QualType strType = getConstantStringStructType();
2591
2592 std::string S = "__NSConstantStringImpl_";
Steve Naroffa6141f02008-05-31 03:35:42 +00002593
2594 std::string tmpName = InFileName;
2595 unsigned i;
2596 for (i=0; i < tmpName.length(); i++) {
2597 char c = tmpName.at(i);
2598 // replace any non alphanumeric characters with '_'.
2599 if (!isalpha(c) && (c < '0' || c > '9'))
2600 tmpName[i] = '_';
2601 }
2602 S += tmpName;
2603 S += "_";
Steve Naroffce8e8862008-03-15 00:55:56 +00002604 S += utostr(NumObjCStringLiterals++);
2605
Steve Naroff00a31762008-03-27 22:29:16 +00002606 Preamble += "static __NSConstantStringImpl " + S;
2607 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2608 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffce8e8862008-03-15 00:55:56 +00002609 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek2d470fc2008-09-13 05:16:45 +00002610 std::string prettyBufS;
2611 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00002612 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2613 PrintingPolicy(LangOpts));
Steve Naroff00a31762008-03-27 22:29:16 +00002614 Preamble += prettyBuf.str();
2615 Preamble += ",";
Steve Naroff94ed6dc2009-12-06 01:48:44 +00002616 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002617
2618 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002619 &Context->Idents.get(S), strType, 0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002620 VarDecl::Static, VarDecl::None);
Ted Kremenek5a201952009-02-07 01:47:29 +00002621 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2622 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002623 Context->getPointerType(DRE->getType()),
Steve Naroffce8e8862008-03-15 00:55:56 +00002624 SourceLocation());
Steve Naroff265a6b92007-11-08 14:30:50 +00002625 // cast to NSConstantString *
John McCall97513962010-01-15 18:39:57 +00002626 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2627 CastExpr::CK_Unknown, Unop);
Chris Lattner2e0d2602008-01-31 19:37:57 +00002628 ReplaceStmt(Exp, cast);
Steve Naroff22216db2008-12-04 23:50:32 +00002629 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff265a6b92007-11-08 14:30:50 +00002630 return cast;
Steve Naroffa397efd2007-11-03 11:27:19 +00002631}
2632
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002633bool RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002634 // check if we are sending a message to 'super'
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002635 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return false;
2636 return isa<ObjCSuperExpr>(recExpr);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002637}
2638
2639// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002640QualType RewriteObjC::getSuperStructType() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002641 if (!SuperStructDecl) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00002642 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002643 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002644 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002645 QualType FieldTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002646
Steve Naroff7fa2f042007-11-15 10:28:18 +00002647 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002648 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002649 // struct objc_class *super;
Mike Stump11289f42009-09-09 15:08:12 +00002650 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor91f84212008-12-11 16:49:14 +00002651
Steve Naroff7fa2f042007-11-15 10:28:18 +00002652 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002653 for (unsigned i = 0; i < 2; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002654 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2655 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002656 FieldTypes[i], 0,
2657 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002658 /*Mutable=*/false));
Douglas Gregor91f84212008-12-11 16:49:14 +00002659 }
Mike Stump11289f42009-09-09 15:08:12 +00002660
Douglas Gregord5058122010-02-11 01:19:42 +00002661 SuperStructDecl->completeDefinition();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002662 }
2663 return Context->getTagDeclType(SuperStructDecl);
2664}
2665
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002666QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffce8e8862008-03-15 00:55:56 +00002667 if (!ConstantStringDecl) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00002668 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002669 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002670 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffce8e8862008-03-15 00:55:56 +00002671 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002672
Steve Naroffce8e8862008-03-15 00:55:56 +00002673 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002674 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffce8e8862008-03-15 00:55:56 +00002675 // int flags;
Mike Stump11289f42009-09-09 15:08:12 +00002676 FieldTypes[1] = Context->IntTy;
Steve Naroffce8e8862008-03-15 00:55:56 +00002677 // char *str;
Mike Stump11289f42009-09-09 15:08:12 +00002678 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffce8e8862008-03-15 00:55:56 +00002679 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002680 FieldTypes[3] = Context->LongTy;
Douglas Gregor91f84212008-12-11 16:49:14 +00002681
Steve Naroffce8e8862008-03-15 00:55:56 +00002682 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002683 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002684 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2685 ConstantStringDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002686 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002687 FieldTypes[i], 0,
Douglas Gregor91f84212008-12-11 16:49:14 +00002688 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002689 /*Mutable=*/true));
Douglas Gregor91f84212008-12-11 16:49:14 +00002690 }
2691
Douglas Gregord5058122010-02-11 01:19:42 +00002692 ConstantStringDecl->completeDefinition();
Steve Naroffce8e8862008-03-15 00:55:56 +00002693 }
2694 return Context->getTagDeclType(ConstantStringDecl);
2695}
2696
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002697Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2698 SourceLocation StartLoc,
2699 SourceLocation EndLoc) {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002700 if (!SelGetUidFunctionDecl)
2701 SynthSelGetUidFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002702 if (!MsgSendFunctionDecl)
2703 SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002704 if (!MsgSendSuperFunctionDecl)
2705 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002706 if (!MsgSendStretFunctionDecl)
2707 SynthMsgSendStretFunctionDecl();
2708 if (!MsgSendSuperStretFunctionDecl)
2709 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002710 if (!MsgSendFpretFunctionDecl)
2711 SynthMsgSendFpretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002712 if (!GetClassFunctionDecl)
2713 SynthGetClassFunctionDecl();
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002714 if (!GetSuperClassFunctionDecl)
2715 SynthGetSuperClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002716 if (!GetMetaClassFunctionDecl)
2717 SynthGetMetaClassFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002718
Steve Naroff7fa2f042007-11-15 10:28:18 +00002719 // default to objc_msgSend().
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002720 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2721 // May need to use objc_msgSend_stret() as well.
2722 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroffd9803712009-04-29 16:37:50 +00002723 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2724 QualType resultType = mDecl->getResultType();
Douglas Gregor8385a062010-04-26 21:31:17 +00002725 if (resultType->isRecordType())
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002726 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002727 else if (resultType->isRealFloatingType())
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002728 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002729 }
Mike Stump11289f42009-09-09 15:08:12 +00002730
Steve Naroff574440f2007-10-24 22:48:43 +00002731 // Synthesize a call to objc_msgSend().
2732 llvm::SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor9a129192010-04-21 00:45:42 +00002733 switch (Exp->getReceiverKind()) {
2734 case ObjCMessageExpr::SuperClass: {
2735 MsgSendFlavor = MsgSendSuperFunctionDecl;
2736 if (MsgSendStretFlavor)
2737 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2738 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002739
Douglas Gregor9a129192010-04-21 00:45:42 +00002740 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00002741
Douglas Gregor9a129192010-04-21 00:45:42 +00002742 llvm::SmallVector<Expr*, 4> InitExprs;
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002743
Douglas Gregor9a129192010-04-21 00:45:42 +00002744 // set the receiver to self, the first argument to all methods.
2745 InitExprs.push_back(
2746 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2747 CastExpr::CK_Unknown,
2748 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2749 Context->getObjCIdType(),
2750 SourceLocation()))
2751 ); // set the 'receiver'.
Mike Stump11289f42009-09-09 15:08:12 +00002752
Douglas Gregor9a129192010-04-21 00:45:42 +00002753 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2754 llvm::SmallVector<Expr*, 8> ClsExprs;
2755 QualType argType = Context->getPointerType(Context->CharTy);
2756 ClsExprs.push_back(StringLiteral::Create(*Context,
2757 ClassDecl->getIdentifier()->getNameStart(),
2758 ClassDecl->getIdentifier()->getLength(),
2759 false, argType, SourceLocation()));
2760 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2761 &ClsExprs[0],
2762 ClsExprs.size(),
2763 StartLoc,
2764 EndLoc);
2765 // (Class)objc_getClass("CurrentClass")
2766 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2767 Context->getObjCClassType(),
2768 CastExpr::CK_Unknown, Cls);
2769 ClsExprs.clear();
2770 ClsExprs.push_back(ArgExpr);
2771 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2772 &ClsExprs[0], ClsExprs.size(),
2773 StartLoc, EndLoc);
2774
2775 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2776 // To turn off a warning, type-cast to 'id'
2777 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2778 NoTypeInfoCStyleCastExpr(Context,
2779 Context->getObjCIdType(),
2780 CastExpr::CK_Unknown, Cls));
2781 // struct objc_super
2782 QualType superType = getSuperStructType();
2783 Expr *SuperRep;
Steve Naroffd9803712009-04-29 16:37:50 +00002784
Douglas Gregor9a129192010-04-21 00:45:42 +00002785 if (LangOpts.Microsoft) {
2786 SynthSuperContructorFunctionDecl();
2787 // Simulate a contructor call...
2788 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
2789 superType, SourceLocation());
2790 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2791 InitExprs.size(),
2792 superType, SourceLocation());
2793 // The code for super is a little tricky to prevent collision with
2794 // the structure definition in the header. The rewriter has it's own
2795 // internal definition (__rw_objc_super) that is uses. This is why
2796 // we need the cast below. For example:
2797 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2798 //
2799 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2800 Context->getPointerType(SuperRep->getType()),
2801 SourceLocation());
2802 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2803 Context->getPointerType(superType),
2804 CastExpr::CK_Unknown, SuperRep);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002805 } else {
Douglas Gregor9a129192010-04-21 00:45:42 +00002806 // (struct objc_super) { <exprs from above> }
2807 InitListExpr *ILE =
2808 new (Context) InitListExpr(*Context, SourceLocation(),
2809 &InitExprs[0], InitExprs.size(),
2810 SourceLocation());
2811 TypeSourceInfo *superTInfo
2812 = Context->getTrivialTypeSourceInfo(superType);
2813 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2814 superType, ILE, false);
2815 // struct objc_super *
2816 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2817 Context->getPointerType(SuperRep->getType()),
2818 SourceLocation());
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002819 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002820 MsgExprs.push_back(SuperRep);
2821 break;
Steve Naroffe7f18192007-11-14 23:54:14 +00002822 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002823
2824 case ObjCMessageExpr::Class: {
2825 llvm::SmallVector<Expr*, 8> ClsExprs;
2826 QualType argType = Context->getPointerType(Context->CharTy);
2827 ObjCInterfaceDecl *Class
John McCall96fa4842010-05-17 21:00:27 +00002828 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor9a129192010-04-21 00:45:42 +00002829 IdentifierInfo *clsName = Class->getIdentifier();
2830 ClsExprs.push_back(StringLiteral::Create(*Context,
2831 clsName->getNameStart(),
2832 clsName->getLength(),
2833 false, argType,
2834 SourceLocation()));
2835 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2836 &ClsExprs[0],
2837 ClsExprs.size(),
2838 StartLoc, EndLoc);
2839 MsgExprs.push_back(Cls);
2840 break;
2841 }
2842
2843 case ObjCMessageExpr::SuperInstance:{
2844 MsgSendFlavor = MsgSendSuperFunctionDecl;
2845 if (MsgSendStretFlavor)
2846 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2847 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2848 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2849 llvm::SmallVector<Expr*, 4> InitExprs;
2850
2851 InitExprs.push_back(
2852 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2853 CastExpr::CK_Unknown,
2854 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2855 Context->getObjCIdType(),
2856 SourceLocation()))
2857 ); // set the 'receiver'.
2858
2859 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2860 llvm::SmallVector<Expr*, 8> ClsExprs;
2861 QualType argType = Context->getPointerType(Context->CharTy);
2862 ClsExprs.push_back(StringLiteral::Create(*Context,
2863 ClassDecl->getIdentifier()->getNameStart(),
2864 ClassDecl->getIdentifier()->getLength(),
2865 false, argType, SourceLocation()));
2866 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2867 &ClsExprs[0],
2868 ClsExprs.size(),
2869 StartLoc, EndLoc);
2870 // (Class)objc_getClass("CurrentClass")
2871 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2872 Context->getObjCClassType(),
2873 CastExpr::CK_Unknown, Cls);
2874 ClsExprs.clear();
2875 ClsExprs.push_back(ArgExpr);
2876 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2877 &ClsExprs[0], ClsExprs.size(),
2878 StartLoc, EndLoc);
2879
2880 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2881 // To turn off a warning, type-cast to 'id'
2882 InitExprs.push_back(
2883 // set 'super class', using class_getSuperclass().
2884 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2885 CastExpr::CK_Unknown, Cls));
2886 // struct objc_super
2887 QualType superType = getSuperStructType();
2888 Expr *SuperRep;
2889
2890 if (LangOpts.Microsoft) {
2891 SynthSuperContructorFunctionDecl();
2892 // Simulate a contructor call...
2893 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
2894 superType, SourceLocation());
2895 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2896 InitExprs.size(),
2897 superType, SourceLocation());
2898 // The code for super is a little tricky to prevent collision with
2899 // the structure definition in the header. The rewriter has it's own
2900 // internal definition (__rw_objc_super) that is uses. This is why
2901 // we need the cast below. For example:
2902 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2903 //
2904 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2905 Context->getPointerType(SuperRep->getType()),
2906 SourceLocation());
2907 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2908 Context->getPointerType(superType),
2909 CastExpr::CK_Unknown, SuperRep);
2910 } else {
2911 // (struct objc_super) { <exprs from above> }
2912 InitListExpr *ILE =
2913 new (Context) InitListExpr(*Context, SourceLocation(),
2914 &InitExprs[0], InitExprs.size(),
2915 SourceLocation());
2916 TypeSourceInfo *superTInfo
2917 = Context->getTrivialTypeSourceInfo(superType);
2918 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2919 superType, ILE, false);
2920 }
2921 MsgExprs.push_back(SuperRep);
2922 break;
2923 }
2924
2925 case ObjCMessageExpr::Instance: {
2926 // Remove all type-casts because it may contain objc-style types; e.g.
2927 // Foo<Proto> *.
2928 Expr *recExpr = Exp->getInstanceReceiver();
2929 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2930 recExpr = CE->getSubExpr();
2931 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2932 CastExpr::CK_Unknown, recExpr);
2933 MsgExprs.push_back(recExpr);
2934 break;
2935 }
2936 }
2937
Steve Naroffa397efd2007-11-03 11:27:19 +00002938 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff574440f2007-10-24 22:48:43 +00002939 llvm::SmallVector<Expr*, 8> SelExprs;
2940 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002941 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002942 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002943 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00002944 false, argType, SourceLocation()));
Steve Naroff574440f2007-10-24 22:48:43 +00002945 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002946 &SelExprs[0], SelExprs.size(),
2947 StartLoc,
2948 EndLoc);
Steve Naroff574440f2007-10-24 22:48:43 +00002949 MsgExprs.push_back(SelExp);
Mike Stump11289f42009-09-09 15:08:12 +00002950
Steve Naroff574440f2007-10-24 22:48:43 +00002951 // Now push any user supplied arguments.
2952 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroffe7f18192007-11-14 23:54:14 +00002953 Expr *userExpr = Exp->getArg(i);
Steve Narofff60782b2007-11-15 02:58:25 +00002954 // Make all implicit casts explicit...ICE comes in handy:-)
2955 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2956 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregore200adc2008-10-27 19:41:14 +00002957 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002958 ? Context->getObjCIdType()
Douglas Gregore200adc2008-10-27 19:41:14 +00002959 : ICE->getType();
Fariborz Jahanian19c62402010-05-25 15:56:08 +00002960 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00002961 (void)convertBlockPointerToFunctionPointer(type);
John McCall97513962010-01-15 18:39:57 +00002962 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CastExpr::CK_Unknown,
2963 userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002964 }
2965 // Make id<P...> cast into an 'id' cast.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002966 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002967 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregorf19b2312008-10-28 15:36:24 +00002968 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002969 userExpr = CE->getSubExpr();
John McCall97513962010-01-15 18:39:57 +00002970 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2971 CastExpr::CK_Unknown, userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002972 }
Mike Stump11289f42009-09-09 15:08:12 +00002973 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002974 MsgExprs.push_back(userExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00002975 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2976 // out the argument in the original expression (since we aren't deleting
2977 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2978 //Exp->setArg(i, 0);
Steve Naroff574440f2007-10-24 22:48:43 +00002979 }
Steve Narofff36987c2007-11-04 22:37:50 +00002980 // Generate the funky cast.
2981 CastExpr *cast;
2982 llvm::SmallVector<QualType, 8> ArgTypes;
2983 QualType returnType;
Mike Stump11289f42009-09-09 15:08:12 +00002984
Steve Narofff36987c2007-11-04 22:37:50 +00002985 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff44864e42007-11-15 10:43:57 +00002986 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2987 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2988 else
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002989 ArgTypes.push_back(Context->getObjCIdType());
2990 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattnera4997152009-02-20 18:43:26 +00002991 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Narofff36987c2007-11-04 22:37:50 +00002992 // Push any user argument types.
Chris Lattnera4997152009-02-20 18:43:26 +00002993 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2994 E = OMD->param_end(); PI != E; ++PI) {
2995 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump11289f42009-09-09 15:08:12 +00002996 ? Context->getObjCIdType()
Chris Lattnera4997152009-02-20 18:43:26 +00002997 : (*PI)->getType();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002998 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00002999 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff98eb8d12007-11-05 14:36:37 +00003000 ArgTypes.push_back(t);
3001 }
Chris Lattnera4997152009-02-20 18:43:26 +00003002 returnType = OMD->getResultType()->isObjCQualifiedIdType()
3003 ? Context->getObjCIdType() : OMD->getResultType();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00003004 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Narofff36987c2007-11-04 22:37:50 +00003005 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003006 returnType = Context->getObjCIdType();
Steve Narofff36987c2007-11-04 22:37:50 +00003007 }
3008 // Get the type, we will need to reference it in a couple spots.
Steve Naroff7fa2f042007-11-15 10:28:18 +00003009 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump11289f42009-09-09 15:08:12 +00003010
Steve Narofff36987c2007-11-04 22:37:50 +00003011 // Create a reference to the objc_msgSend() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003012 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003013 SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00003014
Mike Stump11289f42009-09-09 15:08:12 +00003015 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Narofff36987c2007-11-04 22:37:50 +00003016 // If we don't do this cast, we get the following bizarre warning/note:
3017 // xx.m:13: warning: function called through a non-compatible type
3018 // xx.m:13: note: if this code is reached, the program will abort
John McCall97513962010-01-15 18:39:57 +00003019 cast = NoTypeInfoCStyleCastExpr(Context,
3020 Context->getPointerType(Context->VoidTy),
3021 CastExpr::CK_Unknown, DRE);
Mike Stump11289f42009-09-09 15:08:12 +00003022
Steve Narofff36987c2007-11-04 22:37:50 +00003023 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00003024 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00003025 &ArgTypes[0], ArgTypes.size(),
Steve Naroff327f0f42008-03-18 02:02:04 +00003026 // If we don't have a method decl, force a variadic cast.
Douglas Gregor36c569f2010-02-21 22:15:06 +00003027 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003028 false, false, 0, 0,
3029 FunctionType::ExtInfo());
Steve Narofff36987c2007-11-04 22:37:50 +00003030 castType = Context->getPointerType(castType);
John McCall97513962010-01-15 18:39:57 +00003031 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
3032 cast);
Steve Narofff36987c2007-11-04 22:37:50 +00003033
3034 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00003035 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump11289f42009-09-09 15:08:12 +00003036
John McCall9dd450b2009-09-21 23:43:11 +00003037 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003038 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00003039 MsgExprs.size(),
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00003040 FT->getResultType(), EndLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003041 Stmt *ReplacingStmt = CE;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003042 if (MsgSendStretFlavor) {
3043 // We have the method which returns a struct/union. Must also generate
3044 // call to objc_msgSend_stret and hang both varieties on a conditional
3045 // expression which dictate which one to envoke depending on size of
3046 // method's return type.
Mike Stump11289f42009-09-09 15:08:12 +00003047
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003048 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003049 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003050 SourceLocation());
3051 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall97513962010-01-15 18:39:57 +00003052 cast = NoTypeInfoCStyleCastExpr(Context,
3053 Context->getPointerType(Context->VoidTy),
3054 CastExpr::CK_Unknown, STDRE);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003055 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00003056 castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00003057 &ArgTypes[0], ArgTypes.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00003058 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003059 false, false, 0, 0,
3060 FunctionType::ExtInfo());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003061 castType = Context->getPointerType(castType);
John McCall97513962010-01-15 18:39:57 +00003062 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
3063 cast);
Mike Stump11289f42009-09-09 15:08:12 +00003064
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003065 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00003066 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00003067
John McCall9dd450b2009-09-21 23:43:11 +00003068 FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003069 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00003070 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003071 FT->getResultType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00003072
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003073 // Build sizeof(returnType)
Mike Stump11289f42009-09-09 15:08:12 +00003074 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCallbcd03502009-12-07 02:54:59 +00003075 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl6f282892008-11-11 17:56:53 +00003076 Context->getSizeType(),
3077 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003078 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3079 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3080 // For X86 it is more complicated and some kind of target specific routine
3081 // is needed to decide what to do.
Mike Stump11289f42009-09-09 15:08:12 +00003082 unsigned IntSize =
Chris Lattner37e05872008-03-05 18:54:05 +00003083 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Mike Stump11289f42009-09-09 15:08:12 +00003084 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003085 Context->IntTy,
3086 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00003087 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
3088 BinaryOperator::LE,
3089 Context->IntTy,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003090 SourceLocation());
3091 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump11289f42009-09-09 15:08:12 +00003092 ConditionalOperator *CondExpr =
Douglas Gregor7e112b02009-08-26 14:37:04 +00003093 new (Context) ConditionalOperator(lessThanExpr,
3094 SourceLocation(), CE,
3095 SourceLocation(), STCE, returnType);
Ted Kremenek5a201952009-02-07 01:47:29 +00003096 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003097 }
Mike Stump11289f42009-09-09 15:08:12 +00003098 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003099 return ReplacingStmt;
3100}
3101
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003102Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00003103 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3104 Exp->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003105
Steve Naroff574440f2007-10-24 22:48:43 +00003106 // Now do the actual rewrite.
Chris Lattner2e0d2602008-01-31 19:37:57 +00003107 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00003108
3109 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003110 return ReplacingStmt;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00003111}
3112
Steve Naroffd9803712009-04-29 16:37:50 +00003113// typedef struct objc_object Protocol;
3114QualType RewriteObjC::getProtocolType() {
3115 if (!ProtocolTypeDecl) {
John McCallbcd03502009-12-07 02:54:59 +00003116 TypeSourceInfo *TInfo
3117 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroffd9803712009-04-29 16:37:50 +00003118 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00003119 SourceLocation(),
Steve Naroffd9803712009-04-29 16:37:50 +00003120 &Context->Idents.get("Protocol"),
John McCallbcd03502009-12-07 02:54:59 +00003121 TInfo);
Steve Naroffd9803712009-04-29 16:37:50 +00003122 }
3123 return Context->getTypeDeclType(ProtocolTypeDecl);
3124}
3125
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00003126/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroffd9803712009-04-29 16:37:50 +00003127/// a synthesized/forward data reference (to the protocol's metadata).
3128/// The forward references (and metadata) are generated in
3129/// RewriteObjC::HandleTranslationUnit().
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003130Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroffd9803712009-04-29 16:37:50 +00003131 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3132 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump11289f42009-09-09 15:08:12 +00003133 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregorc4df4072010-04-19 22:54:31 +00003134 ID, getProtocolType(), 0,
3135 VarDecl::Extern, VarDecl::None);
Steve Naroffd9803712009-04-29 16:37:50 +00003136 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
3137 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
3138 Context->getPointerType(DRE->getType()),
3139 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00003140 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3141 CastExpr::CK_Unknown,
3142 DerefExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00003143 ReplaceStmt(Exp, castExpr);
3144 ProtocolExprDecls.insert(Exp->getProtocol());
Mike Stump11289f42009-09-09 15:08:12 +00003145 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00003146 return castExpr;
Mike Stump11289f42009-09-09 15:08:12 +00003147
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00003148}
3149
Mike Stump11289f42009-09-09 15:08:12 +00003150bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003151 const char *endBuf) {
3152 while (startBuf < endBuf) {
3153 if (*startBuf == '#') {
3154 // Skip whitespace.
3155 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3156 ;
3157 if (!strncmp(startBuf, "if", strlen("if")) ||
3158 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3159 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3160 !strncmp(startBuf, "define", strlen("define")) ||
3161 !strncmp(startBuf, "undef", strlen("undef")) ||
3162 !strncmp(startBuf, "else", strlen("else")) ||
3163 !strncmp(startBuf, "elif", strlen("elif")) ||
3164 !strncmp(startBuf, "endif", strlen("endif")) ||
3165 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3166 !strncmp(startBuf, "include", strlen("include")) ||
3167 !strncmp(startBuf, "import", strlen("import")) ||
3168 !strncmp(startBuf, "include_next", strlen("include_next")))
3169 return true;
3170 }
3171 startBuf++;
3172 }
3173 return false;
3174}
3175
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003176/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003177/// an objective-c class with ivars.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003178void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003179 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003180 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Mike Stump11289f42009-09-09 15:08:12 +00003181 assert(CDecl->getNameAsCString() &&
Douglas Gregor77324f32008-11-17 14:58:09 +00003182 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00003183 // Do not synthesize more than once.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003184 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00003185 return;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003186 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003187 int NumIvars = CDecl->ivar_size();
Steve Naroffdde78982007-11-14 19:25:57 +00003188 SourceLocation LocStart = CDecl->getLocStart();
3189 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00003190
Steve Naroffdde78982007-11-14 19:25:57 +00003191 const char *startBuf = SM->getCharacterData(LocStart);
3192 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00003193
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003194 // If no ivars and no root or if its root, directly or indirectly,
3195 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003196 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3197 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner184e65d2009-04-14 23:22:57 +00003198 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003199 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003200 return;
3201 }
Mike Stump11289f42009-09-09 15:08:12 +00003202
3203 // FIXME: This has potential of causing problem. If
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003204 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003205 Result += "\nstruct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003206 Result += CDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00003207 if (LangOpts.Microsoft)
3208 Result += "_IMPL";
Steve Naroffdc5b6b22008-03-12 00:25:36 +00003209
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003210 if (NumIvars > 0) {
Steve Naroffdde78982007-11-14 19:25:57 +00003211 const char *cursor = strchr(startBuf, '{');
Mike Stump11289f42009-09-09 15:08:12 +00003212 assert((cursor && endBuf)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003213 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003214 // If the buffer contains preprocessor directives, we do more fine-grained
3215 // rewrites. This is intended to fix code that looks like (which occurs in
3216 // NSURL.h, for example):
3217 //
3218 // #ifdef XYZ
3219 // @interface Foo : NSObject
3220 // #else
3221 // @interface FooBar : NSObject
3222 // #endif
3223 // {
3224 // int i;
3225 // }
3226 // @end
3227 //
3228 // This clause is segregated to avoid breaking the common case.
3229 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump11289f42009-09-09 15:08:12 +00003230 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003231 CDecl->getClassLoc();
3232 const char *endHeader = SM->getCharacterData(L);
Chris Lattner184e65d2009-04-14 23:22:57 +00003233 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003234
Chris Lattnerf5b77512009-02-20 18:18:36 +00003235 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003236 // advance to the end of the referenced protocols.
3237 while (endHeader < cursor && *endHeader != '>') endHeader++;
3238 endHeader++;
3239 }
3240 // rewrite the original header
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003241 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003242 } else {
3243 // rewrite the original header *without* disturbing the '{'
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003244 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003245 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003246 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroffdde78982007-11-14 19:25:57 +00003247 Result = "\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003248 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003249 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003250 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003251 Result += "_IVARS;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003252
Steve Naroffdde78982007-11-14 19:25:57 +00003253 // insert the super class structure definition.
Chris Lattner1780a852008-01-31 19:42:41 +00003254 SourceLocation OnePastCurly =
3255 LocStart.getFileLocWithOffset(cursor-startBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003256 InsertText(OnePastCurly, Result);
Steve Naroffdde78982007-11-14 19:25:57 +00003257 }
3258 cursor++; // past '{'
Mike Stump11289f42009-09-09 15:08:12 +00003259
Steve Naroffdde78982007-11-14 19:25:57 +00003260 // Now comment out any visibility specifiers.
3261 while (cursor < endBuf) {
3262 if (*cursor == '@') {
3263 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner174a8252007-11-14 22:57:51 +00003264 // Skip whitespace.
3265 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3266 /*scan*/;
3267
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003268 // FIXME: presence of @public, etc. inside comment results in
3269 // this transformation as well, which is still correct c-code.
Steve Naroffdde78982007-11-14 19:25:57 +00003270 if (!strncmp(cursor, "public", strlen("public")) ||
3271 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffaf91b9a2008-04-04 22:34:24 +00003272 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003273 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003274 InsertText(atLoc, "// ");
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003275 }
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003276 // FIXME: If there are cases where '<' is used in ivar declaration part
3277 // of user code, then scan the ivar list and use needToScanForQualifiers
3278 // for type checking.
3279 else if (*cursor == '<') {
3280 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003281 InsertText(atLoc, "/* ");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003282 cursor = strchr(cursor, '>');
3283 cursor++;
3284 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003285 InsertText(atLoc, " */");
Steve Naroff295570a2008-10-30 12:09:33 +00003286 } else if (*cursor == '^') { // rewrite block specifier.
3287 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003288 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003289 }
Steve Naroffdde78982007-11-14 19:25:57 +00003290 cursor++;
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003291 }
Steve Naroffdde78982007-11-14 19:25:57 +00003292 // Don't forget to add a ';'!!
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003293 InsertText(LocEnd.getFileLocWithOffset(1), ";");
Steve Naroffdde78982007-11-14 19:25:57 +00003294 } else { // we don't have any instance variables - insert super struct.
Chris Lattner184e65d2009-04-14 23:22:57 +00003295 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroffdde78982007-11-14 19:25:57 +00003296 Result += " {\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003297 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003298 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003299 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003300 Result += "_IVARS;\n};\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003301 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003302 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003303 // Mark this struct as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003304 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff13e74872008-05-06 18:26:51 +00003305 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003306}
3307
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003308// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003309/// class methods.
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003310template<typename MethodIterator>
3311void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3312 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +00003313 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003314 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +00003315 const char *ClassName,
3316 std::string &Result) {
Chris Lattner31bc07e2007-12-12 07:46:12 +00003317 if (MethodBegin == MethodEnd) return;
Mike Stump11289f42009-09-09 15:08:12 +00003318
Chris Lattner31bc07e2007-12-12 07:46:12 +00003319 if (!objc_impl_method) {
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003320 /* struct _objc_method {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003321 SEL _cmd;
3322 char *method_types;
3323 void *_imp;
3324 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003325 */
Chris Lattner211f8b82007-10-25 17:07:24 +00003326 Result += "\nstruct _objc_method {\n";
3327 Result += "\tSEL _cmd;\n";
3328 Result += "\tchar *method_types;\n";
3329 Result += "\tvoid *_imp;\n";
3330 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003331
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003332 objc_impl_method = true;
Fariborz Jahanian74a1cfa2007-10-19 00:36:46 +00003333 }
Mike Stump11289f42009-09-09 15:08:12 +00003334
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003335 // Build _objc_method_list for class's methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003336
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003337 /* struct {
3338 struct _objc_method_list *next_method;
3339 int method_count;
3340 struct _objc_method method_list[];
3341 }
3342 */
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003343 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003344 Result += "\nstatic struct {\n";
3345 Result += "\tstruct _objc_method_list *next_method;\n";
3346 Result += "\tint method_count;\n";
3347 Result += "\tstruct _objc_method method_list[";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003348 Result += utostr(NumMethods);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003349 Result += "];\n} _OBJC_";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003350 Result += prefix;
3351 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3352 Result += "_METHODS_";
3353 Result += ClassName;
Steve Naroffb327e492008-03-12 17:18:30 +00003354 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003355 Result += IsInstanceMethod ? "inst" : "cls";
3356 Result += "_meth\")))= ";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003357 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003358
Chris Lattner31bc07e2007-12-12 07:46:12 +00003359 Result += "\t,{{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003360 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattner31bc07e2007-12-12 07:46:12 +00003361 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003362 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattner31bc07e2007-12-12 07:46:12 +00003363 Result += "\", \"";
3364 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003365 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003366 Result += MethodInternalNames[*MethodBegin];
3367 Result += "}\n";
3368 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3369 Result += "\t ,{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003370 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003371 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003372 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003373 Result += "\", \"";
3374 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003375 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003376 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanian56338352007-11-13 21:02:00 +00003377 Result += "}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003378 }
Chris Lattner31bc07e2007-12-12 07:46:12 +00003379 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003380}
3381
Steve Naroffd9803712009-04-29 16:37:50 +00003382/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner390d39a2008-07-21 21:32:27 +00003383void RewriteObjC::
Steve Naroffd9803712009-04-29 16:37:50 +00003384RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
3385 const char *ClassName, std::string &Result) {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003386 static bool objc_protocol_methods = false;
Steve Naroffd9803712009-04-29 16:37:50 +00003387
3388 // Output struct protocol_methods holder of method selector and type.
3389 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3390 /* struct protocol_methods {
3391 SEL _cmd;
3392 char *method_types;
3393 }
3394 */
3395 Result += "\nstruct _protocol_methods {\n";
3396 Result += "\tstruct objc_selector *_cmd;\n";
3397 Result += "\tchar *method_types;\n";
3398 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003399
Steve Naroffd9803712009-04-29 16:37:50 +00003400 objc_protocol_methods = true;
3401 }
3402 // Do not synthesize the protocol more than once.
3403 if (ObjCSynthesizedProtocols.count(PDecl))
3404 return;
Mike Stump11289f42009-09-09 15:08:12 +00003405
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003406 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3407 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3408 PDecl->instmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003409 /* struct _objc_protocol_method_list {
3410 int protocol_method_count;
3411 struct protocol_methods protocols[];
3412 }
Steve Naroff251084d2008-03-12 01:06:30 +00003413 */
Steve Naroffd9803712009-04-29 16:37:50 +00003414 Result += "\nstatic struct {\n";
3415 Result += "\tint protocol_method_count;\n";
3416 Result += "\tstruct _protocol_methods protocol_methods[";
3417 Result += utostr(NumMethods);
3418 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3419 Result += PDecl->getNameAsString();
3420 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3421 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003422
Steve Naroffd9803712009-04-29 16:37:50 +00003423 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003424 for (ObjCProtocolDecl::instmeth_iterator
3425 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003426 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003427 if (I == PDecl->instmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003428 Result += "\t ,{{(struct objc_selector *)\"";
3429 else
3430 Result += "\t ,{(struct objc_selector *)\"";
3431 Result += (*I)->getSelector().getAsString().c_str();
3432 std::string MethodTypeString;
3433 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3434 Result += "\", \"";
3435 Result += MethodTypeString;
3436 Result += "\"}\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003437 }
Steve Naroffd9803712009-04-29 16:37:50 +00003438 Result += "\t }\n};\n";
3439 }
Mike Stump11289f42009-09-09 15:08:12 +00003440
Steve Naroffd9803712009-04-29 16:37:50 +00003441 // Output class methods declared in this protocol.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003442 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3443 PDecl->classmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003444 if (NumMethods > 0) {
3445 /* struct _objc_protocol_method_list {
3446 int protocol_method_count;
3447 struct protocol_methods protocols[];
3448 }
3449 */
3450 Result += "\nstatic struct {\n";
3451 Result += "\tint protocol_method_count;\n";
3452 Result += "\tstruct _protocol_methods protocol_methods[";
3453 Result += utostr(NumMethods);
3454 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3455 Result += PDecl->getNameAsString();
3456 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3457 "{\n\t";
3458 Result += utostr(NumMethods);
3459 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003460
Steve Naroffd9803712009-04-29 16:37:50 +00003461 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003462 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003463 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003464 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003465 if (I == PDecl->classmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003466 Result += "\t ,{{(struct objc_selector *)\"";
3467 else
3468 Result += "\t ,{(struct objc_selector *)\"";
3469 Result += (*I)->getSelector().getAsString().c_str();
3470 std::string MethodTypeString;
3471 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3472 Result += "\", \"";
3473 Result += MethodTypeString;
3474 Result += "\"}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003475 }
Steve Naroffd9803712009-04-29 16:37:50 +00003476 Result += "\t }\n};\n";
3477 }
3478
3479 // Output:
3480 /* struct _objc_protocol {
3481 // Objective-C 1.0 extensions
3482 struct _objc_protocol_extension *isa;
3483 char *protocol_name;
3484 struct _objc_protocol **protocol_list;
3485 struct _objc_protocol_method_list *instance_methods;
3486 struct _objc_protocol_method_list *class_methods;
Mike Stump11289f42009-09-09 15:08:12 +00003487 };
Steve Naroffd9803712009-04-29 16:37:50 +00003488 */
3489 static bool objc_protocol = false;
3490 if (!objc_protocol) {
3491 Result += "\nstruct _objc_protocol {\n";
3492 Result += "\tstruct _objc_protocol_extension *isa;\n";
3493 Result += "\tchar *protocol_name;\n";
3494 Result += "\tstruct _objc_protocol **protocol_list;\n";
3495 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3496 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003497 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003498
Steve Naroffd9803712009-04-29 16:37:50 +00003499 objc_protocol = true;
Chris Lattner388f6e92008-07-21 21:33:21 +00003500 }
Mike Stump11289f42009-09-09 15:08:12 +00003501
Steve Naroffd9803712009-04-29 16:37:50 +00003502 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3503 Result += PDecl->getNameAsString();
3504 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3505 "{\n\t0, \"";
3506 Result += PDecl->getNameAsString();
3507 Result += "\", 0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003508 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003509 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3510 Result += PDecl->getNameAsString();
3511 Result += ", ";
3512 }
3513 else
3514 Result += "0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003515 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003516 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3517 Result += PDecl->getNameAsString();
3518 Result += "\n";
3519 }
3520 else
3521 Result += "0\n";
3522 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003523
Steve Naroffd9803712009-04-29 16:37:50 +00003524 // Mark this protocol as having been generated.
3525 if (!ObjCSynthesizedProtocols.insert(PDecl))
3526 assert(false && "protocol already synthesized");
3527
3528}
3529
3530void RewriteObjC::
3531RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3532 const char *prefix, const char *ClassName,
3533 std::string &Result) {
3534 if (Protocols.empty()) return;
Mike Stump11289f42009-09-09 15:08:12 +00003535
Steve Naroffd9803712009-04-29 16:37:50 +00003536 for (unsigned i = 0; i != Protocols.size(); i++)
3537 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3538
Chris Lattner388f6e92008-07-21 21:33:21 +00003539 // Output the top lovel protocol meta-data for the class.
3540 /* struct _objc_protocol_list {
3541 struct _objc_protocol_list *next;
3542 int protocol_count;
3543 struct _objc_protocol *class_protocols[];
3544 }
3545 */
3546 Result += "\nstatic struct {\n";
3547 Result += "\tstruct _objc_protocol_list *next;\n";
3548 Result += "\tint protocol_count;\n";
3549 Result += "\tstruct _objc_protocol *class_protocols[";
3550 Result += utostr(Protocols.size());
3551 Result += "];\n} _OBJC_";
3552 Result += prefix;
3553 Result += "_PROTOCOLS_";
3554 Result += ClassName;
3555 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3556 "{\n\t0, ";
3557 Result += utostr(Protocols.size());
3558 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003559
Chris Lattner388f6e92008-07-21 21:33:21 +00003560 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003561 Result += Protocols[0]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003562 Result += " \n";
Mike Stump11289f42009-09-09 15:08:12 +00003563
Chris Lattner388f6e92008-07-21 21:33:21 +00003564 for (unsigned i = 1; i != Protocols.size(); i++) {
3565 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003566 Result += Protocols[i]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003567 Result += "\n";
3568 }
3569 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003570}
3571
Steve Naroffd9803712009-04-29 16:37:50 +00003572
Mike Stump11289f42009-09-09 15:08:12 +00003573/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003574/// implementation.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003575void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003576 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003577 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003578 // Find category declaration for this implementation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003579 ObjCCategoryDecl *CDecl;
Mike Stump11289f42009-09-09 15:08:12 +00003580 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003581 CDecl = CDecl->getNextClassCategory())
3582 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3583 break;
Mike Stump11289f42009-09-09 15:08:12 +00003584
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003585 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003586 FullCategoryName += '_';
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003587 FullCategoryName += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003588
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003589 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003590 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003591 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003592
3593 // If any of our property implementations have associated getters or
3594 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003595 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3596 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003597 Prop != PropEnd; ++Prop) {
3598 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3599 continue;
3600 if (!(*Prop)->getPropertyIvarDecl())
3601 continue;
3602 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3603 if (!PD)
3604 continue;
3605 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3606 InstanceMethods.push_back(Getter);
3607 if (PD->isReadOnly())
3608 continue;
3609 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3610 InstanceMethods.push_back(Setter);
3611 }
3612 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003613 true, "CATEGORY_", FullCategoryName.c_str(),
3614 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003615
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003616 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003617 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003618 false, "CATEGORY_", FullCategoryName.c_str(),
3619 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003620
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003621 // Protocols referenced in class declaration?
Fariborz Jahanian989e0392007-11-13 22:09:49 +00003622 // Null CDecl is case of a category implementation with no category interface
3623 if (CDecl)
Steve Naroffd9803712009-04-29 16:37:50 +00003624 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3625 FullCategoryName.c_str(), Result);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003626 /* struct _objc_category {
3627 char *category_name;
3628 char *class_name;
3629 struct _objc_method_list *instance_methods;
3630 struct _objc_method_list *class_methods;
3631 struct _objc_protocol_list *protocols;
3632 // Objective-C 1.0 extensions
3633 uint32_t size; // sizeof (struct _objc_category)
Mike Stump11289f42009-09-09 15:08:12 +00003634 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003635 // @property decl.
Mike Stump11289f42009-09-09 15:08:12 +00003636 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003637 */
Mike Stump11289f42009-09-09 15:08:12 +00003638
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003639 static bool objc_category = false;
3640 if (!objc_category) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003641 Result += "\nstruct _objc_category {\n";
3642 Result += "\tchar *category_name;\n";
3643 Result += "\tchar *class_name;\n";
3644 Result += "\tstruct _objc_method_list *instance_methods;\n";
3645 Result += "\tstruct _objc_method_list *class_methods;\n";
3646 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003647 Result += "\tunsigned int size;\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003648 Result += "\tstruct _objc_property_list *instance_properties;\n";
3649 Result += "};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003650 objc_category = true;
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003651 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003652 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3653 Result += FullCategoryName;
Steve Naroffb327e492008-03-12 17:18:30 +00003654 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003655 Result += IDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003656 Result += "\"\n\t, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003657 Result += ClassDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003658 Result += "\"\n";
Mike Stump11289f42009-09-09 15:08:12 +00003659
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003660 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003661 Result += "\t, (struct _objc_method_list *)"
3662 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3663 Result += FullCategoryName;
3664 Result += "\n";
3665 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003666 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003667 Result += "\t, 0\n";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003668 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003669 Result += "\t, (struct _objc_method_list *)"
3670 "&_OBJC_CATEGORY_CLASS_METHODS_";
3671 Result += FullCategoryName;
3672 Result += "\n";
3673 }
3674 else
3675 Result += "\t, 0\n";
Mike Stump11289f42009-09-09 15:08:12 +00003676
Chris Lattnerf5b77512009-02-20 18:18:36 +00003677 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump11289f42009-09-09 15:08:12 +00003678 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003679 Result += FullCategoryName;
3680 Result += "\n";
3681 }
3682 else
3683 Result += "\t, 0\n";
3684 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003685}
3686
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003687/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3688/// ivar offset.
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00003689void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCContainerDecl *IDecl,
Mike Stump11289f42009-09-09 15:08:12 +00003690 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003691 std::string &Result) {
Steve Naroffde7d0f62008-07-16 18:22:22 +00003692 if (ivar->isBitField()) {
3693 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3694 // place all bitfields at offset 0.
3695 Result += "0";
3696 } else {
3697 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003698 Result += IDecl->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003699 if (LangOpts.Microsoft)
3700 Result += "_IMPL";
3701 Result += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003702 Result += ivar->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003703 Result += ")";
3704 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003705}
3706
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003707//===----------------------------------------------------------------------===//
3708// Meta Data Emission
3709//===----------------------------------------------------------------------===//
3710
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003711void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003712 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003713 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00003714
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003715 // Explictly declared @interface's are already synthesized.
Steve Naroffaac654a2009-04-20 20:09:33 +00003716 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump11289f42009-09-09 15:08:12 +00003717 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003718 // produce correct synthesis as yet.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003719 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003720 }
Mike Stump11289f42009-09-09 15:08:12 +00003721
Chris Lattner30d23e82007-12-12 07:56:42 +00003722 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003723 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump11289f42009-09-09 15:08:12 +00003724 ? IDecl->ivar_size()
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003725 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003726 if (NumIvars > 0) {
3727 static bool objc_ivar = false;
3728 if (!objc_ivar) {
3729 /* struct _objc_ivar {
3730 char *ivar_name;
3731 char *ivar_type;
3732 int ivar_offset;
Mike Stump11289f42009-09-09 15:08:12 +00003733 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003734 */
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003735 Result += "\nstruct _objc_ivar {\n";
3736 Result += "\tchar *ivar_name;\n";
3737 Result += "\tchar *ivar_type;\n";
3738 Result += "\tint ivar_offset;\n";
3739 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003740
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003741 objc_ivar = true;
3742 }
3743
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003744 /* struct {
3745 int ivar_count;
3746 struct _objc_ivar ivar_list[nIvars];
Mike Stump11289f42009-09-09 15:08:12 +00003747 };
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003748 */
Mike Stump11289f42009-09-09 15:08:12 +00003749 Result += "\nstatic struct {\n";
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003750 Result += "\tint ivar_count;\n";
3751 Result += "\tstruct _objc_ivar ivar_list[";
3752 Result += utostr(NumIvars);
3753 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003754 Result += IDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003755 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003756 "{\n\t";
3757 Result += utostr(NumIvars);
3758 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003759
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003760 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor5f662052009-04-23 03:23:08 +00003761 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003762 if (!IDecl->ivar_empty()) {
Fariborz Jahanianaef66222010-02-19 00:31:17 +00003763 for (ObjCInterfaceDecl::ivar_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003764 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor5f662052009-04-23 03:23:08 +00003765 IV != IVEnd; ++IV)
3766 IVars.push_back(*IV);
Fariborz Jahanianaef66222010-02-19 00:31:17 +00003767 IVI = IDecl->ivar_begin();
3768 IVE = IDecl->ivar_end();
Chris Lattner30d23e82007-12-12 07:56:42 +00003769 } else {
3770 IVI = CDecl->ivar_begin();
3771 IVE = CDecl->ivar_end();
3772 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003773 Result += "\t,{{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003774 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003775 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003776 std::string TmpString, StrEncoding;
3777 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3778 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003779 Result += StrEncoding;
3780 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003781 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003782 Result += "}\n";
Chris Lattner30d23e82007-12-12 07:56:42 +00003783 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003784 Result += "\t ,{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003785 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003786 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003787 std::string TmpString, StrEncoding;
3788 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3789 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003790 Result += StrEncoding;
3791 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003792 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003793 Result += "}\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003794 }
Mike Stump11289f42009-09-09 15:08:12 +00003795
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003796 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003797 }
Mike Stump11289f42009-09-09 15:08:12 +00003798
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003799 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003800 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003801 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003802
3803 // If any of our property implementations have associated getters or
3804 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003805 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3806 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003807 Prop != PropEnd; ++Prop) {
3808 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3809 continue;
3810 if (!(*Prop)->getPropertyIvarDecl())
3811 continue;
3812 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3813 if (!PD)
3814 continue;
3815 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3816 InstanceMethods.push_back(Getter);
3817 if (PD->isReadOnly())
3818 continue;
3819 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3820 InstanceMethods.push_back(Setter);
3821 }
3822 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003823 true, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003824
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003825 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003826 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003827 false, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003828
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003829 // Protocols referenced in class declaration?
Steve Naroffd9803712009-04-29 16:37:50 +00003830 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3831 "CLASS", CDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003832
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003833 // Declaration of class/meta-class metadata
3834 /* struct _objc_class {
3835 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003836 const char *super_class_name;
3837 char *name;
3838 long version;
3839 long info;
3840 long instance_size;
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003841 struct _objc_ivar_list *ivars;
3842 struct _objc_method_list *methods;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003843 struct objc_cache *cache;
3844 struct objc_protocol_list *protocols;
3845 const char *ivar_layout;
3846 struct _objc_class_ext *ext;
Mike Stump11289f42009-09-09 15:08:12 +00003847 };
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003848 */
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003849 static bool objc_class = false;
3850 if (!objc_class) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003851 Result += "\nstruct _objc_class {\n";
3852 Result += "\tstruct _objc_class *isa;\n";
3853 Result += "\tconst char *super_class_name;\n";
3854 Result += "\tchar *name;\n";
3855 Result += "\tlong version;\n";
3856 Result += "\tlong info;\n";
3857 Result += "\tlong instance_size;\n";
3858 Result += "\tstruct _objc_ivar_list *ivars;\n";
3859 Result += "\tstruct _objc_method_list *methods;\n";
3860 Result += "\tstruct objc_cache *cache;\n";
3861 Result += "\tstruct _objc_protocol_list *protocols;\n";
3862 Result += "\tconst char *ivar_layout;\n";
3863 Result += "\tstruct _objc_class_ext *ext;\n";
3864 Result += "};\n";
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003865 objc_class = true;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003866 }
Mike Stump11289f42009-09-09 15:08:12 +00003867
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003868 // Meta-class metadata generation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003869 ObjCInterfaceDecl *RootClass = 0;
3870 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003871 while (SuperClass) {
3872 RootClass = SuperClass;
3873 SuperClass = SuperClass->getSuperClass();
3874 }
3875 SuperClass = CDecl->getSuperClass();
Mike Stump11289f42009-09-09 15:08:12 +00003876
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003877 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003878 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003879 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003880 "{\n\t(struct _objc_class *)\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003881 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003882 Result += "\"";
3883
3884 if (SuperClass) {
3885 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003886 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003887 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003888 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003889 Result += "\"";
3890 }
3891 else {
3892 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003893 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003894 Result += "\"";
3895 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003896 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003897 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003898 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003899 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff0b844f02008-03-11 18:14:26 +00003900 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003901 Result += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003902 Result += "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003903 }
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003904 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003905 Result += ", 0\n";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003906 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003907 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003908 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003909 Result += ",0,0\n";
3910 }
Fariborz Jahanian486f7182007-10-24 20:54:23 +00003911 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003912 Result += "\t,0,0,0,0\n";
3913 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003914
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003915 // class metadata generation.
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003916 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003917 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003918 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003919 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003920 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003921 if (SuperClass) {
3922 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003923 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003924 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003925 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003926 Result += "\"";
3927 }
3928 else {
3929 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003930 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003931 Result += "\"";
3932 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003933 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003934 Result += ", 0,1";
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003935 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003936 Result += ",0";
3937 else {
3938 // class has size. Must synthesize its size.
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00003939 Result += ",sizeof(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003940 Result += CDecl->getNameAsString();
Steve Naroff14a07462008-03-10 23:33:22 +00003941 if (LangOpts.Microsoft)
3942 Result += "_IMPL";
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003943 Result += ")";
3944 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003945 if (NumIvars > 0) {
Steve Naroff17978c42008-03-11 17:37:02 +00003946 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003947 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003948 Result += "\n\t";
3949 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003950 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003951 Result += ",0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003952 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003953 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003954 Result += CDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003955 Result += ", 0\n\t";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003956 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003957 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003958 Result += ",0,0";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003959 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003960 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003961 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003962 Result += ", 0,0\n";
3963 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003964 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003965 Result += ",0,0,0\n";
3966 Result += "};\n";
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003967}
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003968
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003969/// RewriteImplementations - This routine rewrites all method implementations
3970/// and emits meta-data.
3971
Steve Narofff8cfd162008-11-13 20:07:04 +00003972void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003973 int ClsDefCount = ClassImplementation.size();
3974 int CatDefCount = CategoryImplementation.size();
Mike Stump11289f42009-09-09 15:08:12 +00003975
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003976 // Rewrite implemented methods
3977 for (int i = 0; i < ClsDefCount; i++)
3978 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003979
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00003980 for (int i = 0; i < CatDefCount; i++)
3981 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofff8cfd162008-11-13 20:07:04 +00003982}
Mike Stump11289f42009-09-09 15:08:12 +00003983
Steve Narofff8cfd162008-11-13 20:07:04 +00003984void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3985 int ClsDefCount = ClassImplementation.size();
3986 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00003987
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003988 // For each implemented class, write out all its meta data.
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003989 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003990 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump11289f42009-09-09 15:08:12 +00003991
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003992 // For each implemented category, write out all its meta data.
3993 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003994 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroffd9803712009-04-29 16:37:50 +00003995
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003996 // Write objc_symtab metadata
3997 /*
3998 struct _objc_symtab
3999 {
4000 long sel_ref_cnt;
4001 SEL *refs;
4002 short cls_def_cnt;
4003 short cat_def_cnt;
4004 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump11289f42009-09-09 15:08:12 +00004005 };
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004006 */
Mike Stump11289f42009-09-09 15:08:12 +00004007
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004008 Result += "\nstruct _objc_symtab {\n";
4009 Result += "\tlong sel_ref_cnt;\n";
4010 Result += "\tSEL *refs;\n";
4011 Result += "\tshort cls_def_cnt;\n";
4012 Result += "\tshort cat_def_cnt;\n";
4013 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
4014 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00004015
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004016 Result += "static struct _objc_symtab "
Steve Naroffb327e492008-03-12 17:18:30 +00004017 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00004018 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004019 + ", " + utostr(CatDefCount) + "\n";
4020 for (int i = 0; i < ClsDefCount; i++) {
4021 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004022 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004023 Result += "\n";
4024 }
Mike Stump11289f42009-09-09 15:08:12 +00004025
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004026 for (int i = 0; i < CatDefCount; i++) {
4027 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004028 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004029 Result += "_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004030 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004031 Result += "\n";
4032 }
Mike Stump11289f42009-09-09 15:08:12 +00004033
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004034 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00004035
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004036 // Write objc_module metadata
Mike Stump11289f42009-09-09 15:08:12 +00004037
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004038 /*
4039 struct _objc_module {
4040 long version;
4041 long size;
4042 const char *name;
4043 struct _objc_symtab *symtab;
4044 }
4045 */
Mike Stump11289f42009-09-09 15:08:12 +00004046
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004047 Result += "\nstruct _objc_module {\n";
4048 Result += "\tlong version;\n";
4049 Result += "\tlong size;\n";
4050 Result += "\tconst char *name;\n";
4051 Result += "\tstruct _objc_symtab *symtab;\n";
4052 Result += "};\n\n";
4053 Result += "static struct _objc_module "
Steve Naroffb327e492008-03-12 17:18:30 +00004054 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00004055 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00004056 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00004057 Result += "};\n\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00004058
4059 if (LangOpts.Microsoft) {
Steve Naroffd9803712009-04-29 16:37:50 +00004060 if (ProtocolExprDecls.size()) {
4061 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
4062 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump11289f42009-09-09 15:08:12 +00004063 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00004064 E = ProtocolExprDecls.end(); I != E; ++I) {
4065 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
4066 Result += (*I)->getNameAsString();
4067 Result += " = &_OBJC_PROTOCOL_";
4068 Result += (*I)->getNameAsString();
4069 Result += ";\n";
4070 }
4071 Result += "#pragma data_seg(pop)\n\n";
4072 }
Steve Naroff945a3b12008-03-10 20:43:59 +00004073 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffcab93d52008-05-07 00:06:16 +00004074 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00004075 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
4076 Result += "&_OBJC_MODULES;\n";
4077 Result += "#pragma data_seg(pop)\n\n";
4078 }
Fariborz Jahanian93191af2007-10-18 19:23:00 +00004079}
Chris Lattnera7c19fe2007-10-16 22:36:42 +00004080
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004081void RewriteObjC::RewriteByRefString(std::string &ResultStr,
4082 const std::string &Name,
4083 ValueDecl *VD) {
4084 assert(BlockByRefDeclNo.count(VD) &&
4085 "RewriteByRefString: ByRef decl missing");
4086 ResultStr += "struct __Block_byref_" + Name +
4087 "_" + utostr(BlockByRefDeclNo[VD]) ;
4088}
4089
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004090static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4091 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4092 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4093 return false;
4094}
4095
Steve Naroff677ab3a2008-10-27 17:20:55 +00004096std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4097 const char *funcName,
4098 std::string Tag) {
4099 const FunctionType *AFT = CE->getFunctionType();
4100 QualType RT = AFT->getResultType();
4101 std::string StructRef = "struct " + Tag;
4102 std::string S = "static " + RT.getAsString() + " __" +
4103 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00004104
Steve Naroff677ab3a2008-10-27 17:20:55 +00004105 BlockDecl *BD = CE->getBlockDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004106
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004107 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump11289f42009-09-09 15:08:12 +00004108 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Narofff26a1d42009-02-02 17:19:26 +00004109 // block (to reference imported block decl refs).
4110 S += "(" + StructRef + " *__cself)";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004111 } else if (BD->param_empty()) {
4112 S += "(" + StructRef + " *__cself)";
4113 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004114 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004115 assert(FT && "SynthesizeBlockFunc: No function proto");
4116 S += '(';
4117 // first add the implicit argument.
4118 S += StructRef + " *__cself, ";
4119 std::string ParamStr;
4120 for (BlockDecl::param_iterator AI = BD->param_begin(),
4121 E = BD->param_end(); AI != E; ++AI) {
4122 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004123 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004124 QualType QT = (*AI)->getType();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00004125 if (convertBlockPointerToFunctionPointer(QT))
4126 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004127 else
4128 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004129 S += ParamStr;
4130 }
4131 if (FT->isVariadic()) {
4132 if (!BD->param_empty()) S += ", ";
4133 S += "...";
4134 }
4135 S += ')';
4136 }
4137 S += " {\n";
Mike Stump11289f42009-09-09 15:08:12 +00004138
Steve Naroff677ab3a2008-10-27 17:20:55 +00004139 // Create local declarations to avoid rewriting all closure decl ref exprs.
4140 // First, emit a declaration for all "by ref" decls.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004141 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004142 E = BlockByRefDecls.end(); I != E; ++I) {
4143 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004144 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004145 std::string TypeString;
4146 RewriteByRefString(TypeString, Name, (*I));
4147 TypeString += " *";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004148 Name = TypeString + Name;
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004149 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump11289f42009-09-09 15:08:12 +00004150 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004151 // Next, emit a declaration for all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004152 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004153 E = BlockByCopyDecls.end(); I != E; ++I) {
4154 S += " ";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004155 // Handle nested closure invocation. For example:
4156 //
4157 // void (^myImportedClosure)(void);
4158 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00004159 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00004160 // void (^anotherClosure)(void);
4161 // anotherClosure = ^(void) {
4162 // myImportedClosure(); // import and invoke the closure
4163 // };
4164 //
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00004165 if (isTopLevelBlockPointerType((*I)->getType())) {
4166 RewriteBlockPointerTypeVariable(S, (*I));
4167 S += " = (";
4168 RewriteBlockPointerType(S, (*I)->getType());
4169 S += ")";
4170 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4171 }
4172 else {
Fariborz Jahanianb6a68c02010-02-16 17:26:03 +00004173 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004174 QualType QT = (*I)->getType();
4175 if (HasLocalVariableExternalStorage(*I))
4176 QT = Context->getPointerType(QT);
4177 QT.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00004178 S += Name + " = __cself->" +
4179 (*I)->getNameAsString() + "; // bound by copy\n";
4180 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004181 }
4182 std::string RewrittenStr = RewrittenBlockExprs[CE];
4183 const char *cstr = RewrittenStr.c_str();
4184 while (*cstr++ != '{') ;
4185 S += cstr;
4186 S += "\n";
4187 return S;
4188}
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00004189
Steve Naroff677ab3a2008-10-27 17:20:55 +00004190std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4191 const char *funcName,
4192 std::string Tag) {
4193 std::string StructRef = "struct " + Tag;
4194 std::string S = "static void __";
Mike Stump11289f42009-09-09 15:08:12 +00004195
Steve Naroff677ab3a2008-10-27 17:20:55 +00004196 S += funcName;
4197 S += "_block_copy_" + utostr(i);
4198 S += "(" + StructRef;
4199 S += "*dst, " + StructRef;
4200 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00004201 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004202 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00004203 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004204 S += (*I)->getNameAsString();
Steve Naroff5ac4eac2008-12-11 20:51:38 +00004205 S += ", (void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004206 S += (*I)->getNameAsString();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004207 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004208 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00004209 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004210 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004211 }
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00004212 S += "}\n";
4213
Steve Naroff677ab3a2008-10-27 17:20:55 +00004214 S += "\nstatic void __";
4215 S += funcName;
4216 S += "_block_dispose_" + utostr(i);
4217 S += "(" + StructRef;
4218 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00004219 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004220 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00004221 S += "_Block_object_dispose((void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004222 S += (*I)->getNameAsString();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004223 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004224 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00004225 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004226 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004227 }
Mike Stump11289f42009-09-09 15:08:12 +00004228 S += "}\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004229 return S;
4230}
4231
Steve Naroff30484702009-12-06 21:14:13 +00004232std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4233 std::string Desc) {
Steve Naroff295570a2008-10-30 12:09:33 +00004234 std::string S = "\nstruct " + Tag;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004235 std::string Constructor = " " + Tag;
Mike Stump11289f42009-09-09 15:08:12 +00004236
Steve Naroff677ab3a2008-10-27 17:20:55 +00004237 S += " {\n struct __block_impl impl;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004238 S += " struct " + Desc;
4239 S += "* Desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00004240
Steve Naroff30484702009-12-06 21:14:13 +00004241 Constructor += "(void *fp, "; // Invoke function pointer.
4242 Constructor += "struct " + Desc; // Descriptor pointer.
4243 Constructor += " *desc";
Mike Stump11289f42009-09-09 15:08:12 +00004244
Steve Naroff677ab3a2008-10-27 17:20:55 +00004245 if (BlockDeclRefs.size()) {
4246 // Output all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004247 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004248 E = BlockByCopyDecls.end(); I != E; ++I) {
4249 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004250 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004251 std::string ArgName = "_" + FieldName;
4252 // Handle nested closure invocation. For example:
4253 //
4254 // void (^myImportedBlock)(void);
4255 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00004256 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00004257 // void (^anotherBlock)(void);
4258 // anotherBlock = ^(void) {
4259 // myImportedBlock(); // import and invoke the closure
4260 // };
4261 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00004262 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004263 S += "struct __block_impl *";
4264 Constructor += ", void *" + ArgName;
4265 } else {
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004266 QualType QT = (*I)->getType();
4267 if (HasLocalVariableExternalStorage(*I))
4268 QT = Context->getPointerType(QT);
4269 QT.getAsStringInternal(FieldName, Context->PrintingPolicy);
4270 QT.getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004271 Constructor += ", " + ArgName;
4272 }
4273 S += FieldName + ";\n";
4274 }
4275 // Output all "by ref" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004276 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004277 E = BlockByRefDecls.end(); I != E; ++I) {
4278 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004279 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004280 std::string ArgName = "_" + FieldName;
4281 // Handle nested closure invocation. For example:
4282 //
4283 // void (^myImportedBlock)(void);
4284 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00004285 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00004286 // void (^anotherBlock)(void);
4287 // anotherBlock = ^(void) {
4288 // myImportedBlock(); // import and invoke the closure
4289 // };
4290 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00004291 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004292 S += "struct __block_impl *";
4293 Constructor += ", void *" + ArgName;
4294 } else {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004295 std::string TypeString;
4296 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004297 TypeString += " *";
4298 FieldName = TypeString + FieldName;
4299 ArgName = TypeString + ArgName;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004300 Constructor += ", " + ArgName;
4301 }
4302 S += FieldName + "; // by ref\n";
4303 }
4304 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004305 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00004306 if (GlobalVarDecl)
4307 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4308 else
4309 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004310 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00004311
Steve Naroff30484702009-12-06 21:14:13 +00004312 Constructor += " Desc = desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00004313
Steve Naroff677ab3a2008-10-27 17:20:55 +00004314 // Initialize all "by copy" arguments.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004315 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004316 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004317 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004318 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00004319 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004320 Constructor += Name + " = (struct __block_impl *)_";
4321 else
4322 Constructor += Name + " = _";
4323 Constructor += Name + ";\n";
4324 }
4325 // Initialize all "by ref" arguments.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004326 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004327 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004328 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004329 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00004330 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004331 Constructor += Name + " = (struct __block_impl *)_";
4332 else
4333 Constructor += Name + " = _";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004334 Constructor += Name + "->__forwarding;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004335 }
4336 } else {
4337 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004338 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00004339 if (GlobalVarDecl)
4340 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4341 else
4342 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004343 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4344 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004345 }
4346 Constructor += " ";
4347 Constructor += "}\n";
4348 S += Constructor;
4349 S += "};\n";
4350 return S;
4351}
4352
Steve Naroff30484702009-12-06 21:14:13 +00004353std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4354 std::string ImplTag, int i,
4355 const char *FunName,
4356 unsigned hasCopy) {
4357 std::string S = "\nstatic struct " + DescTag;
4358
4359 S += " {\n unsigned long reserved;\n";
4360 S += " unsigned long Block_size;\n";
4361 if (hasCopy) {
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004362 S += " void (*copy)(struct ";
4363 S += ImplTag; S += "*, struct ";
4364 S += ImplTag; S += "*);\n";
4365
4366 S += " void (*dispose)(struct ";
4367 S += ImplTag; S += "*);\n";
Steve Naroff30484702009-12-06 21:14:13 +00004368 }
4369 S += "} ";
4370
4371 S += DescTag + "_DATA = { 0, sizeof(struct ";
4372 S += ImplTag + ")";
4373 if (hasCopy) {
4374 S += ", __" + std::string(FunName) + "_block_copy_" + utostr(i);
4375 S += ", __" + std::string(FunName) + "_block_dispose_" + utostr(i);
4376 }
4377 S += "};\n";
4378 return S;
4379}
4380
Steve Naroff677ab3a2008-10-27 17:20:55 +00004381void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004382 const char *FunName) {
4383 // Insert declaration for the function in which block literal is used.
Fariborz Jahanian5c26eee2010-01-15 18:14:52 +00004384 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004385 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00004386 bool RewriteSC = (GlobalVarDecl &&
4387 !Blocks.empty() &&
4388 GlobalVarDecl->getStorageClass() == VarDecl::Static &&
4389 GlobalVarDecl->getType().getCVRQualifiers());
4390 if (RewriteSC) {
4391 std::string SC(" void __");
4392 SC += GlobalVarDecl->getNameAsString();
4393 SC += "() {}";
4394 InsertText(FunLocStart, SC);
4395 }
4396
Steve Naroff677ab3a2008-10-27 17:20:55 +00004397 // Insert closures that were part of the function.
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004398 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4399 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004400 // Need to copy-in the inner copied-in variables not actually used in this
4401 // block.
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004402 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4403 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
4404 ValueDecl *VD = Exp->getDecl();
4405 BlockDeclRefs.push_back(Exp);
4406 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4407 BlockByCopyDeclsPtrSet.insert(VD);
4408 BlockByCopyDecls.push_back(VD);
4409 }
4410 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4411 BlockByRefDeclsPtrSet.insert(VD);
4412 BlockByRefDecls.push_back(VD);
4413 }
4414 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004415
Steve Naroff30484702009-12-06 21:14:13 +00004416 std::string ImplTag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
4417 std::string DescTag = "__" + std::string(FunName) + "_block_desc_" + utostr(i);
Mike Stump11289f42009-09-09 15:08:12 +00004418
Steve Naroff30484702009-12-06 21:14:13 +00004419 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004420
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004421 InsertText(FunLocStart, CI);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004422
Steve Naroff30484702009-12-06 21:14:13 +00004423 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump11289f42009-09-09 15:08:12 +00004424
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004425 InsertText(FunLocStart, CF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004426
4427 if (ImportedBlockDecls.size()) {
Steve Naroff30484702009-12-06 21:14:13 +00004428 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004429 InsertText(FunLocStart, HF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004430 }
Steve Naroff30484702009-12-06 21:14:13 +00004431 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4432 ImportedBlockDecls.size() > 0);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004433 InsertText(FunLocStart, BD);
Mike Stump11289f42009-09-09 15:08:12 +00004434
Steve Naroff677ab3a2008-10-27 17:20:55 +00004435 BlockDeclRefs.clear();
4436 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004437 BlockByRefDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004438 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004439 BlockByCopyDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004440 ImportedBlockDecls.clear();
4441 }
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00004442 if (RewriteSC) {
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004443 // Must insert any 'const/volatile/static here. Since it has been
4444 // removed as result of rewriting of block literals.
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004445 std::string SC;
4446 if (GlobalVarDecl->getStorageClass() == VarDecl::Static)
4447 SC = "static ";
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004448 if (GlobalVarDecl->getType().isConstQualified())
4449 SC += "const ";
4450 if (GlobalVarDecl->getType().isVolatileQualified())
4451 SC += "volatile ";
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00004452 if (GlobalVarDecl->getType().isRestrictQualified())
4453 SC += "restrict ";
4454 InsertText(FunLocStart, SC);
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00004455 }
4456
Steve Naroff677ab3a2008-10-27 17:20:55 +00004457 Blocks.clear();
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004458 InnerDeclRefsCount.clear();
4459 InnerDeclRefs.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004460 RewrittenBlockExprs.clear();
4461}
4462
4463void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4464 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner86d7d912008-11-24 03:54:41 +00004465 const char *FuncName = FD->getNameAsCString();
Mike Stump11289f42009-09-09 15:08:12 +00004466
Steve Naroff677ab3a2008-10-27 17:20:55 +00004467 SynthesizeBlockLiterals(FunLocStart, FuncName);
4468}
4469
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004470static void BuildUniqueMethodName(std::string &Name,
4471 ObjCMethodDecl *MD) {
4472 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4473 Name = IFace->getNameAsCString();
4474 Name += "__" + MD->getSelector().getAsString();
4475 // Convert colons to underscores.
4476 std::string::size_type loc = 0;
4477 while ((loc = Name.find(":", loc)) != std::string::npos)
4478 Name.replace(loc, 1, "_");
4479}
4480
Steve Naroff677ab3a2008-10-27 17:20:55 +00004481void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff295570a2008-10-30 12:09:33 +00004482 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4483 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianb5f99c32010-01-29 01:55:49 +00004484 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004485 std::string FuncName;
4486 BuildUniqueMethodName(FuncName, MD);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004487 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
4488}
4489
4490void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4491 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4492 CI != E; ++CI)
4493 if (*CI) {
4494 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4495 GetBlockDeclRefExprs(CBE->getBody());
4496 else
4497 GetBlockDeclRefExprs(*CI);
4498 }
4499 // Handle specific things.
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004500 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004501 // FIXME: Handle enums.
4502 if (!isa<FunctionDecl>(CDRE->getDecl()))
4503 BlockDeclRefs.push_back(CDRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004504 }
4505 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4506 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
4507 BlockDeclRefExpr *BDRE =
4508 new (Context)BlockDeclRefExpr(DRE->getDecl(), DRE->getType(),
4509 DRE->getLocation(), false);
4510 BlockDeclRefs.push_back(BDRE);
4511 }
4512
Steve Naroff677ab3a2008-10-27 17:20:55 +00004513 return;
4514}
4515
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004516void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4517 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004518 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004519 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4520 CI != E; ++CI)
4521 if (*CI) {
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004522 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4523 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004524 GetInnerBlockDeclRefExprs(CBE->getBody(),
4525 InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004526 InnerContexts);
4527 }
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004528 else
4529 GetInnerBlockDeclRefExprs(*CI,
4530 InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004531 InnerContexts);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004532
4533 }
4534 // Handle specific things.
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004535 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004536 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004537 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004538 InnerBlockDeclRefs.push_back(CDRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004539 }
4540 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4541 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4542 if (Var->isFunctionOrMethodVarDecl())
4543 ImportedLocalExternalDecls.insert(Var);
4544 }
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004545
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004546 return;
4547}
4548
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004549/// convertFunctionTypeOfBlocks - This routine converts a function type
4550/// whose result type may be a block pointer or whose argument type(s)
4551/// might be block pointers to an equivalent funtion type replacing
4552/// all block pointers to function pointers.
4553QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4554 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4555 // FTP will be null for closures that don't take arguments.
4556 // Generate a funky cast.
4557 llvm::SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004558 QualType Res = FT->getResultType();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00004559 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004560
4561 if (FTP) {
4562 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4563 E = FTP->arg_type_end(); I && (I != E); ++I) {
4564 QualType t = *I;
4565 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00004566 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004567 HasBlockType = true;
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004568 ArgTypes.push_back(t);
4569 }
4570 }
4571 QualType FuncType;
4572 // FIXME. Does this work if block takes no argument but has a return type
4573 // which is of block type?
4574 if (HasBlockType)
4575 FuncType = Context->getFunctionType(Res,
4576 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0,
4577 false, false, 0, 0, FunctionType::ExtInfo());
4578 else FuncType = QualType(FT, 0);
4579 return FuncType;
4580}
4581
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004582Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004583 // Navigate to relevant type information.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004584 const BlockPointerType *CPT = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004585
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004586 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004587 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004588 } else if (const BlockDeclRefExpr *CDRE =
4589 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004590 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004591 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004592 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004593 }
4594 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4595 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4596 }
4597 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4598 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4599 else if (const ConditionalOperator *CEXPR =
4600 dyn_cast<ConditionalOperator>(BlockExp)) {
4601 Expr *LHSExp = CEXPR->getLHS();
4602 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4603 Expr *RHSExp = CEXPR->getRHS();
4604 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4605 Expr *CONDExp = CEXPR->getCond();
4606 ConditionalOperator *CondExpr =
4607 new (Context) ConditionalOperator(CONDExp,
4608 SourceLocation(), cast<Expr>(LHSStmt),
4609 SourceLocation(), cast<Expr>(RHSStmt),
4610 Exp->getType());
4611 return CondExpr;
Fariborz Jahanian6ab7ed42009-12-18 01:15:21 +00004612 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4613 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004614 } else {
4615 assert(1 && "RewriteBlockClass: Bad type");
4616 }
4617 assert(CPT && "RewriteBlockClass: Bad type");
John McCall9dd450b2009-09-21 23:43:11 +00004618 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004619 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004620 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004621 // FTP will be null for closures that don't take arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004622
Abramo Bagnara6150c882010-05-11 21:36:43 +00004623 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Steve Naroff350b6652008-10-30 10:07:53 +00004624 SourceLocation(),
4625 &Context->Idents.get("__block_impl"));
4626 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff677ab3a2008-10-27 17:20:55 +00004627
Steve Naroff350b6652008-10-30 10:07:53 +00004628 // Generate a funky cast.
4629 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00004630
Steve Naroff350b6652008-10-30 10:07:53 +00004631 // Push the block argument type.
4632 ArgTypes.push_back(PtrBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004633 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004634 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff350b6652008-10-30 10:07:53 +00004635 E = FTP->arg_type_end(); I && (I != E); ++I) {
4636 QualType t = *I;
4637 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00004638 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff350b6652008-10-30 10:07:53 +00004639 ArgTypes.push_back(t);
4640 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004641 }
Steve Naroff350b6652008-10-30 10:07:53 +00004642 // Now do the pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00004643 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00004644 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0,
4645 false, false, 0, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004646 FunctionType::ExtInfo());
Mike Stump11289f42009-09-09 15:08:12 +00004647
Steve Naroff350b6652008-10-30 10:07:53 +00004648 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump11289f42009-09-09 15:08:12 +00004649
John McCall97513962010-01-15 18:39:57 +00004650 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4651 CastExpr::CK_Unknown,
4652 const_cast<Expr*>(BlockExp));
Steve Naroff350b6652008-10-30 10:07:53 +00004653 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00004654 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4655 BlkCast);
Steve Naroff350b6652008-10-30 10:07:53 +00004656 //PE->dump();
Mike Stump11289f42009-09-09 15:08:12 +00004657
Douglas Gregor91f84212008-12-11 16:49:14 +00004658 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00004659 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004660 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek5a201952009-02-07 01:47:29 +00004661 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4662 FD->getType());
Mike Stump11289f42009-09-09 15:08:12 +00004663
John McCall97513962010-01-15 18:39:57 +00004664 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4665 CastExpr::CK_Unknown, ME);
Ted Kremenek5a201952009-02-07 01:47:29 +00004666 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump11289f42009-09-09 15:08:12 +00004667
Steve Naroff350b6652008-10-30 10:07:53 +00004668 llvm::SmallVector<Expr*, 8> BlkExprs;
4669 // Add the implicit argument.
4670 BlkExprs.push_back(BlkCast);
4671 // Add the user arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004672 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004673 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00004674 BlkExprs.push_back(*I);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004675 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004676 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4677 BlkExprs.size(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004678 Exp->getType(), SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004679 return CE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004680}
4681
4682void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004683 Stmt *BlockCall = SynthesizeBlockCall(Exp, Exp->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00004684 ReplaceStmt(Exp, BlockCall);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004685}
4686
Steve Naroffd9803712009-04-29 16:37:50 +00004687// We need to return the rewritten expression to handle cases where the
4688// BlockDeclRefExpr is embedded in another expression being rewritten.
4689// For example:
4690//
4691// int main() {
4692// __block Foo *f;
4693// __block int i;
Mike Stump11289f42009-09-09 15:08:12 +00004694//
Steve Naroffd9803712009-04-29 16:37:50 +00004695// void (^myblock)() = ^() {
4696// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4697// i = 77;
4698// };
4699//}
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004700Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanian25c07fa2009-12-23 19:26:34 +00004701 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004702 // for each DeclRefExp where BYREFVAR is name of the variable.
4703 ValueDecl *VD;
4704 bool isArrow = true;
4705 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4706 VD = BDRE->getDecl();
4707 else {
4708 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4709 isArrow = false;
4710 }
4711
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004712 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4713 &Context->Idents.get("__forwarding"),
4714 Context->VoidPtrTy, 0,
4715 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004716 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4717 FD, SourceLocation(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004718 FD->getType());
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004719
4720 const char *Name = VD->getNameAsCString();
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004721 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4722 &Context->Idents.get(Name),
4723 Context->VoidPtrTy, 0,
4724 /*BitWidth=*/0, /*Mutable=*/true);
4725 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004726 DeclRefExp->getType());
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004727
4728
4729
Steve Narofff26a1d42009-02-02 17:19:26 +00004730 // Need parens to enforce precedence.
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004731 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4732 ME);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004733 ReplaceStmt(DeclRefExp, PE);
Steve Naroffd9803712009-04-29 16:37:50 +00004734 return PE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004735}
4736
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004737// Rewrites the imported local variable V with external storage
4738// (static, extern, etc.) as *V
4739//
4740Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4741 ValueDecl *VD = DRE->getDecl();
4742 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4743 if (!ImportedLocalExternalDecls.count(Var))
4744 return DRE;
4745 Expr *Exp = new (Context) UnaryOperator(DRE, UnaryOperator::Deref,
4746 DRE->getType(), DRE->getLocation());
4747 // Need parens to enforce precedence.
4748 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4749 Exp);
4750 ReplaceStmt(DRE, PE);
4751 return PE;
4752}
4753
Steve Naroffc989a7b2008-11-03 23:29:32 +00004754void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4755 SourceLocation LocStart = CE->getLParenLoc();
4756 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofff4b992a2008-10-28 20:29:00 +00004757
4758 // Need to avoid trying to rewrite synthesized casts.
4759 if (LocStart.isInvalid())
4760 return;
Steve Naroff3e7ced12008-11-03 11:20:24 +00004761 // Need to avoid trying to rewrite casts contained in macros.
4762 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4763 return;
Mike Stump11289f42009-09-09 15:08:12 +00004764
Steve Naroff677ab3a2008-10-27 17:20:55 +00004765 const char *startBuf = SM->getCharacterData(LocStart);
4766 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004767 QualType QT = CE->getType();
4768 const Type* TypePtr = QT->getAs<Type>();
4769 if (isa<TypeOfExprType>(TypePtr)) {
4770 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4771 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4772 std::string TypeAsString = "(";
Fariborz Jahanianf5067912010-02-18 01:20:22 +00004773 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004774 TypeAsString += ")";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004775 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004776 return;
4777 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004778 // advance the location to startArgList.
4779 const char *argPtr = startBuf;
Mike Stump11289f42009-09-09 15:08:12 +00004780
Steve Naroff677ab3a2008-10-27 17:20:55 +00004781 while (*argPtr++ && (argPtr < endBuf)) {
4782 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004783 case '^':
4784 // Replace the '^' with '*'.
4785 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004786 ReplaceText(LocStart, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00004787 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004788 }
4789 }
4790 return;
4791}
4792
4793void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4794 SourceLocation DeclLoc = FD->getLocation();
4795 unsigned parenCount = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004796
Steve Naroff677ab3a2008-10-27 17:20:55 +00004797 // We have 1 or more arguments that have closure pointers.
4798 const char *startBuf = SM->getCharacterData(DeclLoc);
4799 const char *startArgList = strchr(startBuf, '(');
Mike Stump11289f42009-09-09 15:08:12 +00004800
Steve Naroff677ab3a2008-10-27 17:20:55 +00004801 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004802
Steve Naroff677ab3a2008-10-27 17:20:55 +00004803 parenCount++;
4804 // advance the location to startArgList.
4805 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4806 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump11289f42009-09-09 15:08:12 +00004807
Steve Naroff677ab3a2008-10-27 17:20:55 +00004808 const char *argPtr = startArgList;
Mike Stump11289f42009-09-09 15:08:12 +00004809
Steve Naroff677ab3a2008-10-27 17:20:55 +00004810 while (*argPtr++ && parenCount) {
4811 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004812 case '^':
4813 // Replace the '^' with '*'.
4814 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004815 ReplaceText(DeclLoc, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00004816 break;
4817 case '(':
4818 parenCount++;
4819 break;
4820 case ')':
4821 parenCount--;
4822 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004823 }
4824 }
4825 return;
4826}
4827
4828bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004829 const FunctionProtoType *FTP;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004830 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004831 if (PT) {
John McCall9dd450b2009-09-21 23:43:11 +00004832 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004833 } else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004834 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004835 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall9dd450b2009-09-21 23:43:11 +00004836 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004837 }
4838 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004839 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004840 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +00004841 if (isTopLevelBlockPointerType(*I))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004842 return true;
4843 }
4844 return false;
4845}
4846
Ted Kremenek5a201952009-02-07 01:47:29 +00004847void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4848 const char *&RParen) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004849 const char *argPtr = strchr(Name, '(');
4850 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004851
Steve Naroff677ab3a2008-10-27 17:20:55 +00004852 LParen = argPtr; // output the start.
4853 argPtr++; // skip past the left paren.
4854 unsigned parenCount = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004855
Steve Naroff677ab3a2008-10-27 17:20:55 +00004856 while (*argPtr && parenCount) {
4857 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004858 case '(': parenCount++; break;
4859 case ')': parenCount--; break;
4860 default: break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004861 }
4862 if (parenCount) argPtr++;
4863 }
4864 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4865 RParen = argPtr; // output the end
4866}
4867
4868void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4869 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4870 RewriteBlockPointerFunctionArgs(FD);
4871 return;
Mike Stump11289f42009-09-09 15:08:12 +00004872 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004873 // Handle Variables and Typedefs.
4874 SourceLocation DeclLoc = ND->getLocation();
4875 QualType DeclT;
4876 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4877 DeclT = VD->getType();
4878 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4879 DeclT = TDD->getUnderlyingType();
4880 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4881 DeclT = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004882 else
Steve Naroff677ab3a2008-10-27 17:20:55 +00004883 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump11289f42009-09-09 15:08:12 +00004884
Steve Naroff677ab3a2008-10-27 17:20:55 +00004885 const char *startBuf = SM->getCharacterData(DeclLoc);
4886 const char *endBuf = startBuf;
4887 // scan backward (from the decl location) for the end of the previous decl.
4888 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4889 startBuf--;
Mike Stump11289f42009-09-09 15:08:12 +00004890
Steve Naroff677ab3a2008-10-27 17:20:55 +00004891 // *startBuf != '^' if we are dealing with a pointer to function that
4892 // may take block argument types (which will be handled below).
4893 if (*startBuf == '^') {
4894 // Replace the '^' with '*', computing a negative offset.
4895 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004896 ReplaceText(DeclLoc, 1, "*");
Steve Naroff677ab3a2008-10-27 17:20:55 +00004897 }
4898 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4899 // Replace the '^' with '*' for arguments.
4900 DeclLoc = ND->getLocation();
4901 startBuf = SM->getCharacterData(DeclLoc);
4902 const char *argListBegin, *argListEnd;
4903 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4904 while (argListBegin < argListEnd) {
4905 if (*argListBegin == '^') {
4906 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004907 ReplaceText(CaretLoc, 1, "*");
Steve Naroff677ab3a2008-10-27 17:20:55 +00004908 }
4909 argListBegin++;
4910 }
4911 }
4912 return;
4913}
4914
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004915
4916/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4917/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4918/// struct Block_byref_id_object *src) {
4919/// _Block_object_assign (&_dest->object, _src->object,
4920/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4921/// [|BLOCK_FIELD_IS_WEAK]) // object
4922/// _Block_object_assign(&_dest->object, _src->object,
4923/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4924/// [|BLOCK_FIELD_IS_WEAK]) // block
4925/// }
4926/// And:
4927/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4928/// _Block_object_dispose(_src->object,
4929/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4930/// [|BLOCK_FIELD_IS_WEAK]) // object
4931/// _Block_object_dispose(_src->object,
4932/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4933/// [|BLOCK_FIELD_IS_WEAK]) // block
4934/// }
4935
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004936std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4937 int flag) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004938 std::string S;
Benjamin Kramere056cea2010-01-10 19:57:50 +00004939 if (CopyDestroyCache.count(flag))
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004940 return S;
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004941 CopyDestroyCache.insert(flag);
4942 S = "static void __Block_byref_id_object_copy_";
4943 S += utostr(flag);
4944 S += "(void *dst, void *src) {\n";
4945
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004946 // offset into the object pointer is computed as:
4947 // void * + void* + int + int + void* + void *
4948 unsigned IntSize =
4949 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4950 unsigned VoidPtrSize =
4951 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4952
4953 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
4954 S += " _Block_object_assign((char*)dst + ";
4955 S += utostr(offset);
4956 S += ", *(void * *) ((char*)src + ";
4957 S += utostr(offset);
4958 S += "), ";
4959 S += utostr(flag);
4960 S += ");\n}\n";
4961
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004962 S += "static void __Block_byref_id_object_dispose_";
4963 S += utostr(flag);
4964 S += "(void *src) {\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004965 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4966 S += utostr(offset);
4967 S += "), ";
4968 S += utostr(flag);
4969 S += ");\n}\n";
4970 return S;
4971}
4972
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004973/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4974/// the declaration into:
4975/// struct __Block_byref_ND {
4976/// void *__isa; // NULL for everything except __weak pointers
4977/// struct __Block_byref_ND *__forwarding;
4978/// int32_t __flags;
4979/// int32_t __size;
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004980/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4981/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004982/// typex ND;
4983/// };
4984///
4985/// It then replaces declaration of ND variable with:
4986/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4987/// __size=sizeof(struct __Block_byref_ND),
4988/// ND=initializer-if-any};
4989///
4990///
4991void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004992 // Insert declaration for the function in which block literal is
4993 // used.
4994 if (CurFunctionDeclToDeclareForBlock)
4995 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004996 int flag = 0;
4997 int isa = 0;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004998 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahanian6005bd82010-02-26 22:49:11 +00004999 if (DeclLoc.isInvalid())
5000 // If type location is missing, it is because of missing type (a warning).
5001 // Use variable's location which is good for this case.
5002 DeclLoc = ND->getLocation();
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005003 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian92368a12009-12-30 20:38:08 +00005004 SourceLocation X = ND->getLocEnd();
5005 X = SM->getInstantiationLoc(X);
5006 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005007 std::string Name(ND->getNameAsString());
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005008 std::string ByrefType;
5009 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005010 ByrefType += " {\n";
5011 ByrefType += " void *__isa;\n";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005012 RewriteByRefString(ByrefType, Name, ND);
5013 ByrefType += " *__forwarding;\n";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005014 ByrefType += " int __flags;\n";
5015 ByrefType += " int __size;\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005016 // Add void *__Block_byref_id_object_copy;
5017 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005018 QualType Ty = ND->getType();
5019 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
5020 if (HasCopyAndDispose) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005021 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5022 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005023 }
5024
5025 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005026 ByrefType += " " + Name + ";\n";
5027 ByrefType += "};\n";
5028 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00005029 SourceLocation FunLocStart;
5030 if (CurFunctionDef)
5031 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
5032 else {
5033 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5034 FunLocStart = CurMethodDef->getLocStart();
5035 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005036 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00005037 if (Ty.isObjCGCWeak()) {
5038 flag |= BLOCK_FIELD_IS_WEAK;
5039 isa = 1;
5040 }
5041
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005042 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005043 flag = BLOCK_BYREF_CALLER;
5044 QualType Ty = ND->getType();
5045 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5046 if (Ty->isBlockPointerType())
5047 flag |= BLOCK_FIELD_IS_BLOCK;
5048 else
5049 flag |= BLOCK_FIELD_IS_OBJECT;
5050 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005051 if (!HF.empty())
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005052 InsertText(FunLocStart, HF);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005053 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005054
5055 // struct __Block_byref_ND ND =
5056 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5057 // initializer-if-any};
5058 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanianf7945432010-01-05 18:15:57 +00005059 unsigned flags = 0;
5060 if (HasCopyAndDispose)
5061 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005062 Name = ND->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005063 ByrefType.clear();
5064 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005065 std::string ForwardingCastType("(");
5066 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005067 if (!hasInit) {
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00005068 ByrefType += " " + Name + " = {(void*)";
5069 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005070 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005071 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005072 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005073 ByrefType += "sizeof(";
5074 RewriteByRefString(ByrefType, Name, ND);
5075 ByrefType += ")";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005076 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005077 ByrefType += ", __Block_byref_id_object_copy_";
5078 ByrefType += utostr(flag);
5079 ByrefType += ", __Block_byref_id_object_dispose_";
5080 ByrefType += utostr(flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005081 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005082 ByrefType += "};\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005083 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(), ByrefType);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005084 }
5085 else {
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00005086 SourceLocation startLoc;
5087 Expr *E = ND->getInit();
5088 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5089 startLoc = ECE->getLParenLoc();
5090 else
5091 startLoc = E->getLocStart();
Fariborz Jahanianb8646ed2010-01-05 23:06:29 +00005092 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00005093 endBuf = SM->getCharacterData(startLoc);
5094
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005095 ByrefType += " " + Name;
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00005096 ByrefType += " = {(void*)";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00005097 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005098 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005099 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005100 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005101 ByrefType += "sizeof(";
5102 RewriteByRefString(ByrefType, Name, ND);
5103 ByrefType += "), ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005104 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00005105 ByrefType += "__Block_byref_id_object_copy_";
5106 ByrefType += utostr(flag);
5107 ByrefType += ", __Block_byref_id_object_dispose_";
5108 ByrefType += utostr(flag);
5109 ByrefType += ", ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00005110 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005111 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroff13468372009-12-23 17:24:33 +00005112
5113 // Complete the newly synthesized compound expression by inserting a right
5114 // curly brace before the end of the declaration.
5115 // FIXME: This approach avoids rewriting the initializer expression. It
5116 // also assumes there is only one declarator. For example, the following
5117 // isn't currently supported by this routine (in general):
5118 //
5119 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
5120 //
5121 const char *startBuf = SM->getCharacterData(startLoc);
5122 const char *semiBuf = strchr(startBuf, ';');
5123 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
5124 SourceLocation semiLoc =
5125 startLoc.getFileLocWithOffset(semiBuf-startBuf);
5126
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005127 InsertText(semiLoc, "}");
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005128 }
Fariborz Jahanian81203462009-12-22 00:48:54 +00005129 return;
5130}
5131
Mike Stump11289f42009-09-09 15:08:12 +00005132void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00005133 // Add initializers for any closure decl refs.
5134 GetBlockDeclRefExprs(Exp->getBody());
5135 if (BlockDeclRefs.size()) {
5136 // Unique all "by copy" declarations.
5137 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005138 if (!BlockDeclRefs[i]->isByRef()) {
5139 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5140 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5141 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5142 }
5143 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00005144 // Unique all "by ref" declarations.
5145 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5146 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005147 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5148 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5149 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5150 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00005151 }
5152 // Find any imported blocks...they will need special attention.
5153 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00005154 if (BlockDeclRefs[i]->isByRef() ||
5155 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian9bbc1482010-02-26 21:46:27 +00005156 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff677ab3a2008-10-27 17:20:55 +00005157 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff677ab3a2008-10-27 17:20:55 +00005158 }
5159}
5160
Steve Narofff4b992a2008-10-28 20:29:00 +00005161FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
5162 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005163 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump11289f42009-09-09 15:08:12 +00005164 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Douglas Gregorc4df4072010-04-19 22:54:31 +00005165 ID, FType, 0, FunctionDecl::Extern,
5166 FunctionDecl::None, false, false);
Steve Narofff4b992a2008-10-28 20:29:00 +00005167}
5168
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005169Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
5170 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005171 Blocks.push_back(Exp);
5172
5173 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005174
5175 // Add inner imported variables now used in current block.
5176 int countOfInnerDecls = 0;
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00005177 if (!InnerBlockDeclRefs.empty()) {
5178 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5179 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
5180 ValueDecl *VD = Exp->getDecl();
5181 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005182 // We need to save the copied-in variables in nested
5183 // blocks because it is needed at the end for some of the API generations.
5184 // See SynthesizeBlockLiterals routine.
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00005185 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5186 BlockDeclRefs.push_back(Exp);
5187 BlockByCopyDeclsPtrSet.insert(VD);
5188 BlockByCopyDecls.push_back(VD);
5189 }
5190 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
5191 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5192 BlockDeclRefs.push_back(Exp);
5193 BlockByRefDeclsPtrSet.insert(VD);
5194 BlockByRefDecls.push_back(VD);
5195 }
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005196 }
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00005197 // Find any imported blocks...they will need special attention.
5198 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5199 if (InnerBlockDeclRefs[i]->isByRef() ||
5200 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5201 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5202 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005203 }
5204 InnerDeclRefsCount.push_back(countOfInnerDecls);
5205
Steve Narofff4b992a2008-10-28 20:29:00 +00005206 std::string FuncName;
Mike Stump11289f42009-09-09 15:08:12 +00005207
Steve Narofff4b992a2008-10-28 20:29:00 +00005208 if (CurFunctionDef)
Chris Lattnere4b95692008-11-24 03:33:13 +00005209 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00005210 else if (CurMethodDef)
5211 BuildUniqueMethodName(FuncName, CurMethodDef);
5212 else if (GlobalVarDecl)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005213 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump11289f42009-09-09 15:08:12 +00005214
Steve Narofff4b992a2008-10-28 20:29:00 +00005215 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump11289f42009-09-09 15:08:12 +00005216
Steve Narofff4b992a2008-10-28 20:29:00 +00005217 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
5218 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump11289f42009-09-09 15:08:12 +00005219
Steve Narofff4b992a2008-10-28 20:29:00 +00005220 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian19c62402010-05-25 15:56:08 +00005221 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5222 QualType FType = Context->getPointerType(BFT);
Steve Narofff4b992a2008-10-28 20:29:00 +00005223
5224 FunctionDecl *FD;
5225 Expr *NewRep;
Mike Stump11289f42009-09-09 15:08:12 +00005226
Steve Narofff4b992a2008-10-28 20:29:00 +00005227 // Simulate a contructor call...
5228 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00005229 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00005230
Steve Narofff4b992a2008-10-28 20:29:00 +00005231 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00005232
Steve Naroffe2514232008-10-29 21:23:59 +00005233 // Initialize the block function.
Steve Narofff4b992a2008-10-28 20:29:00 +00005234 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00005235 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
5236 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00005237 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5238 CastExpr::CK_Unknown, Arg);
Mike Stump11289f42009-09-09 15:08:12 +00005239 InitExprs.push_back(castExpr);
5240
Steve Naroff30484702009-12-06 21:14:13 +00005241 // Initialize the block descriptor.
5242 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump11289f42009-09-09 15:08:12 +00005243
Steve Naroff30484702009-12-06 21:14:13 +00005244 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
5245 &Context->Idents.get(DescData.c_str()),
5246 Context->VoidPtrTy, 0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00005247 VarDecl::Static, VarDecl::None);
Steve Naroff30484702009-12-06 21:14:13 +00005248 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
5249 new (Context) DeclRefExpr(NewVD,
5250 Context->VoidPtrTy, SourceLocation()),
5251 UnaryOperator::AddrOf,
5252 Context->getPointerType(Context->VoidPtrTy),
5253 SourceLocation());
5254 InitExprs.push_back(DescRefExpr);
5255
Steve Narofff4b992a2008-10-28 20:29:00 +00005256 // Add initializers for any closure decl refs.
5257 if (BlockDeclRefs.size()) {
Steve Naroffe2514232008-10-29 21:23:59 +00005258 Expr *Exp;
Steve Narofff4b992a2008-10-28 20:29:00 +00005259 // Output all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005260 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00005261 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005262 if (isObjCType((*I)->getType())) {
Steve Naroffe2514232008-10-29 21:23:59 +00005263 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner86d7d912008-11-24 03:54:41 +00005264 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00005265 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Fariborz Jahanian36680dd2010-05-24 18:32:56 +00005266 if (HasLocalVariableExternalStorage(*I)) {
5267 QualType QT = (*I)->getType();
5268 QT = Context->getPointerType(QT);
5269 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf, QT,
5270 SourceLocation());
5271 }
Steve Naroffa5c0db82008-12-11 21:05:33 +00005272 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner86d7d912008-11-24 03:54:41 +00005273 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00005274 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
John McCall97513962010-01-15 18:39:57 +00005275 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5276 CastExpr::CK_Unknown, Arg);
Steve Narofff4b992a2008-10-28 20:29:00 +00005277 } else {
Chris Lattner86d7d912008-11-24 03:54:41 +00005278 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00005279 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005280 if (HasLocalVariableExternalStorage(*I)) {
5281 QualType QT = (*I)->getType();
5282 QT = Context->getPointerType(QT);
5283 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf, QT,
5284 SourceLocation());
5285 }
5286
Steve Narofff4b992a2008-10-28 20:29:00 +00005287 }
Mike Stump11289f42009-09-09 15:08:12 +00005288 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00005289 }
5290 // Output all "by ref" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005291 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00005292 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005293 ValueDecl *ND = (*I);
5294 std::string Name(ND->getNameAsString());
5295 std::string RecName;
5296 RewriteByRefString(RecName, Name, ND);
5297 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5298 + sizeof("struct"));
Abramo Bagnara6150c882010-05-11 21:36:43 +00005299 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005300 SourceLocation(), II);
5301 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5302 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5303
Chris Lattner86d7d912008-11-24 03:54:41 +00005304 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00005305 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
5306 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00005307 Context->getPointerType(Exp->getType()),
Steve Naroffe2514232008-10-29 21:23:59 +00005308 SourceLocation());
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005309 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CastExpr::CK_Unknown, Exp);
Mike Stump11289f42009-09-09 15:08:12 +00005310 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00005311 }
5312 }
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00005313 if (ImportedBlockDecls.size()) {
5314 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5315 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff30484702009-12-06 21:14:13 +00005316 unsigned IntSize =
5317 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00005318 Expr *FlagExp = new (Context) IntegerLiteral(llvm::APInt(IntSize, flag),
5319 Context->IntTy, SourceLocation());
5320 InitExprs.push_back(FlagExp);
Steve Naroff30484702009-12-06 21:14:13 +00005321 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00005322 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
5323 FType, SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00005324 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00005325 Context->getPointerType(NewRep->getType()),
Steve Narofff4b992a2008-10-28 20:29:00 +00005326 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00005327 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CastExpr::CK_Unknown,
5328 NewRep);
Steve Narofff4b992a2008-10-28 20:29:00 +00005329 BlockDeclRefs.clear();
5330 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005331 BlockByRefDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00005332 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005333 BlockByCopyDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00005334 ImportedBlockDecls.clear();
5335 return NewRep;
5336}
5337
5338//===----------------------------------------------------------------------===//
5339// Function Body / Expression rewriting
5340//===----------------------------------------------------------------------===//
5341
Steve Naroff4588d0f2008-12-04 16:24:46 +00005342// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
5343// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
5344// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
5345// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
5346// Since the rewriter isn't capable of rewriting rewritten code, it's important
5347// we get this right.
5348void RewriteObjC::CollectPropertySetters(Stmt *S) {
5349 // Perform a bottom up traversal of all children.
5350 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5351 CI != E; ++CI)
5352 if (*CI)
5353 CollectPropertySetters(*CI);
5354
5355 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
5356 if (BinOp->isAssignmentOp()) {
5357 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
5358 PropSetters[PRE] = BinOp;
5359 }
5360 }
5361}
5362
Steve Narofff4b992a2008-10-28 20:29:00 +00005363Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump11289f42009-09-09 15:08:12 +00005364 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00005365 isa<DoStmt>(S) || isa<ForStmt>(S))
5366 Stmts.push_back(S);
5367 else if (isa<ObjCForCollectionStmt>(S)) {
5368 Stmts.push_back(S);
Chris Lattnerb71980f2010-01-09 21:45:57 +00005369 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofff4b992a2008-10-28 20:29:00 +00005370 }
Mike Stump11289f42009-09-09 15:08:12 +00005371
Steve Narofff4b992a2008-10-28 20:29:00 +00005372 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005373
Steve Narofff4b992a2008-10-28 20:29:00 +00005374 // Perform a bottom up rewrite of all children.
5375 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5376 CI != E; ++CI)
5377 if (*CI) {
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00005378 Stmt *newStmt;
5379 Stmt *S = (*CI);
5380 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5381 Expr *OldBase = IvarRefExpr->getBase();
5382 bool replaced = false;
5383 newStmt = RewriteObjCNestedIvarRefExpr(S, replaced);
5384 if (replaced) {
5385 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
5386 ReplaceStmt(OldBase, IRE->getBase());
5387 else
5388 ReplaceStmt(S, newStmt);
5389 }
5390 }
5391 else
5392 newStmt = RewriteFunctionBodyOrGlobalInitializer(S);
Mike Stump11289f42009-09-09 15:08:12 +00005393 if (newStmt)
Steve Narofff4b992a2008-10-28 20:29:00 +00005394 *CI = newStmt;
5395 }
Mike Stump11289f42009-09-09 15:08:12 +00005396
Steve Narofff4b992a2008-10-28 20:29:00 +00005397 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005398 llvm::SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00005399 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5400 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005401 ImportedLocalExternalDecls.clear();
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005402 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00005403 InnerBlockDeclRefs, InnerContexts);
Steve Narofff4b992a2008-10-28 20:29:00 +00005404 // Rewrite the block body in place.
5405 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005406 ImportedLocalExternalDecls.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00005407 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenekdb2ef372010-01-07 18:00:35 +00005408 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroffd8907b72008-10-29 18:15:37 +00005409 RewrittenBlockExprs[BE] = Str;
Mike Stump11289f42009-09-09 15:08:12 +00005410
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005411 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5412
Steve Narofff4b992a2008-10-28 20:29:00 +00005413 //blockTranscribed->dump();
Steve Naroffd8907b72008-10-29 18:15:37 +00005414 ReplaceStmt(S, blockTranscribed);
Steve Narofff4b992a2008-10-28 20:29:00 +00005415 return blockTranscribed;
5416 }
5417 // Handle specific things.
5418 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5419 return RewriteAtEncode(AtEncode);
Mike Stump11289f42009-09-09 15:08:12 +00005420
Steve Naroff4588d0f2008-12-04 16:24:46 +00005421 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
5422 BinaryOperator *BinOp = PropSetters[PropRefExpr];
5423 if (BinOp) {
5424 // Because the rewriter doesn't allow us to rewrite rewritten code,
5425 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroff08628db2008-12-09 12:56:34 +00005426 DisableReplaceStmt = true;
5427 // Save the source range. Even if we disable the replacement, the
5428 // rewritten node will have been inserted into the tree. If the synthesized
5429 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump11289f42009-09-09 15:08:12 +00005430 // self.errorHandler = handler ? handler :
Steve Naroff08628db2008-12-09 12:56:34 +00005431 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
5432 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroff4588d0f2008-12-04 16:24:46 +00005433 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroff08628db2008-12-09 12:56:34 +00005434 DisableReplaceStmt = false;
Steve Naroff22216db2008-12-04 23:50:32 +00005435 //
5436 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
5437 // we changed the RHS of BinOp, the rewriter would fail (since it needs
5438 // to see the original expression). Consider this example:
5439 //
5440 // Foo *obj1, *obj2;
5441 //
5442 // obj1.i = [obj2 rrrr];
5443 //
5444 // 'BinOp' for the previous expression looks like:
5445 //
5446 // (BinaryOperator 0x231ccf0 'int' '='
5447 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
5448 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
5449 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
5450 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
5451 //
5452 // 'newStmt' represents the rewritten message expression. For example:
5453 //
5454 // (CallExpr 0x231d300 'id':'struct objc_object *'
5455 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
5456 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
5457 // (CStyleCastExpr 0x231d220 'void *'
5458 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
5459 //
5460 // Note that 'newStmt' is passed to RewritePropertySetter so that it
5461 // can be used as the setter argument. ReplaceStmt() will still 'see'
5462 // the original RHS (since we haven't altered BinOp).
5463 //
Mike Stump11289f42009-09-09 15:08:12 +00005464 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff22216db2008-12-04 23:50:32 +00005465 // node. As a result, we now leak the original AST nodes.
5466 //
Steve Naroff08628db2008-12-09 12:56:34 +00005467 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroff4588d0f2008-12-04 16:24:46 +00005468 } else {
5469 return RewritePropertyGetter(PropRefExpr);
Steve Narofff326f402008-12-03 00:56:33 +00005470 }
5471 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005472 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5473 return RewriteAtSelector(AtSelector);
Mike Stump11289f42009-09-09 15:08:12 +00005474
Steve Narofff4b992a2008-10-28 20:29:00 +00005475 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5476 return RewriteObjCStringLiteral(AtString);
Mike Stump11289f42009-09-09 15:08:12 +00005477
Steve Narofff4b992a2008-10-28 20:29:00 +00005478 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00005479#if 0
Steve Narofff4b992a2008-10-28 20:29:00 +00005480 // Before we rewrite it, put the original message expression in a comment.
5481 SourceLocation startLoc = MessExpr->getLocStart();
5482 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00005483
Steve Narofff4b992a2008-10-28 20:29:00 +00005484 const char *startBuf = SM->getCharacterData(startLoc);
5485 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump11289f42009-09-09 15:08:12 +00005486
Steve Narofff4b992a2008-10-28 20:29:00 +00005487 std::string messString;
5488 messString += "// ";
5489 messString.append(startBuf, endBuf-startBuf+1);
5490 messString += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00005491
5492 // FIXME: Missing definition of
Steve Narofff4b992a2008-10-28 20:29:00 +00005493 // InsertText(clang::SourceLocation, char const*, unsigned int).
5494 // InsertText(startLoc, messString.c_str(), messString.size());
5495 // Tried this, but it didn't work either...
5496 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff4588d0f2008-12-04 16:24:46 +00005497#endif
Steve Narofff4b992a2008-10-28 20:29:00 +00005498 return RewriteMessageExpr(MessExpr);
5499 }
Mike Stump11289f42009-09-09 15:08:12 +00005500
Steve Narofff4b992a2008-10-28 20:29:00 +00005501 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5502 return RewriteObjCTryStmt(StmtTry);
5503
5504 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5505 return RewriteObjCSynchronizedStmt(StmtTry);
5506
5507 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5508 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump11289f42009-09-09 15:08:12 +00005509
Steve Narofff4b992a2008-10-28 20:29:00 +00005510 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5511 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump11289f42009-09-09 15:08:12 +00005512
5513 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofff4b992a2008-10-28 20:29:00 +00005514 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump11289f42009-09-09 15:08:12 +00005515 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofff4b992a2008-10-28 20:29:00 +00005516 OrigStmtRange.getEnd());
5517 if (BreakStmt *StmtBreakStmt =
5518 dyn_cast<BreakStmt>(S))
5519 return RewriteBreakStmt(StmtBreakStmt);
5520 if (ContinueStmt *StmtContinueStmt =
5521 dyn_cast<ContinueStmt>(S))
5522 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump11289f42009-09-09 15:08:12 +00005523
5524 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofff4b992a2008-10-28 20:29:00 +00005525 // and cast exprs.
5526 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5527 // FIXME: What we're doing here is modifying the type-specifier that
5528 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump11289f42009-09-09 15:08:12 +00005529 // a separate type-specifier that we can rewrite.
Steve Naroffe70a52a2009-12-05 15:55:59 +00005530 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5531 // the context of an ObjCForCollectionStmt. For example:
5532 // NSArray *someArray;
5533 // for (id <FooProtocol> index in someArray) ;
5534 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5535 // and it depends on the original text locations/positions.
Benjamin Krameracc5fa12009-12-05 22:16:51 +00005536 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroffe70a52a2009-12-05 15:55:59 +00005537 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump11289f42009-09-09 15:08:12 +00005538
Steve Narofff4b992a2008-10-28 20:29:00 +00005539 // Blocks rewrite rules.
5540 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5541 DI != DE; ++DI) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +00005542 Decl *SD = *DI;
Steve Narofff4b992a2008-10-28 20:29:00 +00005543 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005544 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005545 RewriteBlockPointerDecl(ND);
Mike Stump11289f42009-09-09 15:08:12 +00005546 else if (ND->getType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005547 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00005548 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005549 if (VD->hasAttr<BlocksAttr>()) {
5550 static unsigned uniqueByrefDeclCount = 0;
5551 assert(!BlockByRefDeclNo.count(ND) &&
5552 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5553 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005554 RewriteByRefVar(VD);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005555 }
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00005556 else
5557 RewriteTypeOfDecl(VD);
5558 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005559 }
5560 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005561 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005562 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005563 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005564 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5565 }
5566 }
5567 }
Mike Stump11289f42009-09-09 15:08:12 +00005568
Steve Narofff4b992a2008-10-28 20:29:00 +00005569 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5570 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump11289f42009-09-09 15:08:12 +00005571
5572 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00005573 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5574 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump11289f42009-09-09 15:08:12 +00005575 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5576 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005577 && "Statement stack mismatch");
5578 Stmts.pop_back();
5579 }
5580 // Handle blocks rewriting.
5581 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5582 if (BDRE->isByRef())
Steve Naroffd9803712009-04-29 16:37:50 +00005583 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofff4b992a2008-10-28 20:29:00 +00005584 }
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005585 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5586 ValueDecl *VD = DRE->getDecl();
5587 if (VD->hasAttr<BlocksAttr>())
5588 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00005589 if (HasLocalVariableExternalStorage(VD))
5590 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005591 }
5592
Steve Narofff4b992a2008-10-28 20:29:00 +00005593 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff350b6652008-10-30 10:07:53 +00005594 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00005595 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00005596 ReplaceStmt(S, BlockCall);
5597 return BlockCall;
5598 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005599 }
Steve Naroffc989a7b2008-11-03 23:29:32 +00005600 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005601 RewriteCastExpr(CE);
5602 }
5603#if 0
5604 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek5a201952009-02-07 01:47:29 +00005605 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00005606 // Get the new text.
5607 std::string SStr;
5608 llvm::raw_string_ostream Buf(SStr);
Eli Friedman0905f142009-05-30 05:19:26 +00005609 Replacement->printPretty(Buf, *Context);
Steve Narofff4b992a2008-10-28 20:29:00 +00005610 const std::string &Str = Buf.str();
5611
5612 printf("CAST = %s\n", &Str[0]);
5613 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5614 delete S;
5615 return Replacement;
5616 }
5617#endif
5618 // Return this stmt unmodified.
5619 return S;
5620}
5621
Steve Naroffe70a52a2009-12-05 15:55:59 +00005622void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5623 for (RecordDecl::field_iterator i = RD->field_begin(),
5624 e = RD->field_end(); i != e; ++i) {
5625 FieldDecl *FD = *i;
5626 if (isTopLevelBlockPointerType(FD->getType()))
5627 RewriteBlockPointerDecl(FD);
5628 if (FD->getType()->isObjCQualifiedIdType() ||
5629 FD->getType()->isObjCQualifiedInterfaceType())
5630 RewriteObjCQualifiedInterfaceTypes(FD);
5631 }
5632}
5633
Steve Narofff4b992a2008-10-28 20:29:00 +00005634/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5635/// main file of the input.
5636void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5637 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffb1368882008-12-17 00:20:22 +00005638 if (FD->isOverloadedOperator())
5639 return;
Mike Stump11289f42009-09-09 15:08:12 +00005640
Steve Narofff4b992a2008-10-28 20:29:00 +00005641 // Since function prototypes don't have ParmDecl's, we check the function
5642 // prototype. This enables us to rewrite function declarations and
5643 // definitions using the same code.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005644 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005645
Sebastian Redla7b98a72009-04-26 20:35:05 +00005646 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005647 if (CompoundStmt *Body = FD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005648 CurFunctionDef = FD;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005649 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005650 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005651 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005652 Body =
5653 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5654 FD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005655 CurrentBody = 0;
5656 if (PropParentMap) {
5657 delete PropParentMap;
5658 PropParentMap = 0;
5659 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005660 // This synthesizes and inserts the block "impl" struct, invoke function,
5661 // and any copy/dispose helper functions.
5662 InsertBlockLiteralsWithinFunction(FD);
5663 CurFunctionDef = 0;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005664 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005665 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005666 return;
5667 }
5668 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005669 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005670 CurMethodDef = MD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005671 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005672 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005673 Body =
5674 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5675 MD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005676 CurrentBody = 0;
5677 if (PropParentMap) {
5678 delete PropParentMap;
5679 PropParentMap = 0;
5680 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005681 InsertBlockLiteralsWithinMethod(MD);
5682 CurMethodDef = 0;
5683 }
5684 }
5685 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5686 ClassImplementation.push_back(CI);
5687 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5688 CategoryImplementation.push_back(CI);
5689 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5690 RewriteForwardClassDecl(CD);
5691 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5692 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroffa5c0db82008-12-11 21:05:33 +00005693 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005694 RewriteBlockPointerDecl(VD);
Steve Naroffd8907b72008-10-29 18:15:37 +00005695 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005696 CheckFunctionPointerDecl(VD->getType(), VD);
5697 if (VD->getInit()) {
Steve Naroffc989a7b2008-11-03 23:29:32 +00005698 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005699 RewriteCastExpr(CE);
5700 }
5701 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00005702 } else if (VD->getType()->isRecordType()) {
5703 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5704 if (RD->isDefinition())
5705 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005706 }
Steve Naroffd8907b72008-10-29 18:15:37 +00005707 if (VD->getInit()) {
5708 GlobalVarDecl = VD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005709 CollectPropertySetters(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005710 CurrentBody = VD->getInit();
Steve Naroffd8907b72008-10-29 18:15:37 +00005711 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005712 CurrentBody = 0;
5713 if (PropParentMap) {
5714 delete PropParentMap;
5715 PropParentMap = 0;
5716 }
Mike Stump11289f42009-09-09 15:08:12 +00005717 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner86d7d912008-11-24 03:54:41 +00005718 VD->getNameAsCString());
Steve Naroffd8907b72008-10-29 18:15:37 +00005719 GlobalVarDecl = 0;
5720
5721 // This is needed for blocks.
Steve Naroffc989a7b2008-11-03 23:29:32 +00005722 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroffd8907b72008-10-29 18:15:37 +00005723 RewriteCastExpr(CE);
5724 }
5725 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005726 return;
5727 }
5728 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005729 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005730 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005731 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005732 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5733 return;
5734 }
5735 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroffe70a52a2009-12-05 15:55:59 +00005736 if (RD->isDefinition())
5737 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005738 return;
5739 }
5740 // Nothing yet.
5741}
5742
Chris Lattnercf169832009-03-28 04:11:33 +00005743void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005744 if (Diags.hasErrorOccurred())
5745 return;
Mike Stump11289f42009-09-09 15:08:12 +00005746
Steve Narofff4b992a2008-10-28 20:29:00 +00005747 RewriteInclude();
Mike Stump11289f42009-09-09 15:08:12 +00005748
Steve Naroffd9803712009-04-29 16:37:50 +00005749 // Here's a great place to add any extra declarations that may be needed.
5750 // Write out meta data for each @protocol(<expr>).
Mike Stump11289f42009-09-09 15:08:12 +00005751 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00005752 E = ProtocolExprDecls.end(); I != E; ++I)
5753 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5754
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005755 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005756 if (ClassImplementation.size() || CategoryImplementation.size())
5757 RewriteImplementations();
Steve Naroffd9803712009-04-29 16:37:50 +00005758
Steve Narofff4b992a2008-10-28 20:29:00 +00005759 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5760 // we are done.
Mike Stump11289f42009-09-09 15:08:12 +00005761 if (const RewriteBuffer *RewriteBuf =
Steve Narofff4b992a2008-10-28 20:29:00 +00005762 Rewrite.getRewriteBufferFor(MainFileID)) {
5763 //printf("Changed:\n");
5764 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5765 } else {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005766 llvm::errs() << "No changes\n";
Steve Narofff4b992a2008-10-28 20:29:00 +00005767 }
Steve Narofff8cfd162008-11-13 20:07:04 +00005768
Steve Naroffd9803712009-04-29 16:37:50 +00005769 if (ClassImplementation.size() || CategoryImplementation.size() ||
5770 ProtocolExprDecls.size()) {
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005771 // Rewrite Objective-c meta data*
5772 std::string ResultStr;
5773 SynthesizeMetaDataIntoBuffer(ResultStr);
5774 // Emit metadata.
5775 *OutFile << ResultStr;
5776 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005777 OutFile->flush();
5778}