blob: 91b1aaf4c86af59f14f8e98b0dcac6269c929714 [file] [log] [blame]
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattnere99c8322007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnere99c8322007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Eli Friedman9f30fc32009-05-18 22:50:54 +000014#include "clang/Frontend/ASTConsumers.h"
Chris Lattner16a0de42007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattnere99c8322007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Steve Naroff1042ff32008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.h"
Chris Lattner16a0de42007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner4431a1b2007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattnerf3a59a12007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Benjamin Kramer89b422c2009-08-23 12:08:50 +000023#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
Chris Lattner211f8b82007-10-25 17:07:24 +000025#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian99e96b02007-10-26 19:46:17 +000026#include "llvm/ADT/SmallPtrSet.h"
Ted Kremenek2d470fc2008-09-13 05:16:45 +000027#include "llvm/ADT/OwningPtr.h"
Fariborz Jahaniane3891582010-01-05 18:04:40 +000028#include "llvm/ADT/DenseSet.h"
Chris Lattnere99c8322007-10-11 00:43:27 +000029using namespace clang;
Chris Lattner211f8b82007-10-25 17:07:24 +000030using llvm::utostr;
Chris Lattnere99c8322007-10-11 00:43:27 +000031
Chris Lattnere99c8322007-10-11 00:43:27 +000032namespace {
Steve Naroff1dc53ef2008-04-14 22:03:09 +000033 class RewriteObjC : public ASTConsumer {
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000034 enum {
35 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
36 block, ... */
37 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
38 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
39 __block variable */
40 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
41 helpers */
42 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
43 support routines */
44 BLOCK_BYREF_CURRENT_MAX = 256
45 };
46
47 enum {
48 BLOCK_NEEDS_FREE = (1 << 24),
49 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
50 BLOCK_HAS_CXX_OBJ = (1 << 26),
51 BLOCK_IS_GC = (1 << 27),
52 BLOCK_IS_GLOBAL = (1 << 28),
53 BLOCK_HAS_DESCRIPTOR = (1 << 29)
54 };
55
Chris Lattner0bd1c972007-10-16 21:07:07 +000056 Rewriter Rewrite;
Chris Lattnere9c810c2007-11-30 22:25:36 +000057 Diagnostic &Diags;
Steve Naroff945a3b12008-03-10 20:43:59 +000058 const LangOptions &LangOpts;
Steve Naroff7b3579b2008-01-30 19:17:43 +000059 unsigned RewriteFailedDiag;
Steve Naroff6d6da252008-12-05 17:03:39 +000060 unsigned TryFinallyContainsReturnDiag;
Mike Stump11289f42009-09-09 15:08:12 +000061
Chris Lattnerc6d91c02007-10-17 22:35:30 +000062 ASTContext *Context;
Chris Lattnere99c8322007-10-11 00:43:27 +000063 SourceManager *SM;
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +000064 TranslationUnitDecl *TUDecl;
Chris Lattnerd32480d2009-01-17 06:22:33 +000065 FileID MainFileID;
Chris Lattnerf3a59a12007-12-02 01:13:47 +000066 const char *MainFileStart, *MainFileEnd;
Chris Lattner0bd1c972007-10-16 21:07:07 +000067 SourceLocation LastIncLoc;
Mike Stump11289f42009-09-09 15:08:12 +000068
Ted Kremenek1b0ea822008-01-07 19:49:32 +000069 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
70 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
71 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Naroff13e74872008-05-06 18:26:51 +000072 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremenek1b0ea822008-01-07 19:49:32 +000073 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
74 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +000075 llvm::SmallVector<Stmt *, 32> Stmts;
76 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffd9803712009-04-29 16:37:50 +000077 // Remember all the @protocol(<expr>) expressions.
78 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahaniane3891582010-01-05 18:04:40 +000079
80 llvm::DenseSet<uint64_t> CopyDestroyCache;
81
Steve Naroffce8e8862008-03-15 00:55:56 +000082 unsigned NumObjCStringLiterals;
Mike Stump11289f42009-09-09 15:08:12 +000083
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000084 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff7fa2f042007-11-15 10:28:18 +000085 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +000086 FunctionDecl *MsgSendStretFunctionDecl;
87 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanian4f76f222007-12-03 21:26:48 +000088 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000089 FunctionDecl *GetClassFunctionDecl;
Steve Naroffb2f8ff12007-12-07 03:50:46 +000090 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff574440f2007-10-24 22:48:43 +000091 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff265a6b92007-11-08 14:30:50 +000092 FunctionDecl *CFStringFunctionDecl;
Steve Naroff17978c42008-03-11 17:37:02 +000093 FunctionDecl *SuperContructorFunctionDecl;
Mike Stump11289f42009-09-09 15:08:12 +000094
Steve Naroffa397efd2007-11-03 11:27:19 +000095 // ObjC string constant support.
Steve Naroff08899ff2008-04-15 22:42:06 +000096 VarDecl *ConstantStringClassReference;
Steve Naroffa397efd2007-11-03 11:27:19 +000097 RecordDecl *NSStringRecord;
Mike Stump11289f42009-09-09 15:08:12 +000098
Fariborz Jahanian19d42bf2008-01-16 00:09:11 +000099 // ObjC foreach break/continue generation support.
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +0000100 int BcLabelCount;
Mike Stump11289f42009-09-09 15:08:12 +0000101
Steve Naroff7fa2f042007-11-15 10:28:18 +0000102 // Needed for super.
Steve Naroff677ab3a2008-10-27 17:20:55 +0000103 ObjCMethodDecl *CurMethodDef;
Steve Naroff7fa2f042007-11-15 10:28:18 +0000104 RecordDecl *SuperStructDecl;
Steve Naroffce8e8862008-03-15 00:55:56 +0000105 RecordDecl *ConstantStringDecl;
Mike Stump11289f42009-09-09 15:08:12 +0000106
Steve Naroffd9803712009-04-29 16:37:50 +0000107 TypeDecl *ProtocolTypeDecl;
108 QualType getProtocolType();
Mike Stump11289f42009-09-09 15:08:12 +0000109
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000110 // Needed for header files being rewritten
111 bool IsHeader;
Mike Stump11289f42009-09-09 15:08:12 +0000112
Steve Narofff9e7c902008-03-28 22:26:09 +0000113 std::string InFileName;
Eli Friedman94cf21e2009-05-18 22:20:00 +0000114 llvm::raw_ostream* OutFile;
Eli Friedmanf22439a2009-05-18 22:39:16 +0000115
116 bool SilenceRewriteMacroWarning;
Fariborz Jahanianbc6811c2010-01-07 22:51:18 +0000117 bool objc_impl_method;
Eli Friedmanf22439a2009-05-18 22:39:16 +0000118
Steve Naroff00a31762008-03-27 22:29:16 +0000119 std::string Preamble;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000120
121 // Block expressions.
122 llvm::SmallVector<BlockExpr *, 32> Blocks;
123 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
124 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Mike Stump11289f42009-09-09 15:08:12 +0000125
Steve Naroff677ab3a2008-10-27 17:20:55 +0000126 // Block related declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +0000127 llvm::SmallVector<ValueDecl *, 8> BlockByCopyDecls;
128 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
129 llvm::SmallVector<ValueDecl *, 8> BlockByRefDecls;
130 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +0000131 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000132 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
133
134 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
135
Steve Naroff4588d0f2008-12-04 16:24:46 +0000136 // This maps a property to it's assignment statement.
137 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Naroff1042ff32008-12-08 16:43:47 +0000138 // This maps a property to it's synthesied message expression.
139 // This allows us to rewrite chained getters (e.g. o.a.b.c).
140 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
Mike Stump11289f42009-09-09 15:08:12 +0000141
Steve Naroff22216db2008-12-04 23:50:32 +0000142 // This maps an original source AST to it's rewritten form. This allows
143 // us to avoid rewriting the same node twice (which is very uncommon).
144 // This is needed to support some of the exotic property rewriting.
145 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Narofff326f402008-12-03 00:56:33 +0000146
Steve Naroff677ab3a2008-10-27 17:20:55 +0000147 FunctionDecl *CurFunctionDef;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000148 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Steve Naroffd8907b72008-10-29 18:15:37 +0000149 VarDecl *GlobalVarDecl;
Mike Stump11289f42009-09-09 15:08:12 +0000150
Steve Naroff08628db2008-12-09 12:56:34 +0000151 bool DisableReplaceStmt;
Mike Stump11289f42009-09-09 15:08:12 +0000152
Fariborz Jahanian93191af2007-10-18 19:23:00 +0000153 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnere99c8322007-10-11 00:43:27 +0000154 public:
Ted Kremenek380df932008-05-31 20:11:04 +0000155 virtual void Initialize(ASTContext &context);
156
Chris Lattner3c799d72007-10-24 17:06:59 +0000157 // Top Level Driver code.
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000158 virtual void HandleTopLevelDecl(DeclGroupRef D) {
159 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
160 HandleTopLevelSingleDecl(*I);
161 }
162 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000163 void HandleDeclInMainFile(Decl *D);
Eli Friedman94cf21e2009-05-18 22:20:00 +0000164 RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000165 Diagnostic &D, const LangOptions &LOpts,
166 bool silenceMacroWarn);
Ted Kremenek6231e7e2008-08-08 04:15:52 +0000167
168 ~RewriteObjC() {}
Mike Stump11289f42009-09-09 15:08:12 +0000169
Chris Lattnercf169832009-03-28 04:11:33 +0000170 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump11289f42009-09-09 15:08:12 +0000171
Fariborz Jahaniana7e1dcd2010-02-05 16:43:40 +0000172 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff22216db2008-12-04 23:50:32 +0000173 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump11289f42009-09-09 15:08:12 +0000174
Steve Naroff22216db2008-12-04 23:50:32 +0000175 if (ReplacingStmt)
176 return; // We can't rewrite the same node twice.
Chris Lattner2e0d2602008-01-31 19:37:57 +0000177
Steve Naroff08628db2008-12-09 12:56:34 +0000178 if (DisableReplaceStmt)
179 return; // Used when rewriting the assignment of a property setter.
180
Steve Naroff22216db2008-12-04 23:50:32 +0000181 // If replacement succeeded or warning disabled return with no warning.
Fariborz Jahaniana7e1dcd2010-02-05 16:43:40 +0000182 if (!Rewrite.ReplaceStmt(Old, New)) {
Steve Naroff22216db2008-12-04 23:50:32 +0000183 ReplacedNodes[Old] = New;
184 return;
185 }
186 if (SilenceRewriteMacroWarning)
187 return;
Chris Lattner8488c822008-11-18 07:04:44 +0000188 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
189 << Old->getSourceRange();
Chris Lattner2e0d2602008-01-31 19:37:57 +0000190 }
Steve Naroff08628db2008-12-09 12:56:34 +0000191
192 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
193 // Measaure the old text.
194 int Size = Rewrite.getRangeSize(SrcRange);
195 if (Size == -1) {
196 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
197 << Old->getSourceRange();
198 return;
199 }
200 // Get the new text.
201 std::string SStr;
202 llvm::raw_string_ostream S(SStr);
Chris Lattnerc61089a2009-06-30 01:26:17 +0000203 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroff08628db2008-12-09 12:56:34 +0000204 const std::string &Str = S.str();
205
206 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000207 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroff08628db2008-12-09 12:56:34 +0000208 ReplacedNodes[Old] = New;
209 return;
210 }
211 if (SilenceRewriteMacroWarning)
212 return;
213 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
214 << Old->getSourceRange();
215 }
216
Steve Naroff00a31762008-03-27 22:29:16 +0000217 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
218 bool InsertAfter = true) {
Chris Lattner9cc55f52008-01-31 19:51:04 +0000219 // If insertion succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000220 if (!Rewrite.InsertText(Loc, llvm::StringRef(StrData, StrLen),
221 InsertAfter) ||
Chris Lattner1780a852008-01-31 19:42:41 +0000222 SilenceRewriteMacroWarning)
223 return;
Mike Stump11289f42009-09-09 15:08:12 +0000224
Chris Lattner1780a852008-01-31 19:42:41 +0000225 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
226 }
Mike Stump11289f42009-09-09 15:08:12 +0000227
Chris Lattner9cc55f52008-01-31 19:51:04 +0000228 void RemoveText(SourceLocation Loc, unsigned StrLen) {
229 // If removal succeeded or warning disabled return with no warning.
230 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
231 return;
Mike Stump11289f42009-09-09 15:08:12 +0000232
Chris Lattner9cc55f52008-01-31 19:51:04 +0000233 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
234 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000235
Chris Lattner9cc55f52008-01-31 19:51:04 +0000236 void ReplaceText(SourceLocation Start, unsigned OrigLength,
237 const char *NewStr, unsigned NewLength) {
238 // If removal succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000239 if (!Rewrite.ReplaceText(Start, OrigLength,
240 llvm::StringRef(NewStr, NewLength)) ||
Chris Lattner9cc55f52008-01-31 19:51:04 +0000241 SilenceRewriteMacroWarning)
242 return;
Mike Stump11289f42009-09-09 15:08:12 +0000243
Chris Lattner9cc55f52008-01-31 19:51:04 +0000244 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
245 }
Mike Stump11289f42009-09-09 15:08:12 +0000246
Chris Lattner3c799d72007-10-24 17:06:59 +0000247 // Syntactic Rewriting.
Steve Narofff36987c2007-11-04 22:37:50 +0000248 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000249 void RewriteInclude();
Chris Lattner3c799d72007-10-24 17:06:59 +0000250 void RewriteTabs();
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000251 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffc038b3a2008-12-02 17:36:43 +0000252 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
253 ObjCImplementationDecl *IMD,
254 ObjCCategoryImplDecl *CID);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000255 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000256 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000257 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +0000258 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
259 ValueDecl *VD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000260 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
261 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
262 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
263 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000264 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000265 void RewriteFunctionDecl(FunctionDecl *FD);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000266 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000267 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +0000268 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff873bd842008-07-29 18:15:38 +0000269 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroff50d42052007-11-01 13:24:47 +0000270 bool needToScanForQualifiers(QualType T);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000271 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff7fa2f042007-11-15 10:28:18 +0000272 QualType getSuperStructType();
Steve Naroffce8e8862008-03-15 00:55:56 +0000273 QualType getConstantStringStructType();
Steve Naroffcd92aeb2008-05-31 14:15:04 +0000274 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump11289f42009-09-09 15:08:12 +0000275
Chris Lattner3c799d72007-10-24 17:06:59 +0000276 // Expression Rewriting.
Steve Naroff20113382007-11-09 15:20:18 +0000277 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroff4588d0f2008-12-04 16:24:46 +0000278 void CollectPropertySetters(Stmt *S);
Mike Stump11289f42009-09-09 15:08:12 +0000279
Steve Naroff1042ff32008-12-08 16:43:47 +0000280 Stmt *CurrentBody;
281 ParentMap *PropParentMap; // created lazily.
Mike Stump11289f42009-09-09 15:08:12 +0000282
Chris Lattner69534692007-10-24 16:57:36 +0000283 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +0000284 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart,
285 bool &replaced);
286 Stmt *RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced);
Steve Naroff4588d0f2008-12-04 16:24:46 +0000287 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Mike Stump11289f42009-09-09 15:08:12 +0000288 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroff08628db2008-12-09 12:56:34 +0000289 SourceRange SrcRange);
Steve Naroffe4f9b232007-11-05 14:50:49 +0000290 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner69534692007-10-24 16:57:36 +0000291 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffa397efd2007-11-03 11:27:19 +0000292 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian33c0e812007-12-07 18:47:10 +0000293 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffec60b432009-12-05 21:43:12 +0000294 void WarnAboutReturnGotoStmts(Stmt *S);
295 void HasReturnStmts(Stmt *S, bool &hasReturns);
296 void RewriteTryReturnStmts(Stmt *S);
297 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000298 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian284011b2008-01-29 22:59:37 +0000299 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000300 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
301 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
302 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattnera779d692008-01-31 05:10:40 +0000303 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
304 SourceLocation OrigEnd);
Mike Stump11289f42009-09-09 15:08:12 +0000305 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Steve Naroff574440f2007-10-24 22:48:43 +0000306 Expr **args, unsigned nargs);
Fariborz Jahanian965a8962008-01-08 22:06:28 +0000307 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +0000308 Stmt *RewriteBreakStmt(BreakStmt *S);
309 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian965a8962008-01-08 22:06:28 +0000310 void SynthCountByEnumWithState(std::string &buf);
Mike Stump11289f42009-09-09 15:08:12 +0000311
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000312 void SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +0000313 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000314 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +0000315 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000316 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000317 void SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +0000318 void SynthGetMetaClassFunctionDecl();
Fariborz Jahanian31e18502007-12-04 21:47:40 +0000319 void SynthSelGetUidFunctionDecl();
Steve Naroff17978c42008-03-11 17:37:02 +0000320 void SynthSuperContructorFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000321
Chris Lattner3c799d72007-10-24 17:06:59 +0000322 // Metadata emission.
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000323 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000324 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000325
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000326 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000327 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000328
Douglas Gregor29bd76f2009-04-23 01:02:12 +0000329 template<typename MethodIterator>
330 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
331 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +0000332 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +0000333 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +0000334 const char *ClassName,
335 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000336
Steve Naroffd9803712009-04-29 16:37:50 +0000337 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
338 const char *prefix,
339 const char *ClassName,
340 std::string &Result);
341 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Mike Stump11289f42009-09-09 15:08:12 +0000342 const char *prefix,
Steve Naroffd9803712009-04-29 16:37:50 +0000343 const char *ClassName,
344 std::string &Result);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000345 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000346 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000347 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
348 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000349 std::string &Result);
Steve Narofff8cfd162008-11-13 20:07:04 +0000350 void RewriteImplementations();
351 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000352
Steve Naroff677ab3a2008-10-27 17:20:55 +0000353 // Block rewriting.
Mike Stump11289f42009-09-09 15:08:12 +0000354 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000355 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump11289f42009-09-09 15:08:12 +0000356
Steve Naroff677ab3a2008-10-27 17:20:55 +0000357 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
358 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump11289f42009-09-09 15:08:12 +0000359
360 // Block specific rewrite rules.
Steve Naroff677ab3a2008-10-27 17:20:55 +0000361 void RewriteBlockCall(CallExpr *Exp);
362 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000363 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahaniane3891582010-01-05 18:04:40 +0000364 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +0000365 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000366 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump11289f42009-09-09 15:08:12 +0000367
368 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Steve Naroff677ab3a2008-10-27 17:20:55 +0000369 const char *funcName, std::string Tag);
Mike Stump11289f42009-09-09 15:08:12 +0000370 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Steve Naroff677ab3a2008-10-27 17:20:55 +0000371 const char *funcName, std::string Tag);
Steve Naroff30484702009-12-06 21:14:13 +0000372 std::string SynthesizeBlockImpl(BlockExpr *CE,
373 std::string Tag, std::string Desc);
374 std::string SynthesizeBlockDescriptor(std::string DescTag,
375 std::string ImplTag,
376 int i, const char *funcName,
377 unsigned hasCopy);
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +0000378 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000379 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000380 const char *FunName);
Steve Naroffe70a52a2009-12-05 15:55:59 +0000381 void RewriteRecordBody(RecordDecl *RD);
Mike Stump11289f42009-09-09 15:08:12 +0000382
Steve Naroff677ab3a2008-10-27 17:20:55 +0000383 void CollectBlockDeclRefInfo(BlockExpr *Exp);
384 void GetBlockCallExprs(Stmt *S);
385 void GetBlockDeclRefExprs(Stmt *S);
Mike Stump11289f42009-09-09 15:08:12 +0000386
Steve Naroff677ab3a2008-10-27 17:20:55 +0000387 // We avoid calling Type::isBlockPointerType(), since it operates on the
388 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek5a201952009-02-07 01:47:29 +0000389 bool isTopLevelBlockPointerType(QualType T) {
390 return isa<BlockPointerType>(T);
391 }
Mike Stump11289f42009-09-09 15:08:12 +0000392
Steve Naroff677ab3a2008-10-27 17:20:55 +0000393 // FIXME: This predicate seems like it would be useful to add to ASTContext.
394 bool isObjCType(QualType T) {
395 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
396 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000397
Steve Naroff677ab3a2008-10-27 17:20:55 +0000398 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000399
Steve Naroff677ab3a2008-10-27 17:20:55 +0000400 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
401 OCT == Context->getCanonicalType(Context->getObjCClassType()))
402 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000403
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000404 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +0000405 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Narofffb4330f2009-06-17 22:40:22 +0000406 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff677ab3a2008-10-27 17:20:55 +0000407 return true;
408 }
409 return false;
410 }
411 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek5a201952009-02-07 01:47:29 +0000412 void GetExtentOfArgList(const char *Name, const char *&LParen,
413 const char *&RParen);
Steve Naroffc989a7b2008-11-03 23:29:32 +0000414 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump11289f42009-09-09 15:08:12 +0000415
Steve Narofff4b992a2008-10-28 20:29:00 +0000416 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroffd8907b72008-10-29 18:15:37 +0000417 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Mike Stump11289f42009-09-09 15:08:12 +0000418
Steve Naroffd9803712009-04-29 16:37:50 +0000419 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump11289f42009-09-09 15:08:12 +0000420 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroffd9803712009-04-29 16:37:50 +0000421 if (From[i] == '"')
422 To += "\\\"";
423 else
424 To += From[i];
425 }
426 }
Chris Lattnere99c8322007-10-11 00:43:27 +0000427 };
John McCall97513962010-01-15 18:39:57 +0000428
429 // Helper function: create a CStyleCastExpr with trivial type source info.
430 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
431 CastExpr::CastKind Kind, Expr *E) {
432 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
433 return new (Ctx) CStyleCastExpr(Ty, Kind, E, TInfo,
434 SourceLocation(), SourceLocation());
435 }
Chris Lattnere99c8322007-10-11 00:43:27 +0000436}
437
Mike Stump11289f42009-09-09 15:08:12 +0000438void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
439 NamedDecl *D) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000440 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000441 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +0000442 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +0000443 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +0000444 // All the args are checked/rewritten. Don't call twice!
445 RewriteBlockPointerDecl(D);
446 break;
447 }
448 }
449}
450
451void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000452 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +0000453 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000454 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000455}
456
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000457static bool IsHeaderFile(const std::string &Filename) {
458 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump11289f42009-09-09 15:08:12 +0000459
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000460 if (DotPos == std::string::npos) {
461 // no file extension
Mike Stump11289f42009-09-09 15:08:12 +0000462 return false;
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000463 }
Mike Stump11289f42009-09-09 15:08:12 +0000464
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000465 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
466 // C header: .h
467 // C++ header: .hh or .H;
468 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump11289f42009-09-09 15:08:12 +0000469}
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000470
Eli Friedman94cf21e2009-05-18 22:20:00 +0000471RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000472 Diagnostic &D, const LangOptions &LOpts,
473 bool silenceMacroWarn)
474 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
475 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Narofff9e7c902008-03-28 22:26:09 +0000476 IsHeader = IsHeaderFile(inFile);
Mike Stump11289f42009-09-09 15:08:12 +0000477 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Narofff9e7c902008-03-28 22:26:09 +0000478 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump11289f42009-09-09 15:08:12 +0000479 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek5a201952009-02-07 01:47:29 +0000480 "rewriter doesn't support user-specified control flow semantics "
481 "for @try/@finally (code may not execute properly)");
Steve Narofff9e7c902008-03-28 22:26:09 +0000482}
483
Eli Friedmana63ab2d2009-05-18 22:29:17 +0000484ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
485 llvm::raw_ostream* OS,
Mike Stump11289f42009-09-09 15:08:12 +0000486 Diagnostic &Diags,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000487 const LangOptions &LOpts,
488 bool SilenceRewriteMacroWarning) {
489 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere9c810c2007-11-30 22:25:36 +0000490}
Chris Lattnere99c8322007-10-11 00:43:27 +0000491
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000492void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner187f6262008-01-31 19:38:44 +0000493 Context = &context;
494 SM = &Context->getSourceManager();
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +0000495 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner187f6262008-01-31 19:38:44 +0000496 MsgSendFunctionDecl = 0;
497 MsgSendSuperFunctionDecl = 0;
498 MsgSendStretFunctionDecl = 0;
499 MsgSendSuperStretFunctionDecl = 0;
500 MsgSendFpretFunctionDecl = 0;
501 GetClassFunctionDecl = 0;
502 GetMetaClassFunctionDecl = 0;
503 SelGetUidFunctionDecl = 0;
504 CFStringFunctionDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000505 ConstantStringClassReference = 0;
506 NSStringRecord = 0;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000507 CurMethodDef = 0;
508 CurFunctionDef = 0;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000509 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000510 GlobalVarDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000511 SuperStructDecl = 0;
Steve Naroffd9803712009-04-29 16:37:50 +0000512 ProtocolTypeDecl = 0;
Steve Naroff60a9ef62008-03-27 22:59:54 +0000513 ConstantStringDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000514 BcLabelCount = 0;
Steve Naroff17978c42008-03-11 17:37:02 +0000515 SuperContructorFunctionDecl = 0;
Steve Naroffce8e8862008-03-15 00:55:56 +0000516 NumObjCStringLiterals = 0;
Steve Narofff1ab6002008-12-08 20:01:41 +0000517 PropParentMap = 0;
518 CurrentBody = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000519 DisableReplaceStmt = false;
Fariborz Jahanianbc6811c2010-01-07 22:51:18 +0000520 objc_impl_method = false;
Mike Stump11289f42009-09-09 15:08:12 +0000521
Chris Lattner187f6262008-01-31 19:38:44 +0000522 // Get the ID and start/end of the main file.
523 MainFileID = SM->getMainFileID();
524 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
525 MainFileStart = MainBuf->getBufferStart();
526 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000527
Chris Lattner184e65d2009-04-14 23:22:57 +0000528 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump11289f42009-09-09 15:08:12 +0000529
Chris Lattner187f6262008-01-31 19:38:44 +0000530 // declaring objc_selector outside the parameter list removes a silly
531 // scope related warning...
Steve Naroff00a31762008-03-27 22:29:16 +0000532 if (IsHeader)
Steve Narofffcc6fd52009-02-03 20:39:18 +0000533 Preamble = "#pragma once\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000534 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff6ab6dc72008-12-23 20:11:22 +0000535 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroff00a31762008-03-27 22:29:16 +0000536 Preamble += "struct objc_object *superClass; ";
Steve Naroff17978c42008-03-11 17:37:02 +0000537 if (LangOpts.Microsoft) {
538 // Add a constructor for creating temporary objects.
Ted Kremenek5a201952009-02-07 01:47:29 +0000539 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
540 ": ";
Steve Naroff00a31762008-03-27 22:29:16 +0000541 Preamble += "object(o), superClass(s) {} ";
Steve Naroff17978c42008-03-11 17:37:02 +0000542 }
Steve Naroff00a31762008-03-27 22:29:16 +0000543 Preamble += "};\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000544 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
545 Preamble += "typedef struct objc_object Protocol;\n";
546 Preamble += "#define _REWRITER_typedef_Protocol\n";
547 Preamble += "#endif\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000548 if (LangOpts.Microsoft) {
549 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
550 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
551 } else
552 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
553 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroff00a31762008-03-27 22:29:16 +0000554 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000555 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroff00a31762008-03-27 22:29:16 +0000556 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000557 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000558 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000559 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000560 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000561 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroff00a31762008-03-27 22:29:16 +0000562 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000563 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000564 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000565 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000566 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000567 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
568 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
569 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
570 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
571 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroffd30f8c52008-05-09 21:17:56 +0000572 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff8dd15252008-07-16 18:58:11 +0000573 // @synchronized hooks.
Steve Narofff122ff02008-12-08 17:30:33 +0000574 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
575 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
576 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000577 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
578 Preamble += "struct __objcFastEnumerationState {\n\t";
579 Preamble += "unsigned long state;\n\t";
Steve Naroff4dbab8a2008-04-04 22:58:22 +0000580 Preamble += "void **itemsPtr;\n\t";
Steve Naroff00a31762008-03-27 22:29:16 +0000581 Preamble += "unsigned long *mutationsPtr;\n\t";
582 Preamble += "unsigned long extra[5];\n};\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000583 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000584 Preamble += "#define __FASTENUMERATIONSTATE\n";
585 Preamble += "#endif\n";
586 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
587 Preamble += "struct __NSConstantStringImpl {\n";
588 Preamble += " int *isa;\n";
589 Preamble += " int flags;\n";
590 Preamble += " char *str;\n";
591 Preamble += " long length;\n";
592 Preamble += "};\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000593 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
594 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
595 Preamble += "#else\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000596 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000597 Preamble += "#endif\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000598 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
599 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000600 // Blocks preamble.
601 Preamble += "#ifndef BLOCK_IMPL\n";
602 Preamble += "#define BLOCK_IMPL\n";
603 Preamble += "struct __block_impl {\n";
604 Preamble += " void *isa;\n";
605 Preamble += " int Flags;\n";
Steve Naroff30484702009-12-06 21:14:13 +0000606 Preamble += " int Reserved;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000607 Preamble += " void *FuncPtr;\n";
608 Preamble += "};\n";
Steve Naroff61d879e2008-12-16 15:50:30 +0000609 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroff287a2bf2009-12-06 01:52:22 +0000610 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000611 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_assign(void *, const void *, const int);\n";
612 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
613 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
614 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
615 Preamble += "#else\n";
Steve Naroff7bf01ea2010-01-05 18:09:31 +0000616 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
617 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000618 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
619 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
620 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000621 Preamble += "#endif\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000622 if (LangOpts.Microsoft) {
Steve Narofff122ff02008-12-08 17:30:33 +0000623 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
624 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000625 Preamble += "#define __attribute__(X)\n";
Fariborz Jahanianf0462ff2010-01-15 22:29:39 +0000626 Preamble += "#define __weak\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000627 }
Fariborz Jahanian7fac6552010-01-05 19:21:35 +0000628 else {
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000629 Preamble += "#define __block\n";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +0000630 Preamble += "#define __weak\n";
631 }
Chris Lattner187f6262008-01-31 19:38:44 +0000632}
633
634
Chris Lattner3c799d72007-10-24 17:06:59 +0000635//===----------------------------------------------------------------------===//
636// Top Level Driver Code
637//===----------------------------------------------------------------------===//
638
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000639void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremenek31e7f0f2010-02-05 21:28:51 +0000640 if (Diags.hasErrorOccurred())
641 return;
642
Chris Lattner0bd1c972007-10-16 21:07:07 +0000643 // Two cases: either the decl could be in the main file, or it could be in a
644 // #included file. If the former, rewrite it now. If the later, check to see
645 // if we rewrote the #include/#import.
646 SourceLocation Loc = D->getLocation();
Chris Lattner8a425862009-01-16 07:36:28 +0000647 Loc = SM->getInstantiationLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000648
Chris Lattner0bd1c972007-10-16 21:07:07 +0000649 // If this is for a builtin, ignore it.
650 if (Loc.isInvalid()) return;
651
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000652 // Look for built-in declarations that we need to refer during the rewrite.
653 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000654 RewriteFunctionDecl(FD);
Steve Naroff08899ff2008-04-15 22:42:06 +0000655 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000656 // declared in <Foundation/NSString.h>
Chris Lattner86d7d912008-11-24 03:54:41 +0000657 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000658 ConstantStringClassReference = FVD;
659 return;
660 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000661 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff161a92b2007-10-26 20:53:56 +0000662 RewriteInterfaceDecl(MD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000663 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000664 RewriteCategoryDecl(CD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000665 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff921385f2007-10-30 16:42:30 +0000666 RewriteProtocolDecl(PD);
Mike Stump11289f42009-09-09 15:08:12 +0000667 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000668 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000669 RewriteForwardProtocolDecl(FP);
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000670 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
671 // Recurse into linkage specifications
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000672 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
673 DIEnd = LSD->decls_end();
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000674 DI != DIEnd; ++DI)
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000675 HandleTopLevelSingleDecl(*DI);
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000676 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000677 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekd61ed3b2008-04-14 21:24:13 +0000678 if (SM->isFromMainFile(Loc))
Chris Lattner0bd1c972007-10-16 21:07:07 +0000679 return HandleDeclInMainFile(D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000680}
681
Chris Lattner3c799d72007-10-24 17:06:59 +0000682//===----------------------------------------------------------------------===//
683// Syntactic (non-AST) Rewriting Code
684//===----------------------------------------------------------------------===//
685
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000686void RewriteObjC::RewriteInclude() {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000687 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000688 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
689 const char *MainBufStart = MainBuf.first;
690 const char *MainBufEnd = MainBuf.second;
691 size_t ImportLen = strlen("import");
692 size_t IncludeLen = strlen("include");
Mike Stump11289f42009-09-09 15:08:12 +0000693
Fariborz Jahanian137d6932008-01-19 01:03:17 +0000694 // Loop over the whole file, looking for includes.
Fariborz Jahanian80258362008-01-19 00:30:35 +0000695 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
696 if (*BufPtr == '#') {
697 if (++BufPtr == MainBufEnd)
698 return;
699 while (*BufPtr == ' ' || *BufPtr == '\t')
700 if (++BufPtr == MainBufEnd)
701 return;
702 if (!strncmp(BufPtr, "import", ImportLen)) {
703 // replace import with include
Mike Stump11289f42009-09-09 15:08:12 +0000704 SourceLocation ImportLoc =
Fariborz Jahanian80258362008-01-19 00:30:35 +0000705 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000706 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000707 BufPtr += ImportLen;
708 }
709 }
710 }
Chris Lattner0bd1c972007-10-16 21:07:07 +0000711}
712
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000713void RewriteObjC::RewriteTabs() {
Chris Lattner3c799d72007-10-24 17:06:59 +0000714 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
715 const char *MainBufStart = MainBuf.first;
716 const char *MainBufEnd = MainBuf.second;
Mike Stump11289f42009-09-09 15:08:12 +0000717
Chris Lattner3c799d72007-10-24 17:06:59 +0000718 // Loop over the whole file, looking for tabs.
719 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
720 if (*BufPtr != '\t')
721 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000722
Chris Lattner3c799d72007-10-24 17:06:59 +0000723 // Okay, we found a tab. This tab will turn into at least one character,
724 // but it depends on which 'virtual column' it is in. Compute that now.
725 unsigned VCol = 0;
726 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
727 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
728 ++VCol;
Mike Stump11289f42009-09-09 15:08:12 +0000729
Chris Lattner3c799d72007-10-24 17:06:59 +0000730 // Okay, now that we know the virtual column, we know how many spaces to
731 // insert. We assume 8-character tab-stops.
732 unsigned Spaces = 8-(VCol & 7);
Mike Stump11289f42009-09-09 15:08:12 +0000733
Chris Lattner3c799d72007-10-24 17:06:59 +0000734 // Get the location of the tab.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000735 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
736 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Mike Stump11289f42009-09-09 15:08:12 +0000737
Chris Lattner3c799d72007-10-24 17:06:59 +0000738 // Rewrite the single tab character into a sequence of spaces.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000739 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattner3c799d72007-10-24 17:06:59 +0000740 }
Chris Lattner16a0de42007-10-11 18:38:32 +0000741}
742
Steve Naroff9af94912008-12-02 15:48:25 +0000743static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
744 ObjCIvarDecl *OID) {
745 std::string S;
746 S = "((struct ";
747 S += ClassDecl->getIdentifier()->getName();
748 S += "_IMPL *)self)->";
Daniel Dunbar70e7ead2009-10-18 20:26:27 +0000749 S += OID->getName();
Steve Naroff9af94912008-12-02 15:48:25 +0000750 return S;
751}
752
Steve Naroffc038b3a2008-12-02 17:36:43 +0000753void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
754 ObjCImplementationDecl *IMD,
755 ObjCCategoryImplDecl *CID) {
Steve Naroffe1908e32008-12-01 20:33:01 +0000756 SourceLocation startLoc = PID->getLocStart();
757 InsertText(startLoc, "// ", 3);
Steve Naroff9af94912008-12-02 15:48:25 +0000758 const char *startBuf = SM->getCharacterData(startLoc);
759 assert((*startBuf == '@') && "bogus @synthesize location");
760 const char *semiBuf = strchr(startBuf, ';');
761 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek5a201952009-02-07 01:47:29 +0000762 SourceLocation onePastSemiLoc =
763 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroff9af94912008-12-02 15:48:25 +0000764
765 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
766 return; // FIXME: is this correct?
Mike Stump11289f42009-09-09 15:08:12 +0000767
Steve Naroff9af94912008-12-02 15:48:25 +0000768 // Generate the 'getter' function.
Steve Naroff9af94912008-12-02 15:48:25 +0000769 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroff9af94912008-12-02 15:48:25 +0000770 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroff9af94912008-12-02 15:48:25 +0000771 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000772
Steve Naroff003d00e2008-12-02 16:05:55 +0000773 if (!OID)
774 return;
Mike Stump11289f42009-09-09 15:08:12 +0000775
Steve Naroff003d00e2008-12-02 16:05:55 +0000776 std::string Getr;
777 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
778 Getr += "{ ";
779 // Synthesize an explicit cast to gain access to the ivar.
Mike Stump11289f42009-09-09 15:08:12 +0000780 // FIXME: deal with code generation implications for various property
781 // attributes (copy, retain, nonatomic).
Steve Naroff06297042008-12-02 17:54:50 +0000782 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroff003d00e2008-12-02 16:05:55 +0000783 Getr += "return " + getIvarAccessString(ClassDecl, OID);
784 Getr += "; }";
Steve Naroff9af94912008-12-02 15:48:25 +0000785 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroff9af94912008-12-02 15:48:25 +0000786 if (PD->isReadOnly())
787 return;
Mike Stump11289f42009-09-09 15:08:12 +0000788
Steve Naroff9af94912008-12-02 15:48:25 +0000789 // Generate the 'setter' function.
790 std::string Setr;
791 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroff9af94912008-12-02 15:48:25 +0000792 Setr += "{ ";
Steve Naroff003d00e2008-12-02 16:05:55 +0000793 // Synthesize an explicit cast to initialize the ivar.
Mike Stump11289f42009-09-09 15:08:12 +0000794 // FIXME: deal with code generation implications for various property
795 // attributes (copy, retain, nonatomic).
Steve Narofff326f402008-12-03 00:56:33 +0000796 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroff003d00e2008-12-02 16:05:55 +0000797 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000798 Setr += PD->getNameAsCString();
Steve Naroff003d00e2008-12-02 16:05:55 +0000799 Setr += "; }";
Steve Naroff9af94912008-12-02 15:48:25 +0000800 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffe1908e32008-12-01 20:33:01 +0000801}
Chris Lattner16a0de42007-10-11 18:38:32 +0000802
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000803void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattner3c799d72007-10-24 17:06:59 +0000804 // Get the start location and compute the semi location.
805 SourceLocation startLoc = ClassDecl->getLocation();
806 const char *startBuf = SM->getCharacterData(startLoc);
807 const char *semiPtr = strchr(startBuf, ';');
Mike Stump11289f42009-09-09 15:08:12 +0000808
Chris Lattner3c799d72007-10-24 17:06:59 +0000809 // Translate to typedef's that forward reference structs with the same name
810 // as the class. As a convenience, we include the original declaration
811 // as a comment.
812 std::string typedefString;
Fariborz Jahanian1c2cb6d2010-01-11 22:48:40 +0000813 typedefString += "// @class ";
814 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
815 I != E; ++I) {
816 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
817 typedefString += ForwardDecl->getNameAsString();
818 if (I+1 != E)
819 typedefString += ", ";
820 else
821 typedefString += ";\n";
822 }
823
Chris Lattner9ee23b72009-02-20 18:04:31 +0000824 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
825 I != E; ++I) {
Ted Kremenek9b124e12009-11-18 00:28:11 +0000826 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff1b232132007-11-09 12:50:28 +0000827 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000828 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000829 typedefString += "\n";
830 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000831 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000832 typedefString += "\n";
Steve Naroff98eb8d12007-11-05 14:36:37 +0000833 typedefString += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000834 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000835 typedefString += ";\n#endif\n";
Steve Naroff574440f2007-10-24 22:48:43 +0000836 }
Mike Stump11289f42009-09-09 15:08:12 +0000837
Steve Naroff574440f2007-10-24 22:48:43 +0000838 // Replace the @class with typedefs corresponding to the classes.
Mike Stump11289f42009-09-09 15:08:12 +0000839 ReplaceText(startLoc, semiPtr-startBuf+1,
Chris Lattner9cc55f52008-01-31 19:51:04 +0000840 typedefString.c_str(), typedefString.size());
Chris Lattner3c799d72007-10-24 17:06:59 +0000841}
842
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000843void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000844 // When method is a synthesized one, such as a getter/setter there is
845 // nothing to rewrite.
846 if (Method->isSynthesized())
847 return;
Steve Naroff3ce37a62007-12-14 23:37:57 +0000848 SourceLocation LocStart = Method->getLocStart();
849 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000850
Chris Lattner88ea93e2009-02-04 01:06:56 +0000851 if (SM->getInstantiationLineNumber(LocEnd) >
852 SM->getInstantiationLineNumber(LocStart)) {
Steve Naroffe020fa12008-10-21 13:37:27 +0000853 InsertText(LocStart, "#if 0\n", 6);
854 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff3ce37a62007-12-14 23:37:57 +0000855 } else {
Chris Lattner1780a852008-01-31 19:42:41 +0000856 InsertText(LocStart, "// ", 3);
Steve Naroff5448cf62007-10-30 13:30:57 +0000857 }
858}
859
Mike Stump11289f42009-09-09 15:08:12 +0000860void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000861 SourceLocation Loc = prop->getAtLoc();
Mike Stump11289f42009-09-09 15:08:12 +0000862
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000863 ReplaceText(Loc, 0, "// ", 3);
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000864 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahaniane8a30162007-11-07 00:09:37 +0000865}
866
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000867void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000868 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000869
Steve Naroff5448cf62007-10-30 13:30:57 +0000870 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000871 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000872
Fariborz Jahanian68ebe632010-02-10 01:15:09 +0000873 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
874 E = CatDecl->prop_end(); I != E; ++I)
875 RewriteProperty(*I);
876
Mike Stump11289f42009-09-09 15:08:12 +0000877 for (ObjCCategoryDecl::instmeth_iterator
878 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000879 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000880 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +0000881 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000882 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000883 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000884 RewriteMethodDeclaration(*I);
885
Steve Naroff5448cf62007-10-30 13:30:57 +0000886 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +0000887 ReplaceText(CatDecl->getAtEndRange().getBegin(), 0, "// ", 3);
Steve Naroff5448cf62007-10-30 13:30:57 +0000888}
889
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000890void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000891 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Mike Stump11289f42009-09-09 15:08:12 +0000892
Steve Narofff921385f2007-10-30 16:42:30 +0000893 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000894
Steve Narofff921385f2007-10-30 16:42:30 +0000895 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000896 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000897
898 for (ObjCProtocolDecl::instmeth_iterator
899 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000900 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000901 RewriteMethodDeclaration(*I);
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000902 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000903 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000904 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000905 RewriteMethodDeclaration(*I);
906
Steve Narofff921385f2007-10-30 16:42:30 +0000907 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +0000908 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Chris Lattner9cc55f52008-01-31 19:51:04 +0000909 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroffa509f042007-11-14 15:03:57 +0000910
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000911 // Must comment out @optional/@required
912 const char *startBuf = SM->getCharacterData(LocStart);
913 const char *endBuf = SM->getCharacterData(LocEnd);
914 for (const char *p = startBuf; p < endBuf; p++) {
915 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
916 std::string CommentedOptional = "/* @optional */";
Steve Naroffa509f042007-11-14 15:03:57 +0000917 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000918 ReplaceText(OptionalLoc, strlen("@optional"),
919 CommentedOptional.c_str(), CommentedOptional.size());
Mike Stump11289f42009-09-09 15:08:12 +0000920
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000921 }
922 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
923 std::string CommentedRequired = "/* @required */";
Steve Naroffa509f042007-11-14 15:03:57 +0000924 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000925 ReplaceText(OptionalLoc, strlen("@required"),
926 CommentedRequired.c_str(), CommentedRequired.size());
Mike Stump11289f42009-09-09 15:08:12 +0000927
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000928 }
929 }
Steve Narofff921385f2007-10-30 16:42:30 +0000930}
931
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000932void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000933 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffc17b0562007-11-14 03:37:28 +0000934 if (LocStart.isInvalid())
935 assert(false && "Invalid SourceLocation");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000936 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000937 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000938}
939
Mike Stump11289f42009-09-09 15:08:12 +0000940void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000941 std::string &ResultStr) {
Steve Naroff295570a2008-10-30 12:09:33 +0000942 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroffb067bbd2008-07-16 14:40:40 +0000943 const FunctionType *FPRetType = 0;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000944 ResultStr += "\nstatic ";
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000945 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +0000946 ResultStr += "id";
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000947 else if (OMD->getResultType()->isFunctionPointerType() ||
948 OMD->getResultType()->isBlockPointerType()) {
Steve Naroffb067bbd2008-07-16 14:40:40 +0000949 // needs special handling, since pointer-to-functions have special
950 // syntax (where a decaration models use).
951 QualType retType = OMD->getResultType();
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000952 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000953 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000954 PointeeTy = PT->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000955 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000956 PointeeTy = BPT->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +0000957 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000958 ResultStr += FPRetType->getResultType().getAsString();
959 ResultStr += "(*";
Steve Naroffb067bbd2008-07-16 14:40:40 +0000960 }
961 } else
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +0000962 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian7262fca2008-01-10 01:39:52 +0000963 ResultStr += " ";
Mike Stump11289f42009-09-09 15:08:12 +0000964
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000965 // Unique method name
Fariborz Jahanian56338352007-11-13 21:02:00 +0000966 std::string NameStr;
Mike Stump11289f42009-09-09 15:08:12 +0000967
Douglas Gregorffca3a22009-01-09 17:18:27 +0000968 if (OMD->isInstanceMethod())
Fariborz Jahanian56338352007-11-13 21:02:00 +0000969 NameStr += "_I_";
970 else
971 NameStr += "_C_";
Mike Stump11289f42009-09-09 15:08:12 +0000972
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000973 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +0000974 NameStr += "_";
Mike Stump11289f42009-09-09 15:08:12 +0000975
976 if (ObjCCategoryImplDecl *CID =
Steve Naroff11b387f2009-01-08 19:41:02 +0000977 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000978 NameStr += CID->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +0000979 NameStr += "_";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000980 }
Mike Stump11289f42009-09-09 15:08:12 +0000981 // Append selector names, replacing ':' with '_'
Chris Lattnere4b95692008-11-24 03:33:13 +0000982 {
983 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000984 int len = selString.size();
985 for (int i = 0; i < len; i++)
986 if (selString[i] == ':')
987 selString[i] = '_';
Fariborz Jahanian56338352007-11-13 21:02:00 +0000988 NameStr += selString;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000989 }
Fariborz Jahanian56338352007-11-13 21:02:00 +0000990 // Remember this name for metadata emission
991 MethodInternalNames[OMD] = NameStr;
992 ResultStr += NameStr;
Mike Stump11289f42009-09-09 15:08:12 +0000993
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000994 // Rewrite arguments
995 ResultStr += "(";
Mike Stump11289f42009-09-09 15:08:12 +0000996
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000997 // invisible arguments
Douglas Gregorffca3a22009-01-09 17:18:27 +0000998 if (OMD->isInstanceMethod()) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000999 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001000 selfTy = Context->getPointerType(selfTy);
Steve Naroffdc5b6b22008-03-12 00:25:36 +00001001 if (!LangOpts.Microsoft) {
1002 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
1003 ResultStr += "struct ";
1004 }
1005 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001006 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00001007 ResultStr += " *";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001008 }
1009 else
Steve Naroffd9803712009-04-29 16:37:50 +00001010 ResultStr += Context->getObjCClassType().getAsString();
Mike Stump11289f42009-09-09 15:08:12 +00001011
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001012 ResultStr += " self, ";
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001013 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001014 ResultStr += " _cmd";
Mike Stump11289f42009-09-09 15:08:12 +00001015
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001016 // Method arguments.
Chris Lattnera4997152009-02-20 18:43:26 +00001017 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1018 E = OMD->param_end(); PI != E; ++PI) {
1019 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001020 ResultStr += ", ";
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001021 if (PDecl->getType()->isObjCQualifiedIdType()) {
1022 ResultStr += "id ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001023 ResultStr += PDecl->getNameAsString();
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001024 } else {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001025 std::string Name = PDecl->getNameAsString();
Steve Naroffa5c0db82008-12-11 21:05:33 +00001026 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroff44df6a22008-10-30 14:45:29 +00001027 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001028 const BlockPointerType *BPT = PDecl->getType()->getAs<BlockPointerType>();
Douglas Gregor7de59662009-05-29 20:38:28 +00001029 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name,
1030 Context->PrintingPolicy);
Steve Naroff44df6a22008-10-30 14:45:29 +00001031 } else
Douglas Gregor7de59662009-05-29 20:38:28 +00001032 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001033 ResultStr += Name;
1034 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001035 }
Fariborz Jahanianeab81cd2008-01-21 20:14:23 +00001036 if (OMD->isVariadic())
1037 ResultStr += ", ...";
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001038 ResultStr += ") ";
Mike Stump11289f42009-09-09 15:08:12 +00001039
Steve Naroffb067bbd2008-07-16 14:40:40 +00001040 if (FPRetType) {
1041 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump11289f42009-09-09 15:08:12 +00001042
Steve Naroffb067bbd2008-07-16 14:40:40 +00001043 // Now, emit the argument types (if any).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001044 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001045 ResultStr += "(";
1046 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1047 if (i) ResultStr += ", ";
1048 std::string ParamStr = FT->getArgType(i).getAsString();
1049 ResultStr += ParamStr;
1050 }
1051 if (FT->isVariadic()) {
1052 if (FT->getNumArgs()) ResultStr += ", ";
1053 ResultStr += "...";
1054 }
1055 ResultStr += ")";
1056 } else {
1057 ResultStr += "()";
1058 }
1059 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001060}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001061void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001062 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1063 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump11289f42009-09-09 15:08:12 +00001064
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001065 if (IMD)
Chris Lattner1780a852008-01-31 19:42:41 +00001066 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001067 else
Chris Lattner1780a852008-01-31 19:42:41 +00001068 InsertText(CID->getLocStart(), "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +00001069
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001070 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001071 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1072 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001073 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001074 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001075 ObjCMethodDecl *OMD = *I;
1076 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001077 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001078 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redla7b98a72009-04-26 20:35:05 +00001079
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001080 const char *startBuf = SM->getCharacterData(LocStart);
1081 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattner9cc55f52008-01-31 19:51:04 +00001082 ReplaceText(LocStart, endBuf-startBuf,
1083 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001084 }
Mike Stump11289f42009-09-09 15:08:12 +00001085
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001086 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001087 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1088 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001089 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001090 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001091 ObjCMethodDecl *OMD = *I;
1092 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001093 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001094 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +00001095
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001096 const char *startBuf = SM->getCharacterData(LocStart);
1097 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattner9cc55f52008-01-31 19:51:04 +00001098 ReplaceText(LocStart, endBuf-startBuf,
Mike Stump11289f42009-09-09 15:08:12 +00001099 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001100 }
Steve Naroffe1908e32008-12-01 20:33:01 +00001101 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001102 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001103 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001104 I != E; ++I) {
Steve Naroffc038b3a2008-12-02 17:36:43 +00001105 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffe1908e32008-12-01 20:33:01 +00001106 }
1107
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001108 if (IMD)
Chris Lattner1780a852008-01-31 19:42:41 +00001109 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001110 else
Mike Stump11289f42009-09-09 15:08:12 +00001111 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001112}
1113
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001114void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffc5484042007-10-30 02:23:23 +00001115 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001116 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff2f55b982007-11-01 03:35:41 +00001117 // we haven't seen a forward decl - generate a typedef.
Steve Naroff03f27672007-11-14 23:02:56 +00001118 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001119 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001120 ResultStr += "\n";
1121 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001122 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001123 ResultStr += "\n";
Steve Naroffa1e115e2008-03-10 23:16:54 +00001124 ResultStr += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001125 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001126 ResultStr += ";\n#endif\n";
Steve Naroff2f55b982007-11-01 03:35:41 +00001127 // Mark this typedef as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001128 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff2f55b982007-11-01 03:35:41 +00001129 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001130 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump11289f42009-09-09 15:08:12 +00001131
1132 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001133 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff0c0f5ba2009-01-11 01:06:09 +00001134 RewriteProperty(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001135 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001136 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001137 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001138 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001139 for (ObjCInterfaceDecl::classmeth_iterator
1140 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001141 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001142 RewriteMethodDeclaration(*I);
1143
Steve Naroff4cd61ac2007-10-30 03:43:13 +00001144 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +00001145 ReplaceText(ClassDecl->getAtEndRange().getBegin(), 0, "// ", 3);
Steve Naroff161a92b2007-10-26 20:53:56 +00001146}
1147
Steve Naroff08628db2008-12-09 12:56:34 +00001148Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1149 SourceRange SrcRange) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00001150 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1151 // This allows us to reuse all the fun and games in SynthMessageExpr().
1152 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1153 ObjCMessageExpr *MsgExpr;
1154 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1155 llvm::SmallVector<Expr *, 1> ExprVec;
1156 ExprVec.push_back(newStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001157
Steve Naroff1042ff32008-12-08 16:43:47 +00001158 Stmt *Receiver = PropRefExpr->getBase();
1159 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1160 if (PRE && PropGetters[PRE]) {
1161 // This allows us to handle chain/nested property getters.
1162 Receiver = PropGetters[PRE];
1163 }
Ted Kremenek2c809302010-02-11 22:41:21 +00001164 MsgExpr = new (Context) ObjCMessageExpr(*Context, dyn_cast<Expr>(Receiver),
Mike Stump11289f42009-09-09 15:08:12 +00001165 PDecl->getSetterName(), PDecl->getType(),
1166 PDecl->getSetterMethodDecl(),
1167 SourceLocation(), SourceLocation(),
Steve Naroff4588d0f2008-12-04 16:24:46 +00001168 &ExprVec[0], 1);
1169 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001170
Steve Naroff4588d0f2008-12-04 16:24:46 +00001171 // Now do the actual rewrite.
Steve Naroff08628db2008-12-09 12:56:34 +00001172 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffdf705772008-12-10 14:53:27 +00001173 //delete BinOp;
Ted Kremenek5a201952009-02-07 01:47:29 +00001174 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1175 // to things that stay around.
1176 Context->Deallocate(MsgExpr);
Steve Naroff4588d0f2008-12-04 16:24:46 +00001177 return ReplacingStmt;
Steve Narofff326f402008-12-03 00:56:33 +00001178}
1179
Steve Naroff4588d0f2008-12-04 16:24:46 +00001180Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Narofff326f402008-12-03 00:56:33 +00001181 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1182 // This allows us to reuse all the fun and games in SynthMessageExpr().
1183 ObjCMessageExpr *MsgExpr;
1184 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
Mike Stump11289f42009-09-09 15:08:12 +00001185
Steve Naroff1042ff32008-12-08 16:43:47 +00001186 Stmt *Receiver = PropRefExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00001187
Steve Naroff1042ff32008-12-08 16:43:47 +00001188 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1189 if (PRE && PropGetters[PRE]) {
1190 // This allows us to handle chain/nested property getters.
1191 Receiver = PropGetters[PRE];
1192 }
Ted Kremenek2c809302010-02-11 22:41:21 +00001193 MsgExpr = new (Context) ObjCMessageExpr(*Context, dyn_cast<Expr>(Receiver),
Mike Stump11289f42009-09-09 15:08:12 +00001194 PDecl->getGetterName(), PDecl->getType(),
1195 PDecl->getGetterMethodDecl(),
1196 SourceLocation(), SourceLocation(),
Steve Narofff326f402008-12-03 00:56:33 +00001197 0, 0);
1198
Steve Naroff22216db2008-12-04 23:50:32 +00001199 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001200
1201 if (!PropParentMap)
1202 PropParentMap = new ParentMap(CurrentBody);
1203
1204 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1205 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1206 // We stash away the ReplacingStmt since actually doing the
1207 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1208 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek5a201952009-02-07 01:47:29 +00001209 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1210 // to things that stay around.
1211 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001212 return PropRefExpr; // return the original...
1213 } else {
1214 ReplaceStmt(PropRefExpr, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001215 // delete PropRefExpr; elsewhere...
Ted Kremenek5a201952009-02-07 01:47:29 +00001216 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1217 // to things that stay around.
1218 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001219 return ReplacingStmt;
1220 }
Steve Narofff326f402008-12-03 00:56:33 +00001221}
1222
Mike Stump11289f42009-09-09 15:08:12 +00001223Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001224 SourceLocation OrigStart,
1225 bool &replaced) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001226 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001227 const Expr *BaseExpr = IV->getBase();
Steve Naroff677ab3a2008-10-27 17:20:55 +00001228 if (CurMethodDef) {
Fariborz Jahanianf9e8c2b2010-01-26 18:28:51 +00001229 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001230 ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001231 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianf0ed69c2010-01-26 20:37:44 +00001232 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Naroffb1c02372008-05-08 17:52:16 +00001233 // lookup which class implements the instance variable.
1234 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001235 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001236 clsDeclared);
Steve Naroffb1c02372008-05-08 17:52:16 +00001237 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001238
Steve Naroffb1c02372008-05-08 17:52:16 +00001239 // Synthesize an explicit cast to gain access to the ivar.
1240 std::string RecName = clsDeclared->getIdentifier()->getName();
1241 RecName += "_IMPL";
1242 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001243 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001244 SourceLocation(), II);
Steve Naroffb1c02372008-05-08 17:52:16 +00001245 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1246 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall97513962010-01-15 18:39:57 +00001247 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1248 CastExpr::CK_Unknown,
1249 IV->getBase());
Steve Naroffb1c02372008-05-08 17:52:16 +00001250 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001251 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1252 IV->getBase()->getLocEnd(),
1253 castExpr);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001254 replaced = true;
Mike Stump11289f42009-09-09 15:08:12 +00001255 if (IV->isFreeIvar() &&
Steve Naroff677ab3a2008-10-27 17:20:55 +00001256 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001257 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1258 IV->getLocation(),
1259 D->getType());
Steve Naroff22216db2008-12-04 23:50:32 +00001260 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb1c02372008-05-08 17:52:16 +00001261 return ME;
Steve Naroff05caa482007-11-15 11:33:00 +00001262 }
Fariborz Jahanian81310812010-01-28 01:41:20 +00001263 // Get the new text
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001264 // Cannot delete IV->getBase(), since PE points to it.
1265 // Replace the old base with the cast. This is important when doing
1266 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001267 IV->setBase(PE);
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001268 return IV;
Steve Naroff05caa482007-11-15 11:33:00 +00001269 }
Steve Naroff24840f62008-04-18 21:55:08 +00001270 } else { // we are outside a method.
Steve Naroff29ce4e52008-05-06 23:20:07 +00001271 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump11289f42009-09-09 15:08:12 +00001272
Steve Naroff29ce4e52008-05-06 23:20:07 +00001273 // Explicit ivar refs need to have a cast inserted.
1274 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian12e2e862010-01-12 17:31:23 +00001275 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Fariborz Jahanian9146e442010-01-11 17:50:35 +00001276 ObjCInterfaceType *iFaceDecl =
1277 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001278 // lookup which class implements the instance variable.
1279 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001280 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001281 clsDeclared);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001282 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001283
Steve Naroff29ce4e52008-05-06 23:20:07 +00001284 // Synthesize an explicit cast to gain access to the ivar.
1285 std::string RecName = clsDeclared->getIdentifier()->getName();
1286 RecName += "_IMPL";
1287 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001288 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001289 SourceLocation(), II);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001290 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1291 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall97513962010-01-15 18:39:57 +00001292 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1293 CastExpr::CK_Unknown,
1294 IV->getBase());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001295 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001296 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner34873d22008-05-28 16:38:23 +00001297 IV->getBase()->getLocEnd(), castExpr);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001298 replaced = true;
Steve Naroff29ce4e52008-05-06 23:20:07 +00001299 // Cannot delete IV->getBase(), since PE points to it.
1300 // Replace the old base with the cast. This is important when doing
1301 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001302 IV->setBase(PE);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001303 return IV;
1304 }
Steve Naroff05caa482007-11-15 11:33:00 +00001305 }
Steve Naroff24840f62008-04-18 21:55:08 +00001306 return IV;
Steve Narofff60782b2007-11-15 02:58:25 +00001307}
1308
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001309Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
1310 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1311 CI != E; ++CI) {
1312 if (*CI) {
1313 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1314 if (newStmt)
1315 *CI = newStmt;
1316 }
1317 }
1318 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1319 SourceRange OrigStmtRange = S->getSourceRange();
1320 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1321 replaced);
1322 return newStmt;
Fariborz Jahanian31433382010-02-05 17:48:10 +00001323 }
1324 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1325 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1326 return newStmt;
1327 }
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001328 return S;
1329}
1330
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001331/// SynthCountByEnumWithState - To print:
1332/// ((unsigned int (*)
1333/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001334/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001335/// sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001336/// "countByEnumeratingWithState:objects:count:"),
1337/// &enumState,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001338/// (id *)items, (unsigned int)16)
1339///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001340void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001341 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1342 "id *, unsigned int))(void *)objc_msgSend)";
1343 buf += "\n\t\t";
1344 buf += "((id)l_collection,\n\t\t";
1345 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1346 buf += "\n\t\t";
1347 buf += "&enumState, "
1348 "(id *)items, (unsigned int)16)";
1349}
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001350
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001351/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1352/// statement to exit to its outer synthesized loop.
1353///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001354Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001355 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1356 return S;
1357 // replace break with goto __break_label
1358 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001359
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001360 SourceLocation startLoc = S->getLocStart();
1361 buf = "goto __break_label_";
1362 buf += utostr(ObjCBcLabelNo.back());
Chris Lattner9cc55f52008-01-31 19:51:04 +00001363 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001364
1365 return 0;
1366}
1367
1368/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1369/// statement to continue with its inner synthesized loop.
1370///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001371Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001372 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1373 return S;
1374 // replace continue with goto __continue_label
1375 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001376
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001377 SourceLocation startLoc = S->getLocStart();
1378 buf = "goto __continue_label_";
1379 buf += utostr(ObjCBcLabelNo.back());
Chris Lattner9cc55f52008-01-31 19:51:04 +00001380 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001381
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001382 return 0;
1383}
1384
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001385/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001386/// It rewrites:
1387/// for ( type elem in collection) { stmts; }
Mike Stump11289f42009-09-09 15:08:12 +00001388
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001389/// Into:
1390/// {
Mike Stump11289f42009-09-09 15:08:12 +00001391/// type elem;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001392/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001393/// id items[16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001394/// id l_collection = (id)collection;
Mike Stump11289f42009-09-09 15:08:12 +00001395/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001396/// objects:items count:16];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001397/// if (limit) {
1398/// unsigned long startMutations = *enumState.mutationsPtr;
1399/// do {
1400/// unsigned long counter = 0;
1401/// do {
Mike Stump11289f42009-09-09 15:08:12 +00001402/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001403/// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001404/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001405/// stmts;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001406/// __continue_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001407/// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001408/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001409/// objects:items count:16]);
1410/// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001411/// __break_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001412/// }
1413/// else
1414/// elem = nil;
1415/// }
1416///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001417Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattnera779d692008-01-31 05:10:40 +00001418 SourceLocation OrigEnd) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001419 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001420 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001421 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump11289f42009-09-09 15:08:12 +00001422 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001423 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001424
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001425 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001426 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001427 const char *elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001428 std::string elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001429 std::string buf;
1430 buf = "\n{\n\t";
1431 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1432 // type elem;
Chris Lattner529efc72009-03-28 06:33:19 +00001433 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek292b3842008-10-06 22:16:13 +00001434 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001435 if (ElementType->isObjCQualifiedIdType() ||
1436 ElementType->isObjCQualifiedInterfaceType())
1437 // Simply use 'id' for all qualified types.
1438 elementTypeAsString = "id";
1439 else
1440 elementTypeAsString = ElementType.getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001441 buf += elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001442 buf += " ";
Chris Lattner86d7d912008-11-24 03:54:41 +00001443 elementName = D->getNameAsCString();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001444 buf += elementName;
1445 buf += ";\n\t";
1446 }
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001447 else {
1448 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner86d7d912008-11-24 03:54:41 +00001449 elementName = DR->getDecl()->getNameAsCString();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001450 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1451 if (VD->getType()->isObjCQualifiedIdType() ||
1452 VD->getType()->isObjCQualifiedInterfaceType())
1453 // Simply use 'id' for all qualified types.
1454 elementTypeAsString = "id";
1455 else
1456 elementTypeAsString = VD->getType().getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001457 }
Mike Stump11289f42009-09-09 15:08:12 +00001458
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001459 // struct __objcFastEnumerationState enumState = { 0 };
1460 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1461 // id items[16];
1462 buf += "id items[16];\n\t";
1463 // id l_collection = (id)
1464 buf += "id l_collection = (id)";
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001465 // Find start location of 'collection' the hard way!
1466 const char *startCollectionBuf = startBuf;
1467 startCollectionBuf += 3; // skip 'for'
1468 startCollectionBuf = strchr(startCollectionBuf, '(');
1469 startCollectionBuf++; // skip '('
1470 // find 'in' and skip it.
1471 while (*startCollectionBuf != ' ' ||
1472 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1473 (*(startCollectionBuf+3) != ' ' &&
1474 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1475 startCollectionBuf++;
1476 startCollectionBuf += 3;
Mike Stump11289f42009-09-09 15:08:12 +00001477
1478 // Replace: "for (type element in" with string constructed thus far.
Chris Lattner9cc55f52008-01-31 19:51:04 +00001479 ReplaceText(startLoc, startCollectionBuf - startBuf,
1480 buf.c_str(), buf.size());
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001481 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001482 SourceLocation rightParenLoc = S->getRParenLoc();
1483 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1484 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001485 buf = ";\n\t";
Mike Stump11289f42009-09-09 15:08:12 +00001486
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001487 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1488 // objects:items count:16];
1489 // which is synthesized into:
Mike Stump11289f42009-09-09 15:08:12 +00001490 // unsigned int limit =
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001491 // ((unsigned int (*)
1492 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001493 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001494 // sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001495 // "countByEnumeratingWithState:objects:count:"),
1496 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001497 // (id *)items, (unsigned int)16);
1498 buf += "unsigned long limit =\n\t\t";
1499 SynthCountByEnumWithState(buf);
1500 buf += ";\n\t";
1501 /// if (limit) {
1502 /// unsigned long startMutations = *enumState.mutationsPtr;
1503 /// do {
1504 /// unsigned long counter = 0;
1505 /// do {
Mike Stump11289f42009-09-09 15:08:12 +00001506 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001507 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001508 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001509 buf += "if (limit) {\n\t";
1510 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1511 buf += "do {\n\t\t";
1512 buf += "unsigned long counter = 0;\n\t\t";
1513 buf += "do {\n\t\t\t";
1514 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1515 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1516 buf += elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001517 buf += " = (";
1518 buf += elementTypeAsString;
1519 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001520 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattner9cc55f52008-01-31 19:51:04 +00001521 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001522
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001523 /// __continue_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001524 /// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001525 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001526 /// objects:items count:16]);
1527 /// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001528 /// __break_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001529 /// }
1530 /// else
1531 /// elem = nil;
1532 /// }
Mike Stump11289f42009-09-09 15:08:12 +00001533 ///
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001534 buf = ";\n\t";
1535 buf += "__continue_label_";
1536 buf += utostr(ObjCBcLabelNo.back());
1537 buf += ": ;";
1538 buf += "\n\t\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001539 buf += "} while (counter < limit);\n\t";
1540 buf += "} while (limit = ";
1541 SynthCountByEnumWithState(buf);
1542 buf += ");\n\t";
1543 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001544 buf += " = ((";
1545 buf += elementTypeAsString;
1546 buf += ")0);\n\t";
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001547 buf += "__break_label_";
1548 buf += utostr(ObjCBcLabelNo.back());
1549 buf += ": ;\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001550 buf += "}\n\t";
1551 buf += "else\n\t\t";
1552 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001553 buf += " = ((";
1554 buf += elementTypeAsString;
1555 buf += ")0);\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001556 buf += "}\n";
Mike Stump11289f42009-09-09 15:08:12 +00001557
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001558 // Insert all these *after* the statement body.
Sebastian Redla7b98a72009-04-26 20:35:05 +00001559 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Narofff0ff8792008-07-21 18:26:02 +00001560 if (isa<CompoundStmt>(S->getBody())) {
1561 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1562 InsertText(endBodyLoc, buf.c_str(), buf.size());
1563 } else {
1564 /* Need to treat single statements specially. For example:
1565 *
1566 * for (A *a in b) if (stuff()) break;
1567 * for (A *a in b) xxxyy;
1568 *
1569 * The following code simply scans ahead to the semi to find the actual end.
1570 */
1571 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1572 const char *semiBuf = strchr(stmtBuf, ';');
1573 assert(semiBuf && "Can't find ';'");
1574 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1575 InsertText(endBodyLoc, buf.c_str(), buf.size());
1576 }
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001577 Stmts.pop_back();
1578 ObjCBcLabelNo.pop_back();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001579 return 0;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001580}
1581
Mike Stump11289f42009-09-09 15:08:12 +00001582/// RewriteObjCSynchronizedStmt -
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001583/// This routine rewrites @synchronized(expr) stmt;
1584/// into:
1585/// objc_sync_enter(expr);
1586/// @try stmt @finally { objc_sync_exit(expr); }
1587///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001588Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001589 // Get the start location and compute the semi location.
1590 SourceLocation startLoc = S->getLocStart();
1591 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001592
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001593 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump11289f42009-09-09 15:08:12 +00001594
1595 std::string buf;
Steve Naroffb2fc0522008-08-21 13:03:03 +00001596 buf = "objc_sync_enter((id)";
1597 const char *lparenBuf = startBuf;
1598 while (*lparenBuf != '(') lparenBuf++;
1599 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001600 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1601 // the sync expression is typically a message expression that's already
Steve Naroffad7013b2008-08-19 13:04:19 +00001602 // been rewritten! (which implies the SourceLocation's are invalid).
1603 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001604 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffad7013b2008-08-19 13:04:19 +00001605 while (*endBuf != ')') endBuf--;
1606 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001607 buf = ");\n";
1608 // declare a new scope with two variables, _stack and _rethrow.
1609 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1610 buf += "int buf[18/*32-bit i386*/];\n";
1611 buf += "char *pointers[4];} _stack;\n";
1612 buf += "id volatile _rethrow = 0;\n";
1613 buf += "objc_exception_try_enter(&_stack);\n";
1614 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001615 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001616 startLoc = S->getSynchBody()->getLocEnd();
1617 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001618
Steve Naroffad7013b2008-08-19 13:04:19 +00001619 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001620 SourceLocation lastCurlyLoc = startLoc;
1621 buf = "}\nelse {\n";
1622 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroffd9803712009-04-29 16:37:50 +00001623 buf += "}\n";
1624 buf += "{ /* implicit finally clause */\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001625 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffec60b432009-12-05 21:43:12 +00001626
1627 std::string syncBuf;
1628 syncBuf += " objc_sync_exit(";
John McCall97513962010-01-15 18:39:57 +00001629 Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1630 CastExpr::CK_Unknown,
1631 S->getSynchExpr());
Ted Kremenek2d470fc2008-09-13 05:16:45 +00001632 std::string syncExprBufS;
1633 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00001634 syncExpr->printPretty(syncExprBuf, *Context, 0,
1635 PrintingPolicy(LangOpts));
Steve Naroffec60b432009-12-05 21:43:12 +00001636 syncBuf += syncExprBuf.str();
1637 syncBuf += ");";
1638
1639 buf += syncBuf;
1640 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001641 buf += "}\n";
1642 buf += "}";
Mike Stump11289f42009-09-09 15:08:12 +00001643
Chris Lattner9cc55f52008-01-31 19:51:04 +00001644 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffec60b432009-12-05 21:43:12 +00001645
1646 bool hasReturns = false;
1647 HasReturnStmts(S->getSynchBody(), hasReturns);
1648 if (hasReturns)
1649 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1650
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001651 return 0;
1652}
1653
Steve Naroffec60b432009-12-05 21:43:12 +00001654void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1655{
Steve Naroff6d6da252008-12-05 17:03:39 +00001656 // Perform a bottom up traversal of all children.
1657 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1658 CI != E; ++CI)
1659 if (*CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001660 WarnAboutReturnGotoStmts(*CI);
Steve Naroff6d6da252008-12-05 17:03:39 +00001661
Steve Naroffec60b432009-12-05 21:43:12 +00001662 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump11289f42009-09-09 15:08:12 +00001663 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff6d6da252008-12-05 17:03:39 +00001664 TryFinallyContainsReturnDiag);
1665 }
1666 return;
1667}
1668
Steve Naroffec60b432009-12-05 21:43:12 +00001669void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1670{
1671 // Perform a bottom up traversal of all children.
1672 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1673 CI != E; ++CI)
1674 if (*CI)
1675 HasReturnStmts(*CI, hasReturns);
1676
1677 if (isa<ReturnStmt>(S))
1678 hasReturns = true;
1679 return;
1680}
1681
1682void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1683 // Perform a bottom up traversal of all children.
1684 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1685 CI != E; ++CI)
1686 if (*CI) {
1687 RewriteTryReturnStmts(*CI);
1688 }
1689 if (isa<ReturnStmt>(S)) {
1690 SourceLocation startLoc = S->getLocStart();
1691 const char *startBuf = SM->getCharacterData(startLoc);
1692
1693 const char *semiBuf = strchr(startBuf, ';');
1694 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1695 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1696
1697 std::string buf;
1698 buf = "{ objc_exception_try_exit(&_stack); return";
1699
1700 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1701 InsertText(onePastSemiLoc, "}", 1);
1702 }
1703 return;
1704}
1705
1706void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1707 // Perform a bottom up traversal of all children.
1708 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1709 CI != E; ++CI)
1710 if (*CI) {
1711 RewriteSyncReturnStmts(*CI, syncExitBuf);
1712 }
1713 if (isa<ReturnStmt>(S)) {
1714 SourceLocation startLoc = S->getLocStart();
1715 const char *startBuf = SM->getCharacterData(startLoc);
1716
1717 const char *semiBuf = strchr(startBuf, ';');
1718 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1719 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1720
1721 std::string buf;
1722 buf = "{ objc_exception_try_exit(&_stack);";
1723 buf += syncExitBuf;
1724 buf += " return";
1725
1726 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1727 InsertText(onePastSemiLoc, "}", 1);
1728 }
1729 return;
1730}
1731
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001732Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001733 // Get the start location and compute the semi location.
1734 SourceLocation startLoc = S->getLocStart();
1735 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001736
Steve Naroffbf478ec2007-11-07 04:08:17 +00001737 assert((*startBuf == '@') && "bogus @try location");
1738
1739 std::string buf;
1740 // declare a new scope with two variables, _stack and _rethrow.
1741 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1742 buf += "int buf[18/*32-bit i386*/];\n";
1743 buf += "char *pointers[4];} _stack;\n";
1744 buf += "id volatile _rethrow = 0;\n";
1745 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff16018582007-11-07 18:43:40 +00001746 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffbf478ec2007-11-07 04:08:17 +00001747
Chris Lattner9cc55f52008-01-31 19:51:04 +00001748 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001749
Steve Naroffbf478ec2007-11-07 04:08:17 +00001750 startLoc = S->getTryBody()->getLocEnd();
1751 startBuf = SM->getCharacterData(startLoc);
1752
1753 assert((*startBuf == '}') && "bogus @try block");
Mike Stump11289f42009-09-09 15:08:12 +00001754
Steve Naroffbf478ec2007-11-07 04:08:17 +00001755 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffce2dca12008-07-16 15:31:30 +00001756 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1757 if (catchList) {
1758 startLoc = startLoc.getFileLocWithOffset(1);
1759 buf = " /* @catch begin */ else {\n";
1760 buf += " id _caught = objc_exception_extract(&_stack);\n";
1761 buf += " objc_exception_try_enter (&_stack);\n";
1762 buf += " if (_setjmp(_stack.buf))\n";
1763 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1764 buf += " else { /* @catch continue */";
Mike Stump11289f42009-09-09 15:08:12 +00001765
Steve Naroffce2dca12008-07-16 15:31:30 +00001766 InsertText(startLoc, buf.c_str(), buf.size());
Steve Narofffac18fe2008-09-09 19:59:12 +00001767 } else { /* no catch list */
1768 buf = "}\nelse {\n";
1769 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1770 buf += "}";
1771 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffce2dca12008-07-16 15:31:30 +00001772 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001773 bool sawIdTypedCatch = false;
1774 Stmt *lastCatchBody = 0;
Steve Naroffbf478ec2007-11-07 04:08:17 +00001775 while (catchList) {
Steve Naroff371b8fb2009-03-03 19:52:17 +00001776 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001777
Mike Stump11289f42009-09-09 15:08:12 +00001778 if (catchList == S->getCatchStmts())
Steve Naroffbf478ec2007-11-07 04:08:17 +00001779 buf = "if ("; // we are generating code for the first catch clause
1780 else
1781 buf = "else if (";
1782 startLoc = catchList->getLocStart();
1783 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001784
Steve Naroffbf478ec2007-11-07 04:08:17 +00001785 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump11289f42009-09-09 15:08:12 +00001786
Steve Naroffbf478ec2007-11-07 04:08:17 +00001787 const char *lParenLoc = strchr(startBuf, '(');
1788
Steve Naroffe6b7ffd2008-02-01 22:08:12 +00001789 if (catchList->hasEllipsis()) {
Steve Naroffedb5bc62008-02-01 20:02:07 +00001790 // Now rewrite the body...
1791 lastCatchBody = catchList->getCatchBody();
Steve Naroffedb5bc62008-02-01 20:02:07 +00001792 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1793 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001794 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1795 "bogus @catch paren location");
Steve Naroffedb5bc62008-02-01 20:02:07 +00001796 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001797
Steve Naroffedb5bc62008-02-01 20:02:07 +00001798 buf += "1) { id _tmp = _caught;";
Daniel Dunbardec484a2009-08-19 19:10:30 +00001799 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff371b8fb2009-03-03 19:52:17 +00001800 } else if (catchDecl) {
1801 QualType t = catchDecl->getType();
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001802 if (t == Context->getObjCIdType()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001803 buf += "1) { ";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001804 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001805 sawIdTypedCatch = true;
Fariborz Jahanian59516092010-01-12 01:22:23 +00001806 } else if (t->isObjCObjectPointerType()) {
1807 QualType InterfaceTy = t->getPointeeType();
1808 const ObjCInterfaceType *cls = // Should be a pointer to a class.
1809 InterfaceTy->getAs<ObjCInterfaceType>();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001810 if (cls) {
Steve Naroff16018582007-11-07 18:43:40 +00001811 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001812 buf += cls->getDecl()->getNameAsString();
Steve Naroff16018582007-11-07 18:43:40 +00001813 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001814 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001815 }
1816 }
1817 // Now rewrite the body...
1818 lastCatchBody = catchList->getCatchBody();
1819 SourceLocation rParenLoc = catchList->getRParenLoc();
1820 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1821 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1822 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1823 assert((*rParenBuf == ')') && "bogus @catch paren location");
1824 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001825
Steve Naroffbf478ec2007-11-07 04:08:17 +00001826 buf = " = _caught;";
Mike Stump11289f42009-09-09 15:08:12 +00001827 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroffbf478ec2007-11-07 04:08:17 +00001828 // declares the @catch parameter).
Chris Lattner9cc55f52008-01-31 19:51:04 +00001829 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff371b8fb2009-03-03 19:52:17 +00001830 } else {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001831 assert(false && "@catch rewrite bug");
Steve Naroffa733c7f2007-11-07 15:32:26 +00001832 }
Steve Naroffedb5bc62008-02-01 20:02:07 +00001833 // make sure all the catch bodies get rewritten!
Steve Naroffbf478ec2007-11-07 04:08:17 +00001834 catchList = catchList->getNextCatchStmt();
1835 }
1836 // Complete the catch list...
1837 if (lastCatchBody) {
1838 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001839 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1840 "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001841
Steve Naroff4adbe312008-09-11 15:29:03 +00001842 // Insert the last (implicit) else clause *before* the right curly brace.
1843 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1844 buf = "} /* last catch end */\n";
1845 buf += "else {\n";
1846 buf += " _rethrow = _caught;\n";
1847 buf += " objc_exception_try_exit(&_stack);\n";
1848 buf += "} } /* @catch end */\n";
1849 if (!S->getFinallyStmt())
1850 buf += "}\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001851 InsertText(bodyLoc, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001852
Steve Naroffbf478ec2007-11-07 04:08:17 +00001853 // Set lastCurlyLoc
1854 lastCurlyLoc = lastCatchBody->getLocEnd();
1855 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001856 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001857 startLoc = finalStmt->getLocStart();
1858 startBuf = SM->getCharacterData(startLoc);
1859 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump11289f42009-09-09 15:08:12 +00001860
Steve Naroffbf478ec2007-11-07 04:08:17 +00001861 buf = "/* @finally */";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001862 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001863
Steve Naroffbf478ec2007-11-07 04:08:17 +00001864 Stmt *body = finalStmt->getFinallyBody();
1865 SourceLocation startLoc = body->getLocStart();
1866 SourceLocation endLoc = body->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001867 assert(*SM->getCharacterData(startLoc) == '{' &&
1868 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001869 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001870 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001871
Steve Naroffbf478ec2007-11-07 04:08:17 +00001872 startLoc = startLoc.getFileLocWithOffset(1);
1873 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001874 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001875 endLoc = endLoc.getFileLocWithOffset(-1);
1876 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001877 InsertText(endLoc, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001878
Steve Naroffbf478ec2007-11-07 04:08:17 +00001879 // Set lastCurlyLoc
1880 lastCurlyLoc = body->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00001881
Steve Naroff6d6da252008-12-05 17:03:39 +00001882 // Now check for any return/continue/go statements within the @try.
Steve Naroffec60b432009-12-05 21:43:12 +00001883 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff4adbe312008-09-11 15:29:03 +00001884 } else { /* no finally clause - make sure we synthesize an implicit one */
1885 buf = "{ /* implicit finally clause */\n";
1886 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1887 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1888 buf += "}";
1889 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffec60b432009-12-05 21:43:12 +00001890
1891 // Now check for any return/continue/go statements within the @try.
1892 // The implicit finally clause won't called if the @try contains any
1893 // jump statements.
1894 bool hasReturns = false;
1895 HasReturnStmts(S->getTryBody(), hasReturns);
1896 if (hasReturns)
1897 RewriteTryReturnStmts(S->getTryBody());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001898 }
1899 // Now emit the final closing curly brace...
1900 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1901 buf = " } /* @try scope end */\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001902 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001903 return 0;
1904}
1905
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001906Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001907 return 0;
1908}
1909
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001910Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001911 return 0;
1912}
1913
Mike Stump11289f42009-09-09 15:08:12 +00001914// This can't be done with ReplaceStmt(S, ThrowExpr), since
1915// the throw expression is typically a message expression that's already
Steve Naroffa733c7f2007-11-07 15:32:26 +00001916// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001917Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroffa733c7f2007-11-07 15:32:26 +00001918 // Get the start location and compute the semi location.
1919 SourceLocation startLoc = S->getLocStart();
1920 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001921
Steve Naroffa733c7f2007-11-07 15:32:26 +00001922 assert((*startBuf == '@') && "bogus @throw location");
1923
1924 std::string buf;
1925 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffc7d2df22008-01-19 00:42:38 +00001926 if (S->getThrowExpr())
1927 buf = "objc_exception_throw(";
1928 else // add an implicit argument
1929 buf = "objc_exception_throw(_caught";
Mike Stump11289f42009-09-09 15:08:12 +00001930
Steve Naroff29788342008-07-25 15:41:30 +00001931 // handle "@ throw" correctly.
1932 const char *wBuf = strchr(startBuf, 'w');
1933 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1934 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001935
Steve Naroffa733c7f2007-11-07 15:32:26 +00001936 const char *semiBuf = strchr(startBuf, ';');
1937 assert((*semiBuf == ';') && "@throw: can't find ';'");
1938 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1939 buf = ");";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001940 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroffa733c7f2007-11-07 15:32:26 +00001941 return 0;
1942}
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001943
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001944Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerc6d91c02007-10-17 22:35:30 +00001945 // Create a new string expression.
1946 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlssond8499822007-10-29 05:01:08 +00001947 std::string StrEncoding;
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00001948 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00001949 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
1950 StrEncoding.length(), false,StrType,
1951 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00001952 ReplaceStmt(Exp, Replacement);
Mike Stump11289f42009-09-09 15:08:12 +00001953
Chris Lattner4431a1b2007-11-30 22:53:43 +00001954 // Replace this subexpr in the parent.
Steve Naroff22216db2008-12-04 23:50:32 +00001955 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattner69534692007-10-24 16:57:36 +00001956 return Replacement;
Chris Lattnera7c19fe2007-10-16 22:36:42 +00001957}
1958
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001959Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff2654e182008-12-22 22:16:07 +00001960 if (!SelGetUidFunctionDecl)
1961 SynthSelGetUidFunctionDecl();
Steve Naroffe4f9b232007-11-05 14:50:49 +00001962 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1963 // Create a call to sel_registerName("selName").
1964 llvm::SmallVector<Expr*, 8> SelExprs;
1965 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00001966 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00001967 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00001968 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00001969 false, argType, SourceLocation()));
Steve Naroffe4f9b232007-11-05 14:50:49 +00001970 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1971 &SelExprs[0], SelExprs.size());
Chris Lattner2e0d2602008-01-31 19:37:57 +00001972 ReplaceStmt(Exp, SelExp);
Steve Naroff22216db2008-12-04 23:50:32 +00001973 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffe4f9b232007-11-05 14:50:49 +00001974 return SelExp;
1975}
1976
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001977CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff574440f2007-10-24 22:48:43 +00001978 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001979 // Get the type, we will need to reference it in a couple spots.
Steve Naroff574440f2007-10-24 22:48:43 +00001980 QualType msgSendType = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001981
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001982 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek5a201952009-02-07 01:47:29 +00001983 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001984
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001985 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattner3c799d72007-10-24 17:06:59 +00001986 QualType pToFunc = Context->getPointerType(msgSendType);
Mike Stump11289f42009-09-09 15:08:12 +00001987 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc,
Anders Carlssona2615922009-07-31 00:48:10 +00001988 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00001989 DRE,
Douglas Gregora11693b2008-11-12 17:17:38 +00001990 /*isLvalue=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001991
John McCall9dd450b2009-09-21 23:43:11 +00001992 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00001993
Ted Kremenekd7b4f402009-02-09 20:51:47 +00001994 return new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
1995 SourceLocation());
Steve Naroff574440f2007-10-24 22:48:43 +00001996}
1997
Steve Naroff50d42052007-11-01 13:24:47 +00001998static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1999 const char *&startRef, const char *&endRef) {
2000 while (startBuf < endBuf) {
2001 if (*startBuf == '<')
2002 startRef = startBuf; // mark the start.
2003 if (*startBuf == '>') {
Steve Naroff1b232132007-11-09 12:50:28 +00002004 if (startRef && *startRef == '<') {
2005 endRef = startBuf; // mark the end.
2006 return true;
2007 }
2008 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002009 }
2010 startBuf++;
2011 }
2012 return false;
2013}
2014
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002015static void scanToNextArgument(const char *&argRef) {
2016 int angle = 0;
2017 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2018 if (*argRef == '<')
2019 angle++;
2020 else if (*argRef == '>')
2021 angle--;
2022 argRef++;
2023 }
2024 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2025}
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002026
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002027bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian80c54b02010-02-03 21:29:28 +00002028 if (T->isObjCQualifiedIdType())
2029 return true;
Fariborz Jahanian06769f92010-02-02 18:35:07 +00002030 if (const PointerType *PT = T->getAs<PointerType>()) {
2031 if (PT->getPointeeType()->isObjCQualifiedIdType())
2032 return true;
2033 }
2034 if (T->isObjCObjectPointerType()) {
2035 T = T->getPointeeType();
2036 return T->isObjCQualifiedInterfaceType();
2037 }
2038 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002039}
2040
Steve Naroff873bd842008-07-29 18:15:38 +00002041void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2042 QualType Type = E->getType();
2043 if (needToScanForQualifiers(Type)) {
Steve Naroffdbfc6932008-11-19 21:15:47 +00002044 SourceLocation Loc, EndLoc;
Mike Stump11289f42009-09-09 15:08:12 +00002045
Steve Naroffdbfc6932008-11-19 21:15:47 +00002046 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2047 Loc = ECE->getLParenLoc();
2048 EndLoc = ECE->getRParenLoc();
2049 } else {
2050 Loc = E->getLocStart();
2051 EndLoc = E->getLocEnd();
2052 }
2053 // This will defend against trying to rewrite synthesized expressions.
2054 if (Loc.isInvalid() || EndLoc.isInvalid())
2055 return;
2056
Steve Naroff873bd842008-07-29 18:15:38 +00002057 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffdbfc6932008-11-19 21:15:47 +00002058 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff873bd842008-07-29 18:15:38 +00002059 const char *startRef = 0, *endRef = 0;
2060 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2061 // Get the locations of the startRef, endRef.
2062 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2063 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2064 // Comment out the protocol references.
2065 InsertText(LessLoc, "/*", 2);
2066 InsertText(GreaterLoc, "*/", 2);
2067 }
2068 }
2069}
2070
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002071void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002072 SourceLocation Loc;
2073 QualType Type;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002074 const FunctionProtoType *proto = 0;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002075 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2076 Loc = VD->getLocation();
2077 Type = VD->getType();
2078 }
2079 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2080 Loc = FD->getLocation();
2081 // Check for ObjC 'id' and class types that have been adorned with protocol
2082 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall9dd450b2009-09-21 23:43:11 +00002083 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002084 assert(funcType && "missing function type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002085 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002086 if (!proto)
2087 return;
2088 Type = proto->getResultType();
2089 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00002090 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2091 Loc = FD->getLocation();
2092 Type = FD->getType();
2093 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002094 else
2095 return;
Mike Stump11289f42009-09-09 15:08:12 +00002096
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002097 if (needToScanForQualifiers(Type)) {
Steve Naroff50d42052007-11-01 13:24:47 +00002098 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002099
Steve Naroff50d42052007-11-01 13:24:47 +00002100 const char *endBuf = SM->getCharacterData(Loc);
2101 const char *startBuf = endBuf;
Steve Naroff930e0992008-05-31 05:02:17 +00002102 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroff50d42052007-11-01 13:24:47 +00002103 startBuf--; // scan backward (from the decl location) for return type.
2104 const char *startRef = 0, *endRef = 0;
2105 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2106 // Get the locations of the startRef, endRef.
2107 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2108 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2109 // Comment out the protocol references.
Chris Lattner1780a852008-01-31 19:42:41 +00002110 InsertText(LessLoc, "/*", 2);
2111 InsertText(GreaterLoc, "*/", 2);
Steve Naroff37e011c2007-10-31 04:38:33 +00002112 }
2113 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002114 if (!proto)
2115 return; // most likely, was a variable
Steve Naroff50d42052007-11-01 13:24:47 +00002116 // Now check arguments.
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002117 const char *startBuf = SM->getCharacterData(Loc);
2118 const char *startFuncBuf = startBuf;
Steve Naroff50d42052007-11-01 13:24:47 +00002119 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2120 if (needToScanForQualifiers(proto->getArgType(i))) {
2121 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002122
Steve Naroff50d42052007-11-01 13:24:47 +00002123 const char *endBuf = startBuf;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002124 // scan forward (from the decl location) for argument types.
2125 scanToNextArgument(endBuf);
Steve Naroff50d42052007-11-01 13:24:47 +00002126 const char *startRef = 0, *endRef = 0;
2127 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2128 // Get the locations of the startRef, endRef.
Mike Stump11289f42009-09-09 15:08:12 +00002129 SourceLocation LessLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002130 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump11289f42009-09-09 15:08:12 +00002131 SourceLocation GreaterLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002132 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002133 // Comment out the protocol references.
Chris Lattner1780a852008-01-31 19:42:41 +00002134 InsertText(LessLoc, "/*", 2);
2135 InsertText(GreaterLoc, "*/", 2);
Steve Naroff50d42052007-11-01 13:24:47 +00002136 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002137 startBuf = ++endBuf;
2138 }
2139 else {
Steve Naroffc884aa82008-08-06 15:58:23 +00002140 // If the function name is derived from a macro expansion, then the
2141 // argument buffer will not follow the name. Need to speak with Chris.
2142 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002143 startBuf++; // scan forward (from the decl location) for argument types.
2144 startBuf++;
2145 }
Steve Naroff50d42052007-11-01 13:24:47 +00002146 }
Steve Naroff37e011c2007-10-31 04:38:33 +00002147}
2148
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002149void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2150 QualType QT = ND->getType();
2151 const Type* TypePtr = QT->getAs<Type>();
2152 if (!isa<TypeOfExprType>(TypePtr))
2153 return;
2154 while (isa<TypeOfExprType>(TypePtr)) {
2155 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2156 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2157 TypePtr = QT->getAs<Type>();
2158 }
2159 // FIXME. This will not work for multiple declarators; as in:
2160 // __typeof__(a) b,c,d;
2161 std::string TypeAsString(QT.getAsString());
2162 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2163 const char *startBuf = SM->getCharacterData(DeclLoc);
2164 if (ND->getInit()) {
2165 std::string Name(ND->getNameAsString());
2166 TypeAsString += " " + Name + " = ";
2167 Expr *E = ND->getInit();
2168 SourceLocation startLoc;
2169 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2170 startLoc = ECE->getLParenLoc();
2171 else
2172 startLoc = E->getLocStart();
2173 startLoc = SM->getInstantiationLoc(startLoc);
2174 const char *endBuf = SM->getCharacterData(startLoc);
2175 ReplaceText(DeclLoc, endBuf-startBuf-1,
2176 TypeAsString.c_str(), TypeAsString.size());
2177 }
2178 else {
2179 SourceLocation X = ND->getLocEnd();
2180 X = SM->getInstantiationLoc(X);
2181 const char *endBuf = SM->getCharacterData(X);
2182 ReplaceText(DeclLoc, endBuf-startBuf-1,
2183 TypeAsString.c_str(), TypeAsString.size());
2184 }
2185}
2186
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002187// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002188void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002189 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2190 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002191 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002192 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002193 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002194 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002195 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002196 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002197 SelGetUidIdent, getFuncType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002198 FunctionDecl::Extern, false);
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002199}
2200
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002201void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002202 // declared in <objc/objc.h>
Douglas Gregor1e21c192009-01-09 01:47:02 +00002203 if (FD->getIdentifier() &&
2204 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002205 SelGetUidFunctionDecl = FD;
Steve Naroff37e011c2007-10-31 04:38:33 +00002206 return;
2207 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002208 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002209}
2210
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002211void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2212 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2213 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2214 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2215 if (!proto)
2216 return;
2217 QualType Type = proto->getResultType();
2218 std::string FdStr = Type.getAsString();
2219 FdStr += " ";
2220 FdStr += FD->getNameAsCString();
2221 FdStr += "(";
2222 unsigned numArgs = proto->getNumArgs();
2223 for (unsigned i = 0; i < numArgs; i++) {
2224 QualType ArgType = proto->getArgType(i);
2225 FdStr += ArgType.getAsString();
2226
2227 if (i+1 < numArgs)
2228 FdStr += ", ";
2229 }
2230 FdStr += ");\n";
2231 InsertText(FunLocStart, FdStr.c_str(), FdStr.size());
2232 CurFunctionDeclToDeclareForBlock = 0;
2233}
2234
Steve Naroff17978c42008-03-11 17:37:02 +00002235// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002236void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroff17978c42008-03-11 17:37:02 +00002237 if (SuperContructorFunctionDecl)
2238 return;
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002239 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroff17978c42008-03-11 17:37:02 +00002240 llvm::SmallVector<QualType, 16> ArgTys;
2241 QualType argT = Context->getObjCIdType();
2242 assert(!argT.isNull() && "Can't find 'id' type");
2243 ArgTys.push_back(argT);
2244 ArgTys.push_back(argT);
2245 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2246 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002247 false, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002248 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002249 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002250 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002251 FunctionDecl::Extern, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002252}
2253
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002254// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002255void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002256 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2257 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002258 QualType argT = Context->getObjCIdType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002259 assert(!argT.isNull() && "Can't find 'id' type");
2260 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002261 argT = Context->getObjCSelType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002262 assert(!argT.isNull() && "Can't find 'SEL' type");
2263 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002264 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002265 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002266 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002267 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002268 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002269 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002270 FunctionDecl::Extern, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002271}
2272
Steve Naroff7fa2f042007-11-15 10:28:18 +00002273// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002274void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002275 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2276 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002277 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002278 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002279 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002280 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2281 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2282 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002283 argT = Context->getObjCSelType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002284 assert(!argT.isNull() && "Can't find 'SEL' type");
2285 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002286 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff7fa2f042007-11-15 10:28:18 +00002287 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002288 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002289 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002290 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002291 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002292 FunctionDecl::Extern, false);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002293}
2294
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002295// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002296void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002297 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2298 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002299 QualType argT = Context->getObjCIdType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002300 assert(!argT.isNull() && "Can't find 'id' type");
2301 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002302 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002303 assert(!argT.isNull() && "Can't find 'SEL' type");
2304 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002305 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002306 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002307 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002308 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002309 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002310 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002311 FunctionDecl::Extern, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002312}
2313
Mike Stump11289f42009-09-09 15:08:12 +00002314// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002315// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002316void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump11289f42009-09-09 15:08:12 +00002317 IdentifierInfo *msgSendIdent =
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002318 &Context->Idents.get("objc_msgSendSuper_stret");
2319 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002320 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002321 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002322 &Context->Idents.get("objc_super"));
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002323 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2324 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2325 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002326 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002327 assert(!argT.isNull() && "Can't find 'SEL' type");
2328 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002329 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002330 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002331 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002332 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002333 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002334 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002335 FunctionDecl::Extern, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002336}
2337
Steve Naroff2e4e3852008-05-08 22:02:18 +00002338// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002339void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002340 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2341 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002342 QualType argT = Context->getObjCIdType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002343 assert(!argT.isNull() && "Can't find 'id' type");
2344 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002345 argT = Context->getObjCSelType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002346 assert(!argT.isNull() && "Can't find 'SEL' type");
2347 ArgTys.push_back(argT);
Steve Naroff2e4e3852008-05-08 22:02:18 +00002348 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002349 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002350 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002351 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002352 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002353 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002354 FunctionDecl::Extern, false);
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002355}
2356
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002357// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002358void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002359 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2360 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002361 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002362 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002363 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002364 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002365 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002366 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002367 getClassIdent, getClassType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002368 FunctionDecl::Extern, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002369}
2370
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002371// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002372void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002373 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2374 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002375 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002376 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002377 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002378 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002379 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002380 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002381 getClassIdent, getClassType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002382 FunctionDecl::Extern, false);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002383}
2384
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002385Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffce8e8862008-03-15 00:55:56 +00002386 QualType strType = getConstantStringStructType();
2387
2388 std::string S = "__NSConstantStringImpl_";
Steve Naroffa6141f02008-05-31 03:35:42 +00002389
2390 std::string tmpName = InFileName;
2391 unsigned i;
2392 for (i=0; i < tmpName.length(); i++) {
2393 char c = tmpName.at(i);
2394 // replace any non alphanumeric characters with '_'.
2395 if (!isalpha(c) && (c < '0' || c > '9'))
2396 tmpName[i] = '_';
2397 }
2398 S += tmpName;
2399 S += "_";
Steve Naroffce8e8862008-03-15 00:55:56 +00002400 S += utostr(NumObjCStringLiterals++);
2401
Steve Naroff00a31762008-03-27 22:29:16 +00002402 Preamble += "static __NSConstantStringImpl " + S;
2403 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2404 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffce8e8862008-03-15 00:55:56 +00002405 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek2d470fc2008-09-13 05:16:45 +00002406 std::string prettyBufS;
2407 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00002408 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2409 PrintingPolicy(LangOpts));
Steve Naroff00a31762008-03-27 22:29:16 +00002410 Preamble += prettyBuf.str();
2411 Preamble += ",";
Steve Naroff94ed6dc2009-12-06 01:48:44 +00002412 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002413
2414 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2415 &Context->Idents.get(S.c_str()), strType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002416 VarDecl::Static);
Ted Kremenek5a201952009-02-07 01:47:29 +00002417 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2418 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002419 Context->getPointerType(DRE->getType()),
Steve Naroffce8e8862008-03-15 00:55:56 +00002420 SourceLocation());
Steve Naroff265a6b92007-11-08 14:30:50 +00002421 // cast to NSConstantString *
John McCall97513962010-01-15 18:39:57 +00002422 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2423 CastExpr::CK_Unknown, Unop);
Chris Lattner2e0d2602008-01-31 19:37:57 +00002424 ReplaceStmt(Exp, cast);
Steve Naroff22216db2008-12-04 23:50:32 +00002425 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff265a6b92007-11-08 14:30:50 +00002426 return cast;
Steve Naroffa397efd2007-11-03 11:27:19 +00002427}
2428
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002429ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002430 // check if we are sending a message to 'super'
Douglas Gregorffca3a22009-01-09 17:18:27 +00002431 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002432
Douglas Gregor8ea1f532008-11-04 14:56:14 +00002433 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
Mike Stump11289f42009-09-09 15:08:12 +00002434 const ObjCObjectPointerType *OPT =
John McCall9dd450b2009-09-21 23:43:11 +00002435 Super->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00002436 assert(OPT);
2437 const ObjCInterfaceType *IT = OPT->getInterfaceType();
Chris Lattnera9b3cae2008-06-21 18:04:54 +00002438 return IT->getDecl();
2439 }
2440 return 0;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002441}
2442
2443// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002444QualType RewriteObjC::getSuperStructType() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002445 if (!SuperStructDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002446 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002447 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002448 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002449 QualType FieldTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002450
Steve Naroff7fa2f042007-11-15 10:28:18 +00002451 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002452 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002453 // struct objc_class *super;
Mike Stump11289f42009-09-09 15:08:12 +00002454 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor91f84212008-12-11 16:49:14 +00002455
Steve Naroff7fa2f042007-11-15 10:28:18 +00002456 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002457 for (unsigned i = 0; i < 2; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002458 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2459 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002460 FieldTypes[i], 0,
2461 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002462 /*Mutable=*/false));
Douglas Gregor91f84212008-12-11 16:49:14 +00002463 }
Mike Stump11289f42009-09-09 15:08:12 +00002464
Douglas Gregord5058122010-02-11 01:19:42 +00002465 SuperStructDecl->completeDefinition();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002466 }
2467 return Context->getTagDeclType(SuperStructDecl);
2468}
2469
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002470QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffce8e8862008-03-15 00:55:56 +00002471 if (!ConstantStringDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002472 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002473 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002474 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffce8e8862008-03-15 00:55:56 +00002475 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002476
Steve Naroffce8e8862008-03-15 00:55:56 +00002477 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002478 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffce8e8862008-03-15 00:55:56 +00002479 // int flags;
Mike Stump11289f42009-09-09 15:08:12 +00002480 FieldTypes[1] = Context->IntTy;
Steve Naroffce8e8862008-03-15 00:55:56 +00002481 // char *str;
Mike Stump11289f42009-09-09 15:08:12 +00002482 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffce8e8862008-03-15 00:55:56 +00002483 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002484 FieldTypes[3] = Context->LongTy;
Douglas Gregor91f84212008-12-11 16:49:14 +00002485
Steve Naroffce8e8862008-03-15 00:55:56 +00002486 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002487 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002488 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2489 ConstantStringDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002490 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002491 FieldTypes[i], 0,
Douglas Gregor91f84212008-12-11 16:49:14 +00002492 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002493 /*Mutable=*/true));
Douglas Gregor91f84212008-12-11 16:49:14 +00002494 }
2495
Douglas Gregord5058122010-02-11 01:19:42 +00002496 ConstantStringDecl->completeDefinition();
Steve Naroffce8e8862008-03-15 00:55:56 +00002497 }
2498 return Context->getTagDeclType(ConstantStringDecl);
2499}
2500
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002501Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002502 if (!SelGetUidFunctionDecl)
2503 SynthSelGetUidFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002504 if (!MsgSendFunctionDecl)
2505 SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002506 if (!MsgSendSuperFunctionDecl)
2507 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002508 if (!MsgSendStretFunctionDecl)
2509 SynthMsgSendStretFunctionDecl();
2510 if (!MsgSendSuperStretFunctionDecl)
2511 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002512 if (!MsgSendFpretFunctionDecl)
2513 SynthMsgSendFpretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002514 if (!GetClassFunctionDecl)
2515 SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002516 if (!GetMetaClassFunctionDecl)
2517 SynthGetMetaClassFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002518
Steve Naroff7fa2f042007-11-15 10:28:18 +00002519 // default to objc_msgSend().
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002520 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2521 // May need to use objc_msgSend_stret() as well.
2522 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroffd9803712009-04-29 16:37:50 +00002523 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2524 QualType resultType = mDecl->getResultType();
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002525 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002526 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002527 else if (resultType->isRealFloatingType())
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002528 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002529 }
Mike Stump11289f42009-09-09 15:08:12 +00002530
Steve Naroff574440f2007-10-24 22:48:43 +00002531 // Synthesize a call to objc_msgSend().
2532 llvm::SmallVector<Expr*, 8> MsgExprs;
2533 IdentifierInfo *clsName = Exp->getClassName();
Mike Stump11289f42009-09-09 15:08:12 +00002534
Steve Naroff574440f2007-10-24 22:48:43 +00002535 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2536 if (clsName) { // class message.
Steve Naroff6c79f972008-07-24 19:44:33 +00002537 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2538 // the 'super' idiom within a class method.
Daniel Dunbar07d07852009-10-18 21:17:35 +00002539 if (clsName->getName() == "super") {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002540 MsgSendFlavor = MsgSendSuperFunctionDecl;
2541 if (MsgSendStretFlavor)
2542 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2543 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002544
2545 ObjCInterfaceDecl *SuperDecl =
Steve Naroff677ab3a2008-10-27 17:20:55 +00002546 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002547
2548 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002549
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002550 // set the receiver to self, the first argument to all methods.
Steve Naroffd9803712009-04-29 16:37:50 +00002551 InitExprs.push_back(
John McCall97513962010-01-15 18:39:57 +00002552 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2553 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002554 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroffd9803712009-04-29 16:37:50 +00002555 Context->getObjCIdType(),
John McCall97513962010-01-15 18:39:57 +00002556 SourceLocation()))
2557 ); // set the 'receiver'.
Steve Naroffd9803712009-04-29 16:37:50 +00002558
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002559 llvm::SmallVector<Expr*, 8> ClsExprs;
2560 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002561 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002562 SuperDecl->getIdentifier()->getNameStart(),
2563 SuperDecl->getIdentifier()->getLength(),
2564 false, argType, SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002565 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002566 &ClsExprs[0],
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002567 ClsExprs.size());
2568 // To turn off a warning, type-cast to 'id'
Douglas Gregore200adc2008-10-27 19:41:14 +00002569 InitExprs.push_back( // set 'super class', using objc_getClass().
John McCall97513962010-01-15 18:39:57 +00002570 NoTypeInfoCStyleCastExpr(Context,
2571 Context->getObjCIdType(),
2572 CastExpr::CK_Unknown, Cls));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002573 // struct objc_super
2574 QualType superType = getSuperStructType();
Steve Naroff0b844f02008-03-11 18:14:26 +00002575 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002576
Steve Naroff0b844f02008-03-11 18:14:26 +00002577 if (LangOpts.Microsoft) {
2578 SynthSuperContructorFunctionDecl();
2579 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002580 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff0b844f02008-03-11 18:14:26 +00002581 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002582 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002583 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002584 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002585 // The code for super is a little tricky to prevent collision with
2586 // the structure definition in the header. The rewriter has it's own
2587 // internal definition (__rw_objc_super) that is uses. This is why
2588 // we need the cast below. For example:
2589 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2590 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002591 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002592 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002593 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00002594 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2595 Context->getPointerType(superType),
2596 CastExpr::CK_Unknown, SuperRep);
Mike Stump11289f42009-09-09 15:08:12 +00002597 } else {
Steve Naroff0b844f02008-03-11 18:14:26 +00002598 // (struct objc_super) { <exprs from above> }
Mike Stump11289f42009-09-09 15:08:12 +00002599 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2600 &InitExprs[0], InitExprs.size(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002601 SourceLocation());
John McCalle15bbff2010-01-18 19:35:47 +00002602 TypeSourceInfo *superTInfo
2603 = Context->getTrivialTypeSourceInfo(superType);
John McCall5d7aa7f2010-01-19 22:33:45 +00002604 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2605 superType, ILE, false);
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002606 // struct objc_super *
Ted Kremenek5a201952009-02-07 01:47:29 +00002607 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002608 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002609 SourceLocation());
Steve Naroff0b844f02008-03-11 18:14:26 +00002610 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002611 MsgExprs.push_back(SuperRep);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002612 } else {
2613 llvm::SmallVector<Expr*, 8> ClsExprs;
2614 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002615 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002616 clsName->getNameStart(),
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002617 clsName->getLength(),
2618 false, argType,
2619 SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002620 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002621 &ClsExprs[0],
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002622 ClsExprs.size());
2623 MsgExprs.push_back(Cls);
2624 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002625 } else { // instance message.
2626 Expr *recExpr = Exp->getReceiver();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002627
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002628 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002629 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002630 if (MsgSendStretFlavor)
2631 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002632 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002633
Steve Naroff7fa2f042007-11-15 10:28:18 +00002634 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002635
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002636 InitExprs.push_back(
John McCall97513962010-01-15 18:39:57 +00002637 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2638 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002639 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff97adf602008-07-16 22:35:27 +00002640 Context->getObjCIdType(),
John McCall97513962010-01-15 18:39:57 +00002641 SourceLocation()))
2642 ); // set the 'receiver'.
Mike Stump11289f42009-09-09 15:08:12 +00002643
Steve Naroff7fa2f042007-11-15 10:28:18 +00002644 llvm::SmallVector<Expr*, 8> ClsExprs;
2645 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002646 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002647 SuperDecl->getIdentifier()->getNameStart(),
2648 SuperDecl->getIdentifier()->getLength(),
2649 false, argType, SourceLocation()));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002650 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002651 &ClsExprs[0],
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002652 ClsExprs.size());
Fariborz Jahaniand5db92b2007-12-05 17:29:46 +00002653 // To turn off a warning, type-cast to 'id'
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002654 InitExprs.push_back(
Douglas Gregore200adc2008-10-27 19:41:14 +00002655 // set 'super class', using objc_getClass().
John McCall97513962010-01-15 18:39:57 +00002656 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2657 CastExpr::CK_Unknown, Cls));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002658 // struct objc_super
2659 QualType superType = getSuperStructType();
Steve Naroff17978c42008-03-11 17:37:02 +00002660 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002661
Steve Naroff17978c42008-03-11 17:37:02 +00002662 if (LangOpts.Microsoft) {
2663 SynthSuperContructorFunctionDecl();
2664 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002665 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff17978c42008-03-11 17:37:02 +00002666 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002667 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002668 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002669 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002670 // The code for super is a little tricky to prevent collision with
2671 // the structure definition in the header. The rewriter has it's own
2672 // internal definition (__rw_objc_super) that is uses. This is why
2673 // we need the cast below. For example:
2674 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2675 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002676 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002677 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002678 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00002679 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2680 Context->getPointerType(superType),
2681 CastExpr::CK_Unknown, SuperRep);
Steve Naroff17978c42008-03-11 17:37:02 +00002682 } else {
2683 // (struct objc_super) { <exprs from above> }
Mike Stump11289f42009-09-09 15:08:12 +00002684 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2685 &InitExprs[0], InitExprs.size(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002686 SourceLocation());
John McCalle15bbff2010-01-18 19:35:47 +00002687 TypeSourceInfo *superTInfo
2688 = Context->getTrivialTypeSourceInfo(superType);
John McCall5d7aa7f2010-01-19 22:33:45 +00002689 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2690 superType, ILE, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002691 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002692 MsgExprs.push_back(SuperRep);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002693 } else {
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002694 // Remove all type-casts because it may contain objc-style types; e.g.
2695 // Foo<Proto> *.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002696 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002697 recExpr = CE->getSubExpr();
John McCall97513962010-01-15 18:39:57 +00002698 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2699 CastExpr::CK_Unknown, recExpr);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002700 MsgExprs.push_back(recExpr);
2701 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002702 }
Steve Naroffa397efd2007-11-03 11:27:19 +00002703 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff574440f2007-10-24 22:48:43 +00002704 llvm::SmallVector<Expr*, 8> SelExprs;
2705 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002706 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002707 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002708 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00002709 false, argType, SourceLocation()));
Steve Naroff574440f2007-10-24 22:48:43 +00002710 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2711 &SelExprs[0], SelExprs.size());
2712 MsgExprs.push_back(SelExp);
Mike Stump11289f42009-09-09 15:08:12 +00002713
Steve Naroff574440f2007-10-24 22:48:43 +00002714 // Now push any user supplied arguments.
2715 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroffe7f18192007-11-14 23:54:14 +00002716 Expr *userExpr = Exp->getArg(i);
Steve Narofff60782b2007-11-15 02:58:25 +00002717 // Make all implicit casts explicit...ICE comes in handy:-)
2718 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2719 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregore200adc2008-10-27 19:41:14 +00002720 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002721 ? Context->getObjCIdType()
Douglas Gregore200adc2008-10-27 19:41:14 +00002722 : ICE->getType();
John McCall97513962010-01-15 18:39:57 +00002723 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CastExpr::CK_Unknown,
2724 userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002725 }
2726 // Make id<P...> cast into an 'id' cast.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002727 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002728 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregorf19b2312008-10-28 15:36:24 +00002729 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002730 userExpr = CE->getSubExpr();
John McCall97513962010-01-15 18:39:57 +00002731 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2732 CastExpr::CK_Unknown, userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002733 }
Mike Stump11289f42009-09-09 15:08:12 +00002734 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002735 MsgExprs.push_back(userExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00002736 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2737 // out the argument in the original expression (since we aren't deleting
2738 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2739 //Exp->setArg(i, 0);
Steve Naroff574440f2007-10-24 22:48:43 +00002740 }
Steve Narofff36987c2007-11-04 22:37:50 +00002741 // Generate the funky cast.
2742 CastExpr *cast;
2743 llvm::SmallVector<QualType, 8> ArgTypes;
2744 QualType returnType;
Mike Stump11289f42009-09-09 15:08:12 +00002745
Steve Narofff36987c2007-11-04 22:37:50 +00002746 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff44864e42007-11-15 10:43:57 +00002747 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2748 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2749 else
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002750 ArgTypes.push_back(Context->getObjCIdType());
2751 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattnera4997152009-02-20 18:43:26 +00002752 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Narofff36987c2007-11-04 22:37:50 +00002753 // Push any user argument types.
Chris Lattnera4997152009-02-20 18:43:26 +00002754 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2755 E = OMD->param_end(); PI != E; ++PI) {
2756 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump11289f42009-09-09 15:08:12 +00002757 ? Context->getObjCIdType()
Chris Lattnera4997152009-02-20 18:43:26 +00002758 : (*PI)->getType();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002759 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00002760 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002761 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002762 t = Context->getPointerType(BPT->getPointeeType());
2763 }
Steve Naroff98eb8d12007-11-05 14:36:37 +00002764 ArgTypes.push_back(t);
2765 }
Chris Lattnera4997152009-02-20 18:43:26 +00002766 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2767 ? Context->getObjCIdType() : OMD->getResultType();
Steve Narofff36987c2007-11-04 22:37:50 +00002768 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002769 returnType = Context->getObjCIdType();
Steve Narofff36987c2007-11-04 22:37:50 +00002770 }
2771 // Get the type, we will need to reference it in a couple spots.
Steve Naroff7fa2f042007-11-15 10:28:18 +00002772 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002773
Steve Narofff36987c2007-11-04 22:37:50 +00002774 // Create a reference to the objc_msgSend() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002775 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002776 SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002777
Mike Stump11289f42009-09-09 15:08:12 +00002778 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Narofff36987c2007-11-04 22:37:50 +00002779 // If we don't do this cast, we get the following bizarre warning/note:
2780 // xx.m:13: warning: function called through a non-compatible type
2781 // xx.m:13: note: if this code is reached, the program will abort
John McCall97513962010-01-15 18:39:57 +00002782 cast = NoTypeInfoCStyleCastExpr(Context,
2783 Context->getPointerType(Context->VoidTy),
2784 CastExpr::CK_Unknown, DRE);
Mike Stump11289f42009-09-09 15:08:12 +00002785
Steve Narofff36987c2007-11-04 22:37:50 +00002786 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002787 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002788 &ArgTypes[0], ArgTypes.size(),
Steve Naroff327f0f42008-03-18 02:02:04 +00002789 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002790 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Narofff36987c2007-11-04 22:37:50 +00002791 castType = Context->getPointerType(castType);
John McCall97513962010-01-15 18:39:57 +00002792 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
2793 cast);
Steve Narofff36987c2007-11-04 22:37:50 +00002794
2795 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00002796 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00002797
John McCall9dd450b2009-09-21 23:43:11 +00002798 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002799 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002800 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002801 FT->getResultType(), SourceLocation());
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002802 Stmt *ReplacingStmt = CE;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002803 if (MsgSendStretFlavor) {
2804 // We have the method which returns a struct/union. Must also generate
2805 // call to objc_msgSend_stret and hang both varieties on a conditional
2806 // expression which dictate which one to envoke depending on size of
2807 // method's return type.
Mike Stump11289f42009-09-09 15:08:12 +00002808
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002809 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002810 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002811 SourceLocation());
2812 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall97513962010-01-15 18:39:57 +00002813 cast = NoTypeInfoCStyleCastExpr(Context,
2814 Context->getPointerType(Context->VoidTy),
2815 CastExpr::CK_Unknown, STDRE);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002816 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002817 castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002818 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002819 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002820 castType = Context->getPointerType(castType);
John McCall97513962010-01-15 18:39:57 +00002821 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
2822 cast);
Mike Stump11289f42009-09-09 15:08:12 +00002823
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002824 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00002825 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00002826
John McCall9dd450b2009-09-21 23:43:11 +00002827 FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002828 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002829 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002830 FT->getResultType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002831
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002832 // Build sizeof(returnType)
Mike Stump11289f42009-09-09 15:08:12 +00002833 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCallbcd03502009-12-07 02:54:59 +00002834 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl6f282892008-11-11 17:56:53 +00002835 Context->getSizeType(),
2836 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002837 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2838 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2839 // For X86 it is more complicated and some kind of target specific routine
2840 // is needed to decide what to do.
Mike Stump11289f42009-09-09 15:08:12 +00002841 unsigned IntSize =
Chris Lattner37e05872008-03-05 18:54:05 +00002842 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Mike Stump11289f42009-09-09 15:08:12 +00002843 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002844 Context->IntTy,
2845 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002846 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
2847 BinaryOperator::LE,
2848 Context->IntTy,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002849 SourceLocation());
2850 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump11289f42009-09-09 15:08:12 +00002851 ConditionalOperator *CondExpr =
Douglas Gregor7e112b02009-08-26 14:37:04 +00002852 new (Context) ConditionalOperator(lessThanExpr,
2853 SourceLocation(), CE,
2854 SourceLocation(), STCE, returnType);
Ted Kremenek5a201952009-02-07 01:47:29 +00002855 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002856 }
Mike Stump11289f42009-09-09 15:08:12 +00002857 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002858 return ReplacingStmt;
2859}
2860
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002861Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002862 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Mike Stump11289f42009-09-09 15:08:12 +00002863
Steve Naroff574440f2007-10-24 22:48:43 +00002864 // Now do the actual rewrite.
Chris Lattner2e0d2602008-01-31 19:37:57 +00002865 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00002866
2867 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002868 return ReplacingStmt;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002869}
2870
Steve Naroffd9803712009-04-29 16:37:50 +00002871// typedef struct objc_object Protocol;
2872QualType RewriteObjC::getProtocolType() {
2873 if (!ProtocolTypeDecl) {
John McCallbcd03502009-12-07 02:54:59 +00002874 TypeSourceInfo *TInfo
2875 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroffd9803712009-04-29 16:37:50 +00002876 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002877 SourceLocation(),
Steve Naroffd9803712009-04-29 16:37:50 +00002878 &Context->Idents.get("Protocol"),
John McCallbcd03502009-12-07 02:54:59 +00002879 TInfo);
Steve Naroffd9803712009-04-29 16:37:50 +00002880 }
2881 return Context->getTypeDeclType(ProtocolTypeDecl);
2882}
2883
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00002884/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroffd9803712009-04-29 16:37:50 +00002885/// a synthesized/forward data reference (to the protocol's metadata).
2886/// The forward references (and metadata) are generated in
2887/// RewriteObjC::HandleTranslationUnit().
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002888Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroffd9803712009-04-29 16:37:50 +00002889 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
2890 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump11289f42009-09-09 15:08:12 +00002891 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregored6c7442009-11-23 11:41:28 +00002892 ID, getProtocolType(), 0, VarDecl::Extern);
Steve Naroffd9803712009-04-29 16:37:50 +00002893 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
2894 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
2895 Context->getPointerType(DRE->getType()),
2896 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00002897 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
2898 CastExpr::CK_Unknown,
2899 DerefExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00002900 ReplaceStmt(Exp, castExpr);
2901 ProtocolExprDecls.insert(Exp->getProtocol());
Mike Stump11289f42009-09-09 15:08:12 +00002902 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00002903 return castExpr;
Mike Stump11289f42009-09-09 15:08:12 +00002904
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00002905}
2906
Mike Stump11289f42009-09-09 15:08:12 +00002907bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002908 const char *endBuf) {
2909 while (startBuf < endBuf) {
2910 if (*startBuf == '#') {
2911 // Skip whitespace.
2912 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2913 ;
2914 if (!strncmp(startBuf, "if", strlen("if")) ||
2915 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2916 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2917 !strncmp(startBuf, "define", strlen("define")) ||
2918 !strncmp(startBuf, "undef", strlen("undef")) ||
2919 !strncmp(startBuf, "else", strlen("else")) ||
2920 !strncmp(startBuf, "elif", strlen("elif")) ||
2921 !strncmp(startBuf, "endif", strlen("endif")) ||
2922 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2923 !strncmp(startBuf, "include", strlen("include")) ||
2924 !strncmp(startBuf, "import", strlen("import")) ||
2925 !strncmp(startBuf, "include_next", strlen("include_next")))
2926 return true;
2927 }
2928 startBuf++;
2929 }
2930 return false;
2931}
2932
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002933/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002934/// an objective-c class with ivars.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002935void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002936 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002937 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Mike Stump11289f42009-09-09 15:08:12 +00002938 assert(CDecl->getNameAsCString() &&
Douglas Gregor77324f32008-11-17 14:58:09 +00002939 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00002940 // Do not synthesize more than once.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002941 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00002942 return;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002943 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattner8d1c04f2008-03-16 21:08:55 +00002944 int NumIvars = CDecl->ivar_size();
Steve Naroffdde78982007-11-14 19:25:57 +00002945 SourceLocation LocStart = CDecl->getLocStart();
2946 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00002947
Steve Naroffdde78982007-11-14 19:25:57 +00002948 const char *startBuf = SM->getCharacterData(LocStart);
2949 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00002950
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002951 // If no ivars and no root or if its root, directly or indirectly,
2952 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattner8d1c04f2008-03-16 21:08:55 +00002953 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2954 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner184e65d2009-04-14 23:22:57 +00002955 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Chris Lattner9cc55f52008-01-31 19:51:04 +00002956 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002957 return;
2958 }
Mike Stump11289f42009-09-09 15:08:12 +00002959
2960 // FIXME: This has potential of causing problem. If
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002961 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002962 Result += "\nstruct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002963 Result += CDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00002964 if (LangOpts.Microsoft)
2965 Result += "_IMPL";
Steve Naroffdc5b6b22008-03-12 00:25:36 +00002966
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002967 if (NumIvars > 0) {
Steve Naroffdde78982007-11-14 19:25:57 +00002968 const char *cursor = strchr(startBuf, '{');
Mike Stump11289f42009-09-09 15:08:12 +00002969 assert((cursor && endBuf)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002970 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002971 // If the buffer contains preprocessor directives, we do more fine-grained
2972 // rewrites. This is intended to fix code that looks like (which occurs in
2973 // NSURL.h, for example):
2974 //
2975 // #ifdef XYZ
2976 // @interface Foo : NSObject
2977 // #else
2978 // @interface FooBar : NSObject
2979 // #endif
2980 // {
2981 // int i;
2982 // }
2983 // @end
2984 //
2985 // This clause is segregated to avoid breaking the common case.
2986 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump11289f42009-09-09 15:08:12 +00002987 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002988 CDecl->getClassLoc();
2989 const char *endHeader = SM->getCharacterData(L);
Chris Lattner184e65d2009-04-14 23:22:57 +00002990 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002991
Chris Lattnerf5b77512009-02-20 18:18:36 +00002992 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002993 // advance to the end of the referenced protocols.
2994 while (endHeader < cursor && *endHeader != '>') endHeader++;
2995 endHeader++;
2996 }
2997 // rewrite the original header
2998 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2999 } else {
3000 // rewrite the original header *without* disturbing the '{'
Steve Naroffb0e33902009-12-04 21:36:32 +00003001 ReplaceText(LocStart, cursor-startBuf, Result.c_str(), Result.size());
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003002 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003003 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroffdde78982007-11-14 19:25:57 +00003004 Result = "\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003005 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003006 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003007 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003008 Result += "_IVARS;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003009
Steve Naroffdde78982007-11-14 19:25:57 +00003010 // insert the super class structure definition.
Chris Lattner1780a852008-01-31 19:42:41 +00003011 SourceLocation OnePastCurly =
3012 LocStart.getFileLocWithOffset(cursor-startBuf+1);
3013 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Naroffdde78982007-11-14 19:25:57 +00003014 }
3015 cursor++; // past '{'
Mike Stump11289f42009-09-09 15:08:12 +00003016
Steve Naroffdde78982007-11-14 19:25:57 +00003017 // Now comment out any visibility specifiers.
3018 while (cursor < endBuf) {
3019 if (*cursor == '@') {
3020 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner174a8252007-11-14 22:57:51 +00003021 // Skip whitespace.
3022 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3023 /*scan*/;
3024
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003025 // FIXME: presence of @public, etc. inside comment results in
3026 // this transformation as well, which is still correct c-code.
Steve Naroffdde78982007-11-14 19:25:57 +00003027 if (!strncmp(cursor, "public", strlen("public")) ||
3028 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffaf91b9a2008-04-04 22:34:24 +00003029 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003030 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattner1780a852008-01-31 19:42:41 +00003031 InsertText(atLoc, "// ", 3);
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003032 }
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003033 // FIXME: If there are cases where '<' is used in ivar declaration part
3034 // of user code, then scan the ivar list and use needToScanForQualifiers
3035 // for type checking.
3036 else if (*cursor == '<') {
3037 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner1780a852008-01-31 19:42:41 +00003038 InsertText(atLoc, "/* ", 3);
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003039 cursor = strchr(cursor, '>');
3040 cursor++;
3041 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner1780a852008-01-31 19:42:41 +00003042 InsertText(atLoc, " */", 3);
Steve Naroff295570a2008-10-30 12:09:33 +00003043 } else if (*cursor == '^') { // rewrite block specifier.
3044 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
3045 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003046 }
Steve Naroffdde78982007-11-14 19:25:57 +00003047 cursor++;
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003048 }
Steve Naroffdde78982007-11-14 19:25:57 +00003049 // Don't forget to add a ';'!!
Chris Lattner1780a852008-01-31 19:42:41 +00003050 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Naroffdde78982007-11-14 19:25:57 +00003051 } else { // we don't have any instance variables - insert super struct.
Chris Lattner184e65d2009-04-14 23:22:57 +00003052 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroffdde78982007-11-14 19:25:57 +00003053 Result += " {\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003054 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003055 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003056 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003057 Result += "_IVARS;\n};\n";
Chris Lattner9cc55f52008-01-31 19:51:04 +00003058 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003059 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003060 // Mark this struct as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003061 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff13e74872008-05-06 18:26:51 +00003062 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003063}
3064
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003065// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003066/// class methods.
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003067template<typename MethodIterator>
3068void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3069 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +00003070 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003071 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +00003072 const char *ClassName,
3073 std::string &Result) {
Chris Lattner31bc07e2007-12-12 07:46:12 +00003074 if (MethodBegin == MethodEnd) return;
Mike Stump11289f42009-09-09 15:08:12 +00003075
Chris Lattner31bc07e2007-12-12 07:46:12 +00003076 if (!objc_impl_method) {
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003077 /* struct _objc_method {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003078 SEL _cmd;
3079 char *method_types;
3080 void *_imp;
3081 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003082 */
Chris Lattner211f8b82007-10-25 17:07:24 +00003083 Result += "\nstruct _objc_method {\n";
3084 Result += "\tSEL _cmd;\n";
3085 Result += "\tchar *method_types;\n";
3086 Result += "\tvoid *_imp;\n";
3087 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003088
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003089 objc_impl_method = true;
Fariborz Jahanian74a1cfa2007-10-19 00:36:46 +00003090 }
Mike Stump11289f42009-09-09 15:08:12 +00003091
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003092 // Build _objc_method_list for class's methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003093
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003094 /* struct {
3095 struct _objc_method_list *next_method;
3096 int method_count;
3097 struct _objc_method method_list[];
3098 }
3099 */
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003100 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003101 Result += "\nstatic struct {\n";
3102 Result += "\tstruct _objc_method_list *next_method;\n";
3103 Result += "\tint method_count;\n";
3104 Result += "\tstruct _objc_method method_list[";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003105 Result += utostr(NumMethods);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003106 Result += "];\n} _OBJC_";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003107 Result += prefix;
3108 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3109 Result += "_METHODS_";
3110 Result += ClassName;
Steve Naroffb327e492008-03-12 17:18:30 +00003111 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003112 Result += IsInstanceMethod ? "inst" : "cls";
3113 Result += "_meth\")))= ";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003114 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003115
Chris Lattner31bc07e2007-12-12 07:46:12 +00003116 Result += "\t,{{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003117 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattner31bc07e2007-12-12 07:46:12 +00003118 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003119 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattner31bc07e2007-12-12 07:46:12 +00003120 Result += "\", \"";
3121 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003122 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003123 Result += MethodInternalNames[*MethodBegin];
3124 Result += "}\n";
3125 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3126 Result += "\t ,{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003127 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003128 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003129 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003130 Result += "\", \"";
3131 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003132 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003133 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanian56338352007-11-13 21:02:00 +00003134 Result += "}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003135 }
Chris Lattner31bc07e2007-12-12 07:46:12 +00003136 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003137}
3138
Steve Naroffd9803712009-04-29 16:37:50 +00003139/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner390d39a2008-07-21 21:32:27 +00003140void RewriteObjC::
Steve Naroffd9803712009-04-29 16:37:50 +00003141RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
3142 const char *ClassName, std::string &Result) {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003143 static bool objc_protocol_methods = false;
Steve Naroffd9803712009-04-29 16:37:50 +00003144
3145 // Output struct protocol_methods holder of method selector and type.
3146 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3147 /* struct protocol_methods {
3148 SEL _cmd;
3149 char *method_types;
3150 }
3151 */
3152 Result += "\nstruct _protocol_methods {\n";
3153 Result += "\tstruct objc_selector *_cmd;\n";
3154 Result += "\tchar *method_types;\n";
3155 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003156
Steve Naroffd9803712009-04-29 16:37:50 +00003157 objc_protocol_methods = true;
3158 }
3159 // Do not synthesize the protocol more than once.
3160 if (ObjCSynthesizedProtocols.count(PDecl))
3161 return;
Mike Stump11289f42009-09-09 15:08:12 +00003162
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003163 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3164 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3165 PDecl->instmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003166 /* struct _objc_protocol_method_list {
3167 int protocol_method_count;
3168 struct protocol_methods protocols[];
3169 }
Steve Naroff251084d2008-03-12 01:06:30 +00003170 */
Steve Naroffd9803712009-04-29 16:37:50 +00003171 Result += "\nstatic struct {\n";
3172 Result += "\tint protocol_method_count;\n";
3173 Result += "\tstruct _protocol_methods protocol_methods[";
3174 Result += utostr(NumMethods);
3175 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3176 Result += PDecl->getNameAsString();
3177 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3178 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003179
Steve Naroffd9803712009-04-29 16:37:50 +00003180 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003181 for (ObjCProtocolDecl::instmeth_iterator
3182 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003183 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003184 if (I == PDecl->instmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003185 Result += "\t ,{{(struct objc_selector *)\"";
3186 else
3187 Result += "\t ,{(struct objc_selector *)\"";
3188 Result += (*I)->getSelector().getAsString().c_str();
3189 std::string MethodTypeString;
3190 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3191 Result += "\", \"";
3192 Result += MethodTypeString;
3193 Result += "\"}\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003194 }
Steve Naroffd9803712009-04-29 16:37:50 +00003195 Result += "\t }\n};\n";
3196 }
Mike Stump11289f42009-09-09 15:08:12 +00003197
Steve Naroffd9803712009-04-29 16:37:50 +00003198 // Output class methods declared in this protocol.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003199 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3200 PDecl->classmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003201 if (NumMethods > 0) {
3202 /* struct _objc_protocol_method_list {
3203 int protocol_method_count;
3204 struct protocol_methods protocols[];
3205 }
3206 */
3207 Result += "\nstatic struct {\n";
3208 Result += "\tint protocol_method_count;\n";
3209 Result += "\tstruct _protocol_methods protocol_methods[";
3210 Result += utostr(NumMethods);
3211 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3212 Result += PDecl->getNameAsString();
3213 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3214 "{\n\t";
3215 Result += utostr(NumMethods);
3216 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003217
Steve Naroffd9803712009-04-29 16:37:50 +00003218 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003219 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003220 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003221 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003222 if (I == PDecl->classmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003223 Result += "\t ,{{(struct objc_selector *)\"";
3224 else
3225 Result += "\t ,{(struct objc_selector *)\"";
3226 Result += (*I)->getSelector().getAsString().c_str();
3227 std::string MethodTypeString;
3228 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3229 Result += "\", \"";
3230 Result += MethodTypeString;
3231 Result += "\"}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003232 }
Steve Naroffd9803712009-04-29 16:37:50 +00003233 Result += "\t }\n};\n";
3234 }
3235
3236 // Output:
3237 /* struct _objc_protocol {
3238 // Objective-C 1.0 extensions
3239 struct _objc_protocol_extension *isa;
3240 char *protocol_name;
3241 struct _objc_protocol **protocol_list;
3242 struct _objc_protocol_method_list *instance_methods;
3243 struct _objc_protocol_method_list *class_methods;
Mike Stump11289f42009-09-09 15:08:12 +00003244 };
Steve Naroffd9803712009-04-29 16:37:50 +00003245 */
3246 static bool objc_protocol = false;
3247 if (!objc_protocol) {
3248 Result += "\nstruct _objc_protocol {\n";
3249 Result += "\tstruct _objc_protocol_extension *isa;\n";
3250 Result += "\tchar *protocol_name;\n";
3251 Result += "\tstruct _objc_protocol **protocol_list;\n";
3252 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3253 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003254 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003255
Steve Naroffd9803712009-04-29 16:37:50 +00003256 objc_protocol = true;
Chris Lattner388f6e92008-07-21 21:33:21 +00003257 }
Mike Stump11289f42009-09-09 15:08:12 +00003258
Steve Naroffd9803712009-04-29 16:37:50 +00003259 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3260 Result += PDecl->getNameAsString();
3261 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3262 "{\n\t0, \"";
3263 Result += PDecl->getNameAsString();
3264 Result += "\", 0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003265 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003266 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3267 Result += PDecl->getNameAsString();
3268 Result += ", ";
3269 }
3270 else
3271 Result += "0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003272 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003273 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3274 Result += PDecl->getNameAsString();
3275 Result += "\n";
3276 }
3277 else
3278 Result += "0\n";
3279 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003280
Steve Naroffd9803712009-04-29 16:37:50 +00003281 // Mark this protocol as having been generated.
3282 if (!ObjCSynthesizedProtocols.insert(PDecl))
3283 assert(false && "protocol already synthesized");
3284
3285}
3286
3287void RewriteObjC::
3288RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3289 const char *prefix, const char *ClassName,
3290 std::string &Result) {
3291 if (Protocols.empty()) return;
Mike Stump11289f42009-09-09 15:08:12 +00003292
Steve Naroffd9803712009-04-29 16:37:50 +00003293 for (unsigned i = 0; i != Protocols.size(); i++)
3294 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3295
Chris Lattner388f6e92008-07-21 21:33:21 +00003296 // Output the top lovel protocol meta-data for the class.
3297 /* struct _objc_protocol_list {
3298 struct _objc_protocol_list *next;
3299 int protocol_count;
3300 struct _objc_protocol *class_protocols[];
3301 }
3302 */
3303 Result += "\nstatic struct {\n";
3304 Result += "\tstruct _objc_protocol_list *next;\n";
3305 Result += "\tint protocol_count;\n";
3306 Result += "\tstruct _objc_protocol *class_protocols[";
3307 Result += utostr(Protocols.size());
3308 Result += "];\n} _OBJC_";
3309 Result += prefix;
3310 Result += "_PROTOCOLS_";
3311 Result += ClassName;
3312 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3313 "{\n\t0, ";
3314 Result += utostr(Protocols.size());
3315 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003316
Chris Lattner388f6e92008-07-21 21:33:21 +00003317 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003318 Result += Protocols[0]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003319 Result += " \n";
Mike Stump11289f42009-09-09 15:08:12 +00003320
Chris Lattner388f6e92008-07-21 21:33:21 +00003321 for (unsigned i = 1; i != Protocols.size(); i++) {
3322 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003323 Result += Protocols[i]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003324 Result += "\n";
3325 }
3326 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003327}
3328
Steve Naroffd9803712009-04-29 16:37:50 +00003329
Mike Stump11289f42009-09-09 15:08:12 +00003330/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003331/// implementation.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003332void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003333 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003334 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003335 // Find category declaration for this implementation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003336 ObjCCategoryDecl *CDecl;
Mike Stump11289f42009-09-09 15:08:12 +00003337 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003338 CDecl = CDecl->getNextClassCategory())
3339 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3340 break;
Mike Stump11289f42009-09-09 15:08:12 +00003341
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003342 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003343 FullCategoryName += '_';
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003344 FullCategoryName += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003345
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003346 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003347 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003348 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003349
3350 // If any of our property implementations have associated getters or
3351 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003352 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3353 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003354 Prop != PropEnd; ++Prop) {
3355 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3356 continue;
3357 if (!(*Prop)->getPropertyIvarDecl())
3358 continue;
3359 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3360 if (!PD)
3361 continue;
3362 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3363 InstanceMethods.push_back(Getter);
3364 if (PD->isReadOnly())
3365 continue;
3366 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3367 InstanceMethods.push_back(Setter);
3368 }
3369 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003370 true, "CATEGORY_", FullCategoryName.c_str(),
3371 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003372
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003373 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003374 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003375 false, "CATEGORY_", FullCategoryName.c_str(),
3376 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003377
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003378 // Protocols referenced in class declaration?
Fariborz Jahanian989e0392007-11-13 22:09:49 +00003379 // Null CDecl is case of a category implementation with no category interface
3380 if (CDecl)
Steve Naroffd9803712009-04-29 16:37:50 +00003381 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3382 FullCategoryName.c_str(), Result);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003383 /* struct _objc_category {
3384 char *category_name;
3385 char *class_name;
3386 struct _objc_method_list *instance_methods;
3387 struct _objc_method_list *class_methods;
3388 struct _objc_protocol_list *protocols;
3389 // Objective-C 1.0 extensions
3390 uint32_t size; // sizeof (struct _objc_category)
Mike Stump11289f42009-09-09 15:08:12 +00003391 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003392 // @property decl.
Mike Stump11289f42009-09-09 15:08:12 +00003393 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003394 */
Mike Stump11289f42009-09-09 15:08:12 +00003395
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003396 static bool objc_category = false;
3397 if (!objc_category) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003398 Result += "\nstruct _objc_category {\n";
3399 Result += "\tchar *category_name;\n";
3400 Result += "\tchar *class_name;\n";
3401 Result += "\tstruct _objc_method_list *instance_methods;\n";
3402 Result += "\tstruct _objc_method_list *class_methods;\n";
3403 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003404 Result += "\tunsigned int size;\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003405 Result += "\tstruct _objc_property_list *instance_properties;\n";
3406 Result += "};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003407 objc_category = true;
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003408 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003409 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3410 Result += FullCategoryName;
Steve Naroffb327e492008-03-12 17:18:30 +00003411 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003412 Result += IDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003413 Result += "\"\n\t, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003414 Result += ClassDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003415 Result += "\"\n";
Mike Stump11289f42009-09-09 15:08:12 +00003416
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003417 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003418 Result += "\t, (struct _objc_method_list *)"
3419 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3420 Result += FullCategoryName;
3421 Result += "\n";
3422 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003423 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003424 Result += "\t, 0\n";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003425 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003426 Result += "\t, (struct _objc_method_list *)"
3427 "&_OBJC_CATEGORY_CLASS_METHODS_";
3428 Result += FullCategoryName;
3429 Result += "\n";
3430 }
3431 else
3432 Result += "\t, 0\n";
Mike Stump11289f42009-09-09 15:08:12 +00003433
Chris Lattnerf5b77512009-02-20 18:18:36 +00003434 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump11289f42009-09-09 15:08:12 +00003435 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003436 Result += FullCategoryName;
3437 Result += "\n";
3438 }
3439 else
3440 Result += "\t, 0\n";
3441 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003442}
3443
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003444/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3445/// ivar offset.
Mike Stump11289f42009-09-09 15:08:12 +00003446void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
3447 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003448 std::string &Result) {
Steve Naroffde7d0f62008-07-16 18:22:22 +00003449 if (ivar->isBitField()) {
3450 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3451 // place all bitfields at offset 0.
3452 Result += "0";
3453 } else {
3454 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003455 Result += IDecl->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003456 if (LangOpts.Microsoft)
3457 Result += "_IMPL";
3458 Result += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003459 Result += ivar->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003460 Result += ")";
3461 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003462}
3463
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003464//===----------------------------------------------------------------------===//
3465// Meta Data Emission
3466//===----------------------------------------------------------------------===//
3467
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003468void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003469 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003470 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00003471
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003472 // Explictly declared @interface's are already synthesized.
Steve Naroffaac654a2009-04-20 20:09:33 +00003473 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump11289f42009-09-09 15:08:12 +00003474 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003475 // produce correct synthesis as yet.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003476 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003477 }
Mike Stump11289f42009-09-09 15:08:12 +00003478
Chris Lattner30d23e82007-12-12 07:56:42 +00003479 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003480 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump11289f42009-09-09 15:08:12 +00003481 ? IDecl->ivar_size()
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003482 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003483 if (NumIvars > 0) {
3484 static bool objc_ivar = false;
3485 if (!objc_ivar) {
3486 /* struct _objc_ivar {
3487 char *ivar_name;
3488 char *ivar_type;
3489 int ivar_offset;
Mike Stump11289f42009-09-09 15:08:12 +00003490 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003491 */
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003492 Result += "\nstruct _objc_ivar {\n";
3493 Result += "\tchar *ivar_name;\n";
3494 Result += "\tchar *ivar_type;\n";
3495 Result += "\tint ivar_offset;\n";
3496 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003497
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003498 objc_ivar = true;
3499 }
3500
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003501 /* struct {
3502 int ivar_count;
3503 struct _objc_ivar ivar_list[nIvars];
Mike Stump11289f42009-09-09 15:08:12 +00003504 };
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003505 */
Mike Stump11289f42009-09-09 15:08:12 +00003506 Result += "\nstatic struct {\n";
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003507 Result += "\tint ivar_count;\n";
3508 Result += "\tstruct _objc_ivar ivar_list[";
3509 Result += utostr(NumIvars);
3510 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003511 Result += IDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003512 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003513 "{\n\t";
3514 Result += utostr(NumIvars);
3515 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003516
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003517 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor5f662052009-04-23 03:23:08 +00003518 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003519 if (!IDecl->ivar_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00003520 for (ObjCImplementationDecl::ivar_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003521 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor5f662052009-04-23 03:23:08 +00003522 IV != IVEnd; ++IV)
3523 IVars.push_back(*IV);
3524 IVI = IVars.begin();
3525 IVE = IVars.end();
Chris Lattner30d23e82007-12-12 07:56:42 +00003526 } else {
3527 IVI = CDecl->ivar_begin();
3528 IVE = CDecl->ivar_end();
3529 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003530 Result += "\t,{{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003531 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003532 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003533 std::string TmpString, StrEncoding;
3534 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3535 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003536 Result += StrEncoding;
3537 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003538 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003539 Result += "}\n";
Chris Lattner30d23e82007-12-12 07:56:42 +00003540 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003541 Result += "\t ,{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003542 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003543 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003544 std::string TmpString, StrEncoding;
3545 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3546 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003547 Result += StrEncoding;
3548 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003549 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003550 Result += "}\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003551 }
Mike Stump11289f42009-09-09 15:08:12 +00003552
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003553 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003554 }
Mike Stump11289f42009-09-09 15:08:12 +00003555
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003556 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003557 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003558 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003559
3560 // If any of our property implementations have associated getters or
3561 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003562 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3563 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003564 Prop != PropEnd; ++Prop) {
3565 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3566 continue;
3567 if (!(*Prop)->getPropertyIvarDecl())
3568 continue;
3569 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3570 if (!PD)
3571 continue;
3572 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3573 InstanceMethods.push_back(Getter);
3574 if (PD->isReadOnly())
3575 continue;
3576 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3577 InstanceMethods.push_back(Setter);
3578 }
3579 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003580 true, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003581
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003582 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003583 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003584 false, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003585
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003586 // Protocols referenced in class declaration?
Steve Naroffd9803712009-04-29 16:37:50 +00003587 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3588 "CLASS", CDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003589
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003590 // Declaration of class/meta-class metadata
3591 /* struct _objc_class {
3592 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003593 const char *super_class_name;
3594 char *name;
3595 long version;
3596 long info;
3597 long instance_size;
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003598 struct _objc_ivar_list *ivars;
3599 struct _objc_method_list *methods;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003600 struct objc_cache *cache;
3601 struct objc_protocol_list *protocols;
3602 const char *ivar_layout;
3603 struct _objc_class_ext *ext;
Mike Stump11289f42009-09-09 15:08:12 +00003604 };
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003605 */
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003606 static bool objc_class = false;
3607 if (!objc_class) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003608 Result += "\nstruct _objc_class {\n";
3609 Result += "\tstruct _objc_class *isa;\n";
3610 Result += "\tconst char *super_class_name;\n";
3611 Result += "\tchar *name;\n";
3612 Result += "\tlong version;\n";
3613 Result += "\tlong info;\n";
3614 Result += "\tlong instance_size;\n";
3615 Result += "\tstruct _objc_ivar_list *ivars;\n";
3616 Result += "\tstruct _objc_method_list *methods;\n";
3617 Result += "\tstruct objc_cache *cache;\n";
3618 Result += "\tstruct _objc_protocol_list *protocols;\n";
3619 Result += "\tconst char *ivar_layout;\n";
3620 Result += "\tstruct _objc_class_ext *ext;\n";
3621 Result += "};\n";
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003622 objc_class = true;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003623 }
Mike Stump11289f42009-09-09 15:08:12 +00003624
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003625 // Meta-class metadata generation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003626 ObjCInterfaceDecl *RootClass = 0;
3627 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003628 while (SuperClass) {
3629 RootClass = SuperClass;
3630 SuperClass = SuperClass->getSuperClass();
3631 }
3632 SuperClass = CDecl->getSuperClass();
Mike Stump11289f42009-09-09 15:08:12 +00003633
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003634 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003635 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003636 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003637 "{\n\t(struct _objc_class *)\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003638 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003639 Result += "\"";
3640
3641 if (SuperClass) {
3642 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003643 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003644 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003645 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003646 Result += "\"";
3647 }
3648 else {
3649 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003650 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003651 Result += "\"";
3652 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003653 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003654 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003655 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003656 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff0b844f02008-03-11 18:14:26 +00003657 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003658 Result += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003659 Result += "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003660 }
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003661 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003662 Result += ", 0\n";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003663 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003664 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003665 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003666 Result += ",0,0\n";
3667 }
Fariborz Jahanian486f7182007-10-24 20:54:23 +00003668 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003669 Result += "\t,0,0,0,0\n";
3670 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003671
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003672 // class metadata generation.
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003673 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003674 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003675 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003676 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003677 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003678 if (SuperClass) {
3679 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003680 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003681 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003682 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003683 Result += "\"";
3684 }
3685 else {
3686 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003687 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003688 Result += "\"";
3689 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003690 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003691 Result += ", 0,1";
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003692 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003693 Result += ",0";
3694 else {
3695 // class has size. Must synthesize its size.
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00003696 Result += ",sizeof(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003697 Result += CDecl->getNameAsString();
Steve Naroff14a07462008-03-10 23:33:22 +00003698 if (LangOpts.Microsoft)
3699 Result += "_IMPL";
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003700 Result += ")";
3701 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003702 if (NumIvars > 0) {
Steve Naroff17978c42008-03-11 17:37:02 +00003703 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003704 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003705 Result += "\n\t";
3706 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003707 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003708 Result += ",0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003709 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003710 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003711 Result += CDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003712 Result += ", 0\n\t";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003713 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003714 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003715 Result += ",0,0";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003716 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003717 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003718 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003719 Result += ", 0,0\n";
3720 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003721 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003722 Result += ",0,0,0\n";
3723 Result += "};\n";
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003724}
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003725
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003726/// RewriteImplementations - This routine rewrites all method implementations
3727/// and emits meta-data.
3728
Steve Narofff8cfd162008-11-13 20:07:04 +00003729void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003730 int ClsDefCount = ClassImplementation.size();
3731 int CatDefCount = CategoryImplementation.size();
Mike Stump11289f42009-09-09 15:08:12 +00003732
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003733 // Rewrite implemented methods
3734 for (int i = 0; i < ClsDefCount; i++)
3735 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003736
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00003737 for (int i = 0; i < CatDefCount; i++)
3738 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofff8cfd162008-11-13 20:07:04 +00003739}
Mike Stump11289f42009-09-09 15:08:12 +00003740
Steve Narofff8cfd162008-11-13 20:07:04 +00003741void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3742 int ClsDefCount = ClassImplementation.size();
3743 int CatDefCount = CategoryImplementation.size();
3744
Steve Naroff30ac2222008-05-07 21:23:49 +00003745 // This is needed for determining instance variable offsets.
Fariborz Jahanian9ab63492010-01-07 18:31:42 +00003746 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003747 // For each implemented class, write out all its meta data.
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003748 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003749 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump11289f42009-09-09 15:08:12 +00003750
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003751 // For each implemented category, write out all its meta data.
3752 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003753 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroffd9803712009-04-29 16:37:50 +00003754
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003755 // Write objc_symtab metadata
3756 /*
3757 struct _objc_symtab
3758 {
3759 long sel_ref_cnt;
3760 SEL *refs;
3761 short cls_def_cnt;
3762 short cat_def_cnt;
3763 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump11289f42009-09-09 15:08:12 +00003764 };
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003765 */
Mike Stump11289f42009-09-09 15:08:12 +00003766
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003767 Result += "\nstruct _objc_symtab {\n";
3768 Result += "\tlong sel_ref_cnt;\n";
3769 Result += "\tSEL *refs;\n";
3770 Result += "\tshort cls_def_cnt;\n";
3771 Result += "\tshort cat_def_cnt;\n";
3772 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3773 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003774
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003775 Result += "static struct _objc_symtab "
Steve Naroffb327e492008-03-12 17:18:30 +00003776 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003777 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003778 + ", " + utostr(CatDefCount) + "\n";
3779 for (int i = 0; i < ClsDefCount; i++) {
3780 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003781 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003782 Result += "\n";
3783 }
Mike Stump11289f42009-09-09 15:08:12 +00003784
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003785 for (int i = 0; i < CatDefCount; i++) {
3786 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003787 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003788 Result += "_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003789 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003790 Result += "\n";
3791 }
Mike Stump11289f42009-09-09 15:08:12 +00003792
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003793 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003794
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003795 // Write objc_module metadata
Mike Stump11289f42009-09-09 15:08:12 +00003796
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003797 /*
3798 struct _objc_module {
3799 long version;
3800 long size;
3801 const char *name;
3802 struct _objc_symtab *symtab;
3803 }
3804 */
Mike Stump11289f42009-09-09 15:08:12 +00003805
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003806 Result += "\nstruct _objc_module {\n";
3807 Result += "\tlong version;\n";
3808 Result += "\tlong size;\n";
3809 Result += "\tconst char *name;\n";
3810 Result += "\tstruct _objc_symtab *symtab;\n";
3811 Result += "};\n\n";
3812 Result += "static struct _objc_module "
Steve Naroffb327e492008-03-12 17:18:30 +00003813 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003814 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003815 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003816 Result += "};\n\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003817
3818 if (LangOpts.Microsoft) {
Steve Naroffd9803712009-04-29 16:37:50 +00003819 if (ProtocolExprDecls.size()) {
3820 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
3821 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump11289f42009-09-09 15:08:12 +00003822 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00003823 E = ProtocolExprDecls.end(); I != E; ++I) {
3824 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
3825 Result += (*I)->getNameAsString();
3826 Result += " = &_OBJC_PROTOCOL_";
3827 Result += (*I)->getNameAsString();
3828 Result += ";\n";
3829 }
3830 Result += "#pragma data_seg(pop)\n\n";
3831 }
Steve Naroff945a3b12008-03-10 20:43:59 +00003832 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffcab93d52008-05-07 00:06:16 +00003833 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003834 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3835 Result += "&_OBJC_MODULES;\n";
3836 Result += "#pragma data_seg(pop)\n\n";
3837 }
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003838}
Chris Lattnera7c19fe2007-10-16 22:36:42 +00003839
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003840void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3841 const std::string &Name,
3842 ValueDecl *VD) {
3843 assert(BlockByRefDeclNo.count(VD) &&
3844 "RewriteByRefString: ByRef decl missing");
3845 ResultStr += "struct __Block_byref_" + Name +
3846 "_" + utostr(BlockByRefDeclNo[VD]) ;
3847}
3848
Steve Naroff677ab3a2008-10-27 17:20:55 +00003849std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3850 const char *funcName,
3851 std::string Tag) {
3852 const FunctionType *AFT = CE->getFunctionType();
3853 QualType RT = AFT->getResultType();
3854 std::string StructRef = "struct " + Tag;
3855 std::string S = "static " + RT.getAsString() + " __" +
3856 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00003857
Steve Naroff677ab3a2008-10-27 17:20:55 +00003858 BlockDecl *BD = CE->getBlockDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003859
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003860 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump11289f42009-09-09 15:08:12 +00003861 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Narofff26a1d42009-02-02 17:19:26 +00003862 // block (to reference imported block decl refs).
3863 S += "(" + StructRef + " *__cself)";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003864 } else if (BD->param_empty()) {
3865 S += "(" + StructRef + " *__cself)";
3866 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003867 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003868 assert(FT && "SynthesizeBlockFunc: No function proto");
3869 S += '(';
3870 // first add the implicit argument.
3871 S += StructRef + " *__cself, ";
3872 std::string ParamStr;
3873 for (BlockDecl::param_iterator AI = BD->param_begin(),
3874 E = BD->param_end(); AI != E; ++AI) {
3875 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003876 ParamStr = (*AI)->getNameAsString();
Douglas Gregor7de59662009-05-29 20:38:28 +00003877 (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003878 S += ParamStr;
3879 }
3880 if (FT->isVariadic()) {
3881 if (!BD->param_empty()) S += ", ";
3882 S += "...";
3883 }
3884 S += ')';
3885 }
3886 S += " {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003887
Steve Naroff677ab3a2008-10-27 17:20:55 +00003888 // Create local declarations to avoid rewriting all closure decl ref exprs.
3889 // First, emit a declaration for all "by ref" decls.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00003890 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003891 E = BlockByRefDecls.end(); I != E; ++I) {
3892 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003893 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003894 std::string TypeString;
3895 RewriteByRefString(TypeString, Name, (*I));
3896 TypeString += " *";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003897 Name = TypeString + Name;
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003898 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump11289f42009-09-09 15:08:12 +00003899 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003900 // Next, emit a declaration for all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00003901 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003902 E = BlockByCopyDecls.end(); I != E; ++I) {
3903 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003904 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003905 // Handle nested closure invocation. For example:
3906 //
3907 // void (^myImportedClosure)(void);
3908 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003909 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003910 // void (^anotherClosure)(void);
3911 // anotherClosure = ^(void) {
3912 // myImportedClosure(); // import and invoke the closure
3913 // };
3914 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003915 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003916 S += "struct __block_impl *";
3917 else
Douglas Gregor7de59662009-05-29 20:38:28 +00003918 (*I)->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003919 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003920 }
3921 std::string RewrittenStr = RewrittenBlockExprs[CE];
3922 const char *cstr = RewrittenStr.c_str();
3923 while (*cstr++ != '{') ;
3924 S += cstr;
3925 S += "\n";
3926 return S;
3927}
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00003928
Steve Naroff677ab3a2008-10-27 17:20:55 +00003929std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3930 const char *funcName,
3931 std::string Tag) {
3932 std::string StructRef = "struct " + Tag;
3933 std::string S = "static void __";
Mike Stump11289f42009-09-09 15:08:12 +00003934
Steve Naroff677ab3a2008-10-27 17:20:55 +00003935 S += funcName;
3936 S += "_block_copy_" + utostr(i);
3937 S += "(" + StructRef;
3938 S += "*dst, " + StructRef;
3939 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003940 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003941 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003942 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003943 S += (*I)->getNameAsString();
Steve Naroff5ac4eac2008-12-11 20:51:38 +00003944 S += ", (void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003945 S += (*I)->getNameAsString();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00003946 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003947 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003948 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003949 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003950 }
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003951 S += "}\n";
3952
Steve Naroff677ab3a2008-10-27 17:20:55 +00003953 S += "\nstatic void __";
3954 S += funcName;
3955 S += "_block_dispose_" + utostr(i);
3956 S += "(" + StructRef;
3957 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003958 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003959 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003960 S += "_Block_object_dispose((void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003961 S += (*I)->getNameAsString();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00003962 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003963 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003964 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003965 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003966 }
Mike Stump11289f42009-09-09 15:08:12 +00003967 S += "}\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003968 return S;
3969}
3970
Steve Naroff30484702009-12-06 21:14:13 +00003971std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3972 std::string Desc) {
Steve Naroff295570a2008-10-30 12:09:33 +00003973 std::string S = "\nstruct " + Tag;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003974 std::string Constructor = " " + Tag;
Mike Stump11289f42009-09-09 15:08:12 +00003975
Steve Naroff677ab3a2008-10-27 17:20:55 +00003976 S += " {\n struct __block_impl impl;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003977 S += " struct " + Desc;
3978 S += "* Desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003979
Steve Naroff30484702009-12-06 21:14:13 +00003980 Constructor += "(void *fp, "; // Invoke function pointer.
3981 Constructor += "struct " + Desc; // Descriptor pointer.
3982 Constructor += " *desc";
Mike Stump11289f42009-09-09 15:08:12 +00003983
Steve Naroff677ab3a2008-10-27 17:20:55 +00003984 if (BlockDeclRefs.size()) {
3985 // Output all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00003986 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003987 E = BlockByCopyDecls.end(); I != E; ++I) {
3988 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003989 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003990 std::string ArgName = "_" + FieldName;
3991 // Handle nested closure invocation. For example:
3992 //
3993 // void (^myImportedBlock)(void);
3994 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003995 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003996 // void (^anotherBlock)(void);
3997 // anotherBlock = ^(void) {
3998 // myImportedBlock(); // import and invoke the closure
3999 // };
4000 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00004001 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004002 S += "struct __block_impl *";
4003 Constructor += ", void *" + ArgName;
4004 } else {
Douglas Gregor7de59662009-05-29 20:38:28 +00004005 (*I)->getType().getAsStringInternal(FieldName, Context->PrintingPolicy);
4006 (*I)->getType().getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004007 Constructor += ", " + ArgName;
4008 }
4009 S += FieldName + ";\n";
4010 }
4011 // Output all "by ref" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004012 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004013 E = BlockByRefDecls.end(); I != E; ++I) {
4014 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004015 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004016 std::string ArgName = "_" + FieldName;
4017 // Handle nested closure invocation. For example:
4018 //
4019 // void (^myImportedBlock)(void);
4020 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00004021 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00004022 // void (^anotherBlock)(void);
4023 // anotherBlock = ^(void) {
4024 // myImportedBlock(); // import and invoke the closure
4025 // };
4026 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00004027 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004028 S += "struct __block_impl *";
4029 Constructor += ", void *" + ArgName;
4030 } else {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004031 std::string TypeString;
4032 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004033 TypeString += " *";
4034 FieldName = TypeString + FieldName;
4035 ArgName = TypeString + ArgName;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004036 Constructor += ", " + ArgName;
4037 }
4038 S += FieldName + "; // by ref\n";
4039 }
4040 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004041 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00004042 if (GlobalVarDecl)
4043 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4044 else
4045 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004046 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00004047
Steve Naroff30484702009-12-06 21:14:13 +00004048 Constructor += " Desc = desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00004049
Steve Naroff677ab3a2008-10-27 17:20:55 +00004050 // Initialize all "by copy" arguments.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004051 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004052 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004053 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004054 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00004055 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004056 Constructor += Name + " = (struct __block_impl *)_";
4057 else
4058 Constructor += Name + " = _";
4059 Constructor += Name + ";\n";
4060 }
4061 // Initialize all "by ref" arguments.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004062 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004063 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004064 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004065 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00004066 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004067 Constructor += Name + " = (struct __block_impl *)_";
4068 else
4069 Constructor += Name + " = _";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004070 Constructor += Name + "->__forwarding;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004071 }
4072 } else {
4073 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004074 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00004075 if (GlobalVarDecl)
4076 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4077 else
4078 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004079 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4080 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004081 }
4082 Constructor += " ";
4083 Constructor += "}\n";
4084 S += Constructor;
4085 S += "};\n";
4086 return S;
4087}
4088
Steve Naroff30484702009-12-06 21:14:13 +00004089std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4090 std::string ImplTag, int i,
4091 const char *FunName,
4092 unsigned hasCopy) {
4093 std::string S = "\nstatic struct " + DescTag;
4094
4095 S += " {\n unsigned long reserved;\n";
4096 S += " unsigned long Block_size;\n";
4097 if (hasCopy) {
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004098 S += " void (*copy)(struct ";
4099 S += ImplTag; S += "*, struct ";
4100 S += ImplTag; S += "*);\n";
4101
4102 S += " void (*dispose)(struct ";
4103 S += ImplTag; S += "*);\n";
Steve Naroff30484702009-12-06 21:14:13 +00004104 }
4105 S += "} ";
4106
4107 S += DescTag + "_DATA = { 0, sizeof(struct ";
4108 S += ImplTag + ")";
4109 if (hasCopy) {
4110 S += ", __" + std::string(FunName) + "_block_copy_" + utostr(i);
4111 S += ", __" + std::string(FunName) + "_block_dispose_" + utostr(i);
4112 }
4113 S += "};\n";
4114 return S;
4115}
4116
Steve Naroff677ab3a2008-10-27 17:20:55 +00004117void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004118 const char *FunName) {
4119 // Insert declaration for the function in which block literal is used.
Fariborz Jahanian5c26eee2010-01-15 18:14:52 +00004120 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004121 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004122 // Insert closures that were part of the function.
4123 for (unsigned i = 0; i < Blocks.size(); i++) {
4124
4125 CollectBlockDeclRefInfo(Blocks[i]);
4126
Steve Naroff30484702009-12-06 21:14:13 +00004127 std::string ImplTag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
4128 std::string DescTag = "__" + std::string(FunName) + "_block_desc_" + utostr(i);
Mike Stump11289f42009-09-09 15:08:12 +00004129
Steve Naroff30484702009-12-06 21:14:13 +00004130 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004131
4132 InsertText(FunLocStart, CI.c_str(), CI.size());
4133
Steve Naroff30484702009-12-06 21:14:13 +00004134 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump11289f42009-09-09 15:08:12 +00004135
Steve Naroff677ab3a2008-10-27 17:20:55 +00004136 InsertText(FunLocStart, CF.c_str(), CF.size());
4137
4138 if (ImportedBlockDecls.size()) {
Steve Naroff30484702009-12-06 21:14:13 +00004139 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004140 InsertText(FunLocStart, HF.c_str(), HF.size());
4141 }
Steve Naroff30484702009-12-06 21:14:13 +00004142 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4143 ImportedBlockDecls.size() > 0);
4144 InsertText(FunLocStart, BD.c_str(), BD.size());
Mike Stump11289f42009-09-09 15:08:12 +00004145
Steve Naroff677ab3a2008-10-27 17:20:55 +00004146 BlockDeclRefs.clear();
4147 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004148 BlockByRefDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004149 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004150 BlockByCopyDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004151 BlockCallExprs.clear();
4152 ImportedBlockDecls.clear();
4153 }
4154 Blocks.clear();
4155 RewrittenBlockExprs.clear();
4156}
4157
4158void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4159 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner86d7d912008-11-24 03:54:41 +00004160 const char *FuncName = FD->getNameAsCString();
Mike Stump11289f42009-09-09 15:08:12 +00004161
Steve Naroff677ab3a2008-10-27 17:20:55 +00004162 SynthesizeBlockLiterals(FunLocStart, FuncName);
4163}
4164
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004165static void BuildUniqueMethodName(std::string &Name,
4166 ObjCMethodDecl *MD) {
4167 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4168 Name = IFace->getNameAsCString();
4169 Name += "__" + MD->getSelector().getAsString();
4170 // Convert colons to underscores.
4171 std::string::size_type loc = 0;
4172 while ((loc = Name.find(":", loc)) != std::string::npos)
4173 Name.replace(loc, 1, "_");
4174}
4175
Steve Naroff677ab3a2008-10-27 17:20:55 +00004176void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff295570a2008-10-30 12:09:33 +00004177 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4178 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianb5f99c32010-01-29 01:55:49 +00004179 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004180 std::string FuncName;
4181 BuildUniqueMethodName(FuncName, MD);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004182 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
4183}
4184
4185void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4186 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4187 CI != E; ++CI)
4188 if (*CI) {
4189 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4190 GetBlockDeclRefExprs(CBE->getBody());
4191 else
4192 GetBlockDeclRefExprs(*CI);
4193 }
4194 // Handle specific things.
4195 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
4196 // FIXME: Handle enums.
4197 if (!isa<FunctionDecl>(CDRE->getDecl()))
4198 BlockDeclRefs.push_back(CDRE);
4199 return;
4200}
4201
4202void RewriteObjC::GetBlockCallExprs(Stmt *S) {
4203 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4204 CI != E; ++CI)
4205 if (*CI) {
4206 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4207 GetBlockCallExprs(CBE->getBody());
4208 else
4209 GetBlockCallExprs(*CI);
4210 }
Mike Stump11289f42009-09-09 15:08:12 +00004211
Steve Naroff677ab3a2008-10-27 17:20:55 +00004212 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4213 if (CE->getCallee()->getType()->isBlockPointerType()) {
4214 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
4215 }
4216 }
4217 return;
4218}
4219
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004220Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004221 // Navigate to relevant type information.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004222 const BlockPointerType *CPT = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004223
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004224 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004225 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004226 } else if (const BlockDeclRefExpr *CDRE =
4227 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004228 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004229 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004230 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004231 }
4232 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4233 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4234 }
4235 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4236 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4237 else if (const ConditionalOperator *CEXPR =
4238 dyn_cast<ConditionalOperator>(BlockExp)) {
4239 Expr *LHSExp = CEXPR->getLHS();
4240 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4241 Expr *RHSExp = CEXPR->getRHS();
4242 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4243 Expr *CONDExp = CEXPR->getCond();
4244 ConditionalOperator *CondExpr =
4245 new (Context) ConditionalOperator(CONDExp,
4246 SourceLocation(), cast<Expr>(LHSStmt),
4247 SourceLocation(), cast<Expr>(RHSStmt),
4248 Exp->getType());
4249 return CondExpr;
Fariborz Jahanian6ab7ed42009-12-18 01:15:21 +00004250 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4251 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004252 } else {
4253 assert(1 && "RewriteBlockClass: Bad type");
4254 }
4255 assert(CPT && "RewriteBlockClass: Bad type");
John McCall9dd450b2009-09-21 23:43:11 +00004256 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004257 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004258 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004259 // FTP will be null for closures that don't take arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004260
Steve Naroff350b6652008-10-30 10:07:53 +00004261 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
4262 SourceLocation(),
4263 &Context->Idents.get("__block_impl"));
4264 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff677ab3a2008-10-27 17:20:55 +00004265
Steve Naroff350b6652008-10-30 10:07:53 +00004266 // Generate a funky cast.
4267 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00004268
Steve Naroff350b6652008-10-30 10:07:53 +00004269 // Push the block argument type.
4270 ArgTypes.push_back(PtrBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004271 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004272 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff350b6652008-10-30 10:07:53 +00004273 E = FTP->arg_type_end(); I && (I != E); ++I) {
4274 QualType t = *I;
4275 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00004276 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004277 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff350b6652008-10-30 10:07:53 +00004278 t = Context->getPointerType(BPT->getPointeeType());
4279 }
4280 ArgTypes.push_back(t);
4281 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004282 }
Steve Naroff350b6652008-10-30 10:07:53 +00004283 // Now do the pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00004284 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Steve Naroff350b6652008-10-30 10:07:53 +00004285 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004286
Steve Naroff350b6652008-10-30 10:07:53 +00004287 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump11289f42009-09-09 15:08:12 +00004288
John McCall97513962010-01-15 18:39:57 +00004289 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4290 CastExpr::CK_Unknown,
4291 const_cast<Expr*>(BlockExp));
Steve Naroff350b6652008-10-30 10:07:53 +00004292 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00004293 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4294 BlkCast);
Steve Naroff350b6652008-10-30 10:07:53 +00004295 //PE->dump();
Mike Stump11289f42009-09-09 15:08:12 +00004296
Douglas Gregor91f84212008-12-11 16:49:14 +00004297 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00004298 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004299 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek5a201952009-02-07 01:47:29 +00004300 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4301 FD->getType());
Mike Stump11289f42009-09-09 15:08:12 +00004302
John McCall97513962010-01-15 18:39:57 +00004303 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4304 CastExpr::CK_Unknown, ME);
Ted Kremenek5a201952009-02-07 01:47:29 +00004305 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump11289f42009-09-09 15:08:12 +00004306
Steve Naroff350b6652008-10-30 10:07:53 +00004307 llvm::SmallVector<Expr*, 8> BlkExprs;
4308 // Add the implicit argument.
4309 BlkExprs.push_back(BlkCast);
4310 // Add the user arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004311 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004312 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00004313 BlkExprs.push_back(*I);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004314 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004315 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4316 BlkExprs.size(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004317 Exp->getType(), SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004318 return CE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004319}
4320
4321void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004322 Stmt *BlockCall = SynthesizeBlockCall(Exp, Exp->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00004323 ReplaceStmt(Exp, BlockCall);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004324}
4325
Steve Naroffd9803712009-04-29 16:37:50 +00004326// We need to return the rewritten expression to handle cases where the
4327// BlockDeclRefExpr is embedded in another expression being rewritten.
4328// For example:
4329//
4330// int main() {
4331// __block Foo *f;
4332// __block int i;
Mike Stump11289f42009-09-09 15:08:12 +00004333//
Steve Naroffd9803712009-04-29 16:37:50 +00004334// void (^myblock)() = ^() {
4335// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4336// i = 77;
4337// };
4338//}
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004339Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanian25c07fa2009-12-23 19:26:34 +00004340 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004341 // for each DeclRefExp where BYREFVAR is name of the variable.
4342 ValueDecl *VD;
4343 bool isArrow = true;
4344 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4345 VD = BDRE->getDecl();
4346 else {
4347 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4348 isArrow = false;
4349 }
4350
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004351 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4352 &Context->Idents.get("__forwarding"),
4353 Context->VoidPtrTy, 0,
4354 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004355 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4356 FD, SourceLocation(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004357 FD->getType());
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004358
4359 const char *Name = VD->getNameAsCString();
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004360 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4361 &Context->Idents.get(Name),
4362 Context->VoidPtrTy, 0,
4363 /*BitWidth=*/0, /*Mutable=*/true);
4364 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004365 DeclRefExp->getType());
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004366
4367
4368
Steve Narofff26a1d42009-02-02 17:19:26 +00004369 // Need parens to enforce precedence.
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004370 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4371 ME);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004372 ReplaceStmt(DeclRefExp, PE);
Steve Naroffd9803712009-04-29 16:37:50 +00004373 return PE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004374}
4375
Steve Naroffc989a7b2008-11-03 23:29:32 +00004376void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4377 SourceLocation LocStart = CE->getLParenLoc();
4378 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofff4b992a2008-10-28 20:29:00 +00004379
4380 // Need to avoid trying to rewrite synthesized casts.
4381 if (LocStart.isInvalid())
4382 return;
Steve Naroff3e7ced12008-11-03 11:20:24 +00004383 // Need to avoid trying to rewrite casts contained in macros.
4384 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4385 return;
Mike Stump11289f42009-09-09 15:08:12 +00004386
Steve Naroff677ab3a2008-10-27 17:20:55 +00004387 const char *startBuf = SM->getCharacterData(LocStart);
4388 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004389 QualType QT = CE->getType();
4390 const Type* TypePtr = QT->getAs<Type>();
4391 if (isa<TypeOfExprType>(TypePtr)) {
4392 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4393 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4394 std::string TypeAsString = "(";
4395 TypeAsString += QT.getAsString();
4396 TypeAsString += ")";
4397 ReplaceText(LocStart, endBuf-startBuf+1,
4398 TypeAsString.c_str(), TypeAsString.size());
4399 return;
4400 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004401 // advance the location to startArgList.
4402 const char *argPtr = startBuf;
Mike Stump11289f42009-09-09 15:08:12 +00004403
Steve Naroff677ab3a2008-10-27 17:20:55 +00004404 while (*argPtr++ && (argPtr < endBuf)) {
4405 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004406 case '^':
4407 // Replace the '^' with '*'.
4408 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
4409 ReplaceText(LocStart, 1, "*", 1);
4410 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004411 }
4412 }
4413 return;
4414}
4415
4416void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4417 SourceLocation DeclLoc = FD->getLocation();
4418 unsigned parenCount = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004419
Steve Naroff677ab3a2008-10-27 17:20:55 +00004420 // We have 1 or more arguments that have closure pointers.
4421 const char *startBuf = SM->getCharacterData(DeclLoc);
4422 const char *startArgList = strchr(startBuf, '(');
Mike Stump11289f42009-09-09 15:08:12 +00004423
Steve Naroff677ab3a2008-10-27 17:20:55 +00004424 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004425
Steve Naroff677ab3a2008-10-27 17:20:55 +00004426 parenCount++;
4427 // advance the location to startArgList.
4428 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4429 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump11289f42009-09-09 15:08:12 +00004430
Steve Naroff677ab3a2008-10-27 17:20:55 +00004431 const char *argPtr = startArgList;
Mike Stump11289f42009-09-09 15:08:12 +00004432
Steve Naroff677ab3a2008-10-27 17:20:55 +00004433 while (*argPtr++ && parenCount) {
4434 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004435 case '^':
4436 // Replace the '^' with '*'.
4437 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
4438 ReplaceText(DeclLoc, 1, "*", 1);
4439 break;
4440 case '(':
4441 parenCount++;
4442 break;
4443 case ')':
4444 parenCount--;
4445 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004446 }
4447 }
4448 return;
4449}
4450
4451bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004452 const FunctionProtoType *FTP;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004453 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004454 if (PT) {
John McCall9dd450b2009-09-21 23:43:11 +00004455 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004456 } else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004457 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004458 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall9dd450b2009-09-21 23:43:11 +00004459 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004460 }
4461 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004462 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004463 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +00004464 if (isTopLevelBlockPointerType(*I))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004465 return true;
4466 }
4467 return false;
4468}
4469
Ted Kremenek5a201952009-02-07 01:47:29 +00004470void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4471 const char *&RParen) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004472 const char *argPtr = strchr(Name, '(');
4473 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004474
Steve Naroff677ab3a2008-10-27 17:20:55 +00004475 LParen = argPtr; // output the start.
4476 argPtr++; // skip past the left paren.
4477 unsigned parenCount = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004478
Steve Naroff677ab3a2008-10-27 17:20:55 +00004479 while (*argPtr && parenCount) {
4480 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004481 case '(': parenCount++; break;
4482 case ')': parenCount--; break;
4483 default: break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004484 }
4485 if (parenCount) argPtr++;
4486 }
4487 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4488 RParen = argPtr; // output the end
4489}
4490
4491void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4492 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4493 RewriteBlockPointerFunctionArgs(FD);
4494 return;
Mike Stump11289f42009-09-09 15:08:12 +00004495 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004496 // Handle Variables and Typedefs.
4497 SourceLocation DeclLoc = ND->getLocation();
4498 QualType DeclT;
4499 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4500 DeclT = VD->getType();
4501 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4502 DeclT = TDD->getUnderlyingType();
4503 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4504 DeclT = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004505 else
Steve Naroff677ab3a2008-10-27 17:20:55 +00004506 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump11289f42009-09-09 15:08:12 +00004507
Steve Naroff677ab3a2008-10-27 17:20:55 +00004508 const char *startBuf = SM->getCharacterData(DeclLoc);
4509 const char *endBuf = startBuf;
4510 // scan backward (from the decl location) for the end of the previous decl.
4511 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4512 startBuf--;
Mike Stump11289f42009-09-09 15:08:12 +00004513
Steve Naroff677ab3a2008-10-27 17:20:55 +00004514 // *startBuf != '^' if we are dealing with a pointer to function that
4515 // may take block argument types (which will be handled below).
4516 if (*startBuf == '^') {
4517 // Replace the '^' with '*', computing a negative offset.
4518 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4519 ReplaceText(DeclLoc, 1, "*", 1);
4520 }
4521 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4522 // Replace the '^' with '*' for arguments.
4523 DeclLoc = ND->getLocation();
4524 startBuf = SM->getCharacterData(DeclLoc);
4525 const char *argListBegin, *argListEnd;
4526 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4527 while (argListBegin < argListEnd) {
4528 if (*argListBegin == '^') {
4529 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
4530 ReplaceText(CaretLoc, 1, "*", 1);
4531 }
4532 argListBegin++;
4533 }
4534 }
4535 return;
4536}
4537
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004538
4539/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4540/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4541/// struct Block_byref_id_object *src) {
4542/// _Block_object_assign (&_dest->object, _src->object,
4543/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4544/// [|BLOCK_FIELD_IS_WEAK]) // object
4545/// _Block_object_assign(&_dest->object, _src->object,
4546/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4547/// [|BLOCK_FIELD_IS_WEAK]) // block
4548/// }
4549/// And:
4550/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4551/// _Block_object_dispose(_src->object,
4552/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4553/// [|BLOCK_FIELD_IS_WEAK]) // object
4554/// _Block_object_dispose(_src->object,
4555/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4556/// [|BLOCK_FIELD_IS_WEAK]) // block
4557/// }
4558
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004559std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4560 int flag) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004561 std::string S;
Benjamin Kramere056cea2010-01-10 19:57:50 +00004562 if (CopyDestroyCache.count(flag))
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004563 return S;
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004564 CopyDestroyCache.insert(flag);
4565 S = "static void __Block_byref_id_object_copy_";
4566 S += utostr(flag);
4567 S += "(void *dst, void *src) {\n";
4568
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004569 // offset into the object pointer is computed as:
4570 // void * + void* + int + int + void* + void *
4571 unsigned IntSize =
4572 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4573 unsigned VoidPtrSize =
4574 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4575
4576 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
4577 S += " _Block_object_assign((char*)dst + ";
4578 S += utostr(offset);
4579 S += ", *(void * *) ((char*)src + ";
4580 S += utostr(offset);
4581 S += "), ";
4582 S += utostr(flag);
4583 S += ");\n}\n";
4584
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004585 S += "static void __Block_byref_id_object_dispose_";
4586 S += utostr(flag);
4587 S += "(void *src) {\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004588 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4589 S += utostr(offset);
4590 S += "), ";
4591 S += utostr(flag);
4592 S += ");\n}\n";
4593 return S;
4594}
4595
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004596/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4597/// the declaration into:
4598/// struct __Block_byref_ND {
4599/// void *__isa; // NULL for everything except __weak pointers
4600/// struct __Block_byref_ND *__forwarding;
4601/// int32_t __flags;
4602/// int32_t __size;
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004603/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4604/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004605/// typex ND;
4606/// };
4607///
4608/// It then replaces declaration of ND variable with:
4609/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4610/// __size=sizeof(struct __Block_byref_ND),
4611/// ND=initializer-if-any};
4612///
4613///
4614void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004615 // Insert declaration for the function in which block literal is
4616 // used.
4617 if (CurFunctionDeclToDeclareForBlock)
4618 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004619 int flag = 0;
4620 int isa = 0;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004621 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4622 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian92368a12009-12-30 20:38:08 +00004623 SourceLocation X = ND->getLocEnd();
4624 X = SM->getInstantiationLoc(X);
4625 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004626 std::string Name(ND->getNameAsString());
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004627 std::string ByrefType;
4628 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004629 ByrefType += " {\n";
4630 ByrefType += " void *__isa;\n";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004631 RewriteByRefString(ByrefType, Name, ND);
4632 ByrefType += " *__forwarding;\n";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004633 ByrefType += " int __flags;\n";
4634 ByrefType += " int __size;\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004635 // Add void *__Block_byref_id_object_copy;
4636 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004637 QualType Ty = ND->getType();
4638 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4639 if (HasCopyAndDispose) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004640 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4641 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004642 }
4643
4644 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004645 ByrefType += " " + Name + ";\n";
4646 ByrefType += "};\n";
4647 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004648 SourceLocation FunLocStart;
4649 if (CurFunctionDef)
4650 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4651 else {
4652 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4653 FunLocStart = CurMethodDef->getLocStart();
4654 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004655 InsertText(FunLocStart, ByrefType.c_str(), ByrefType.size());
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004656 if (Ty.isObjCGCWeak()) {
4657 flag |= BLOCK_FIELD_IS_WEAK;
4658 isa = 1;
4659 }
4660
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004661 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004662 flag = BLOCK_BYREF_CALLER;
4663 QualType Ty = ND->getType();
4664 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4665 if (Ty->isBlockPointerType())
4666 flag |= BLOCK_FIELD_IS_BLOCK;
4667 else
4668 flag |= BLOCK_FIELD_IS_OBJECT;
4669 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004670 if (!HF.empty())
4671 InsertText(FunLocStart, HF.c_str(), HF.size());
4672 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004673
4674 // struct __Block_byref_ND ND =
4675 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4676 // initializer-if-any};
4677 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanianf7945432010-01-05 18:15:57 +00004678 unsigned flags = 0;
4679 if (HasCopyAndDispose)
4680 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004681 Name = ND->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004682 ByrefType.clear();
4683 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004684 std::string ForwardingCastType("(");
4685 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004686 if (!hasInit) {
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004687 ByrefType += " " + Name + " = {(void*)";
4688 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004689 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004690 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004691 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004692 ByrefType += "sizeof(";
4693 RewriteByRefString(ByrefType, Name, ND);
4694 ByrefType += ")";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004695 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004696 ByrefType += ", __Block_byref_id_object_copy_";
4697 ByrefType += utostr(flag);
4698 ByrefType += ", __Block_byref_id_object_dispose_";
4699 ByrefType += utostr(flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004700 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004701 ByrefType += "};\n";
4702 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(),
4703 ByrefType.c_str(), ByrefType.size());
4704 }
4705 else {
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004706 SourceLocation startLoc;
4707 Expr *E = ND->getInit();
4708 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4709 startLoc = ECE->getLParenLoc();
4710 else
4711 startLoc = E->getLocStart();
Fariborz Jahanianb8646ed2010-01-05 23:06:29 +00004712 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004713 endBuf = SM->getCharacterData(startLoc);
4714
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004715 ByrefType += " " + Name;
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004716 ByrefType += " = {(void*)";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004717 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004718 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004719 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004720 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004721 ByrefType += "sizeof(";
4722 RewriteByRefString(ByrefType, Name, ND);
4723 ByrefType += "), ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004724 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004725 ByrefType += "__Block_byref_id_object_copy_";
4726 ByrefType += utostr(flag);
4727 ByrefType += ", __Block_byref_id_object_dispose_";
4728 ByrefType += utostr(flag);
4729 ByrefType += ", ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004730 }
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004731 ReplaceText(DeclLoc, endBuf-startBuf,
4732 ByrefType.c_str(), ByrefType.size());
Steve Naroff13468372009-12-23 17:24:33 +00004733
4734 // Complete the newly synthesized compound expression by inserting a right
4735 // curly brace before the end of the declaration.
4736 // FIXME: This approach avoids rewriting the initializer expression. It
4737 // also assumes there is only one declarator. For example, the following
4738 // isn't currently supported by this routine (in general):
4739 //
4740 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4741 //
4742 const char *startBuf = SM->getCharacterData(startLoc);
4743 const char *semiBuf = strchr(startBuf, ';');
4744 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4745 SourceLocation semiLoc =
4746 startLoc.getFileLocWithOffset(semiBuf-startBuf);
4747
4748 InsertText(semiLoc, "}", 1);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004749 }
Fariborz Jahanian81203462009-12-22 00:48:54 +00004750 return;
4751}
4752
Mike Stump11289f42009-09-09 15:08:12 +00004753void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004754 // Add initializers for any closure decl refs.
4755 GetBlockDeclRefExprs(Exp->getBody());
4756 if (BlockDeclRefs.size()) {
4757 // Unique all "by copy" declarations.
4758 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004759 if (!BlockDeclRefs[i]->isByRef()) {
4760 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4761 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4762 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4763 }
4764 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004765 // Unique all "by ref" declarations.
4766 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4767 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004768 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4769 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4770 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4771 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004772 }
4773 // Find any imported blocks...they will need special attention.
4774 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004775 if (BlockDeclRefs[i]->isByRef() ||
4776 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4777 BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroff832d8902008-11-13 17:40:07 +00004778 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004779 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4780 }
4781 }
4782}
4783
Steve Narofff4b992a2008-10-28 20:29:00 +00004784FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4785 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004786 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump11289f42009-09-09 15:08:12 +00004787 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004788 ID, FType, 0, FunctionDecl::Extern, false,
Douglas Gregor739ef0c2009-02-25 16:33:18 +00004789 false);
Steve Narofff4b992a2008-10-28 20:29:00 +00004790}
4791
Steve Naroffd8907b72008-10-29 18:15:37 +00004792Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004793 Blocks.push_back(Exp);
4794
4795 CollectBlockDeclRefInfo(Exp);
4796 std::string FuncName;
Mike Stump11289f42009-09-09 15:08:12 +00004797
Steve Narofff4b992a2008-10-28 20:29:00 +00004798 if (CurFunctionDef)
Chris Lattnere4b95692008-11-24 03:33:13 +00004799 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004800 else if (CurMethodDef)
4801 BuildUniqueMethodName(FuncName, CurMethodDef);
4802 else if (GlobalVarDecl)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004803 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump11289f42009-09-09 15:08:12 +00004804
Steve Narofff4b992a2008-10-28 20:29:00 +00004805 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump11289f42009-09-09 15:08:12 +00004806
Steve Narofff4b992a2008-10-28 20:29:00 +00004807 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4808 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump11289f42009-09-09 15:08:12 +00004809
Steve Narofff4b992a2008-10-28 20:29:00 +00004810 // Get a pointer to the function type so we can cast appropriately.
4811 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4812
4813 FunctionDecl *FD;
4814 Expr *NewRep;
Mike Stump11289f42009-09-09 15:08:12 +00004815
Steve Narofff4b992a2008-10-28 20:29:00 +00004816 // Simulate a contructor call...
4817 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004818 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004819
Steve Narofff4b992a2008-10-28 20:29:00 +00004820 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00004821
Steve Naroffe2514232008-10-29 21:23:59 +00004822 // Initialize the block function.
Steve Narofff4b992a2008-10-28 20:29:00 +00004823 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004824 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4825 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00004826 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4827 CastExpr::CK_Unknown, Arg);
Mike Stump11289f42009-09-09 15:08:12 +00004828 InitExprs.push_back(castExpr);
4829
Steve Naroff30484702009-12-06 21:14:13 +00004830 // Initialize the block descriptor.
4831 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump11289f42009-09-09 15:08:12 +00004832
Steve Naroff30484702009-12-06 21:14:13 +00004833 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
4834 &Context->Idents.get(DescData.c_str()),
4835 Context->VoidPtrTy, 0,
4836 VarDecl::Static);
4837 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
4838 new (Context) DeclRefExpr(NewVD,
4839 Context->VoidPtrTy, SourceLocation()),
4840 UnaryOperator::AddrOf,
4841 Context->getPointerType(Context->VoidPtrTy),
4842 SourceLocation());
4843 InitExprs.push_back(DescRefExpr);
4844
Steve Narofff4b992a2008-10-28 20:29:00 +00004845 // Add initializers for any closure decl refs.
4846 if (BlockDeclRefs.size()) {
Steve Naroffe2514232008-10-29 21:23:59 +00004847 Expr *Exp;
Steve Narofff4b992a2008-10-28 20:29:00 +00004848 // Output all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004849 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004850 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004851 if (isObjCType((*I)->getType())) {
Steve Naroffe2514232008-10-29 21:23:59 +00004852 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner86d7d912008-11-24 03:54:41 +00004853 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004854 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroffa5c0db82008-12-11 21:05:33 +00004855 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004856 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004857 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
John McCall97513962010-01-15 18:39:57 +00004858 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4859 CastExpr::CK_Unknown, Arg);
Steve Narofff4b992a2008-10-28 20:29:00 +00004860 } else {
Chris Lattner86d7d912008-11-24 03:54:41 +00004861 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004862 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004863 }
Mike Stump11289f42009-09-09 15:08:12 +00004864 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004865 }
4866 // Output all "by ref" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004867 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004868 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004869 ValueDecl *ND = (*I);
4870 std::string Name(ND->getNameAsString());
4871 std::string RecName;
4872 RewriteByRefString(RecName, Name, ND);
4873 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4874 + sizeof("struct"));
4875 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
4876 SourceLocation(), II);
4877 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4878 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4879
Chris Lattner86d7d912008-11-24 03:54:41 +00004880 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004881 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4882 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004883 Context->getPointerType(Exp->getType()),
Steve Naroffe2514232008-10-29 21:23:59 +00004884 SourceLocation());
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004885 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CastExpr::CK_Unknown, Exp);
Mike Stump11289f42009-09-09 15:08:12 +00004886 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004887 }
4888 }
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00004889 if (ImportedBlockDecls.size()) {
4890 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4891 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff30484702009-12-06 21:14:13 +00004892 unsigned IntSize =
4893 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00004894 Expr *FlagExp = new (Context) IntegerLiteral(llvm::APInt(IntSize, flag),
4895 Context->IntTy, SourceLocation());
4896 InitExprs.push_back(FlagExp);
Steve Naroff30484702009-12-06 21:14:13 +00004897 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004898 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4899 FType, SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00004900 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004901 Context->getPointerType(NewRep->getType()),
Steve Narofff4b992a2008-10-28 20:29:00 +00004902 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00004903 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CastExpr::CK_Unknown,
4904 NewRep);
Steve Narofff4b992a2008-10-28 20:29:00 +00004905 BlockDeclRefs.clear();
4906 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004907 BlockByRefDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00004908 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004909 BlockByCopyDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00004910 ImportedBlockDecls.clear();
4911 return NewRep;
4912}
4913
4914//===----------------------------------------------------------------------===//
4915// Function Body / Expression rewriting
4916//===----------------------------------------------------------------------===//
4917
Steve Naroff4588d0f2008-12-04 16:24:46 +00004918// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4919// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4920// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4921// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4922// Since the rewriter isn't capable of rewriting rewritten code, it's important
4923// we get this right.
4924void RewriteObjC::CollectPropertySetters(Stmt *S) {
4925 // Perform a bottom up traversal of all children.
4926 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4927 CI != E; ++CI)
4928 if (*CI)
4929 CollectPropertySetters(*CI);
4930
4931 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4932 if (BinOp->isAssignmentOp()) {
4933 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4934 PropSetters[PRE] = BinOp;
4935 }
4936 }
4937}
4938
Steve Narofff4b992a2008-10-28 20:29:00 +00004939Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump11289f42009-09-09 15:08:12 +00004940 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004941 isa<DoStmt>(S) || isa<ForStmt>(S))
4942 Stmts.push_back(S);
4943 else if (isa<ObjCForCollectionStmt>(S)) {
4944 Stmts.push_back(S);
Chris Lattnerb71980f2010-01-09 21:45:57 +00004945 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofff4b992a2008-10-28 20:29:00 +00004946 }
Mike Stump11289f42009-09-09 15:08:12 +00004947
Steve Narofff4b992a2008-10-28 20:29:00 +00004948 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004949
Steve Narofff4b992a2008-10-28 20:29:00 +00004950 // Perform a bottom up rewrite of all children.
4951 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4952 CI != E; ++CI)
4953 if (*CI) {
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00004954 Stmt *newStmt;
4955 Stmt *S = (*CI);
4956 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4957 Expr *OldBase = IvarRefExpr->getBase();
4958 bool replaced = false;
4959 newStmt = RewriteObjCNestedIvarRefExpr(S, replaced);
4960 if (replaced) {
4961 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
4962 ReplaceStmt(OldBase, IRE->getBase());
4963 else
4964 ReplaceStmt(S, newStmt);
4965 }
4966 }
4967 else
4968 newStmt = RewriteFunctionBodyOrGlobalInitializer(S);
Mike Stump11289f42009-09-09 15:08:12 +00004969 if (newStmt)
Steve Narofff4b992a2008-10-28 20:29:00 +00004970 *CI = newStmt;
4971 }
Mike Stump11289f42009-09-09 15:08:12 +00004972
Steve Narofff4b992a2008-10-28 20:29:00 +00004973 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4974 // Rewrite the block body in place.
4975 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Mike Stump11289f42009-09-09 15:08:12 +00004976
Steve Narofff4b992a2008-10-28 20:29:00 +00004977 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenekdb2ef372010-01-07 18:00:35 +00004978 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroffd8907b72008-10-29 18:15:37 +00004979 RewrittenBlockExprs[BE] = Str;
Mike Stump11289f42009-09-09 15:08:12 +00004980
Steve Narofff4b992a2008-10-28 20:29:00 +00004981 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4982 //blockTranscribed->dump();
Steve Naroffd8907b72008-10-29 18:15:37 +00004983 ReplaceStmt(S, blockTranscribed);
Steve Narofff4b992a2008-10-28 20:29:00 +00004984 return blockTranscribed;
4985 }
4986 // Handle specific things.
4987 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4988 return RewriteAtEncode(AtEncode);
Mike Stump11289f42009-09-09 15:08:12 +00004989
Steve Naroff4588d0f2008-12-04 16:24:46 +00004990 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4991 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4992 if (BinOp) {
4993 // Because the rewriter doesn't allow us to rewrite rewritten code,
4994 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroff08628db2008-12-09 12:56:34 +00004995 DisableReplaceStmt = true;
4996 // Save the source range. Even if we disable the replacement, the
4997 // rewritten node will have been inserted into the tree. If the synthesized
4998 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump11289f42009-09-09 15:08:12 +00004999 // self.errorHandler = handler ? handler :
Steve Naroff08628db2008-12-09 12:56:34 +00005000 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
5001 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroff4588d0f2008-12-04 16:24:46 +00005002 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroff08628db2008-12-09 12:56:34 +00005003 DisableReplaceStmt = false;
Steve Naroff22216db2008-12-04 23:50:32 +00005004 //
5005 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
5006 // we changed the RHS of BinOp, the rewriter would fail (since it needs
5007 // to see the original expression). Consider this example:
5008 //
5009 // Foo *obj1, *obj2;
5010 //
5011 // obj1.i = [obj2 rrrr];
5012 //
5013 // 'BinOp' for the previous expression looks like:
5014 //
5015 // (BinaryOperator 0x231ccf0 'int' '='
5016 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
5017 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
5018 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
5019 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
5020 //
5021 // 'newStmt' represents the rewritten message expression. For example:
5022 //
5023 // (CallExpr 0x231d300 'id':'struct objc_object *'
5024 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
5025 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
5026 // (CStyleCastExpr 0x231d220 'void *'
5027 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
5028 //
5029 // Note that 'newStmt' is passed to RewritePropertySetter so that it
5030 // can be used as the setter argument. ReplaceStmt() will still 'see'
5031 // the original RHS (since we haven't altered BinOp).
5032 //
Mike Stump11289f42009-09-09 15:08:12 +00005033 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff22216db2008-12-04 23:50:32 +00005034 // node. As a result, we now leak the original AST nodes.
5035 //
Steve Naroff08628db2008-12-09 12:56:34 +00005036 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroff4588d0f2008-12-04 16:24:46 +00005037 } else {
5038 return RewritePropertyGetter(PropRefExpr);
Steve Narofff326f402008-12-03 00:56:33 +00005039 }
5040 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005041 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5042 return RewriteAtSelector(AtSelector);
Mike Stump11289f42009-09-09 15:08:12 +00005043
Steve Narofff4b992a2008-10-28 20:29:00 +00005044 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5045 return RewriteObjCStringLiteral(AtString);
Mike Stump11289f42009-09-09 15:08:12 +00005046
Steve Narofff4b992a2008-10-28 20:29:00 +00005047 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00005048#if 0
Steve Narofff4b992a2008-10-28 20:29:00 +00005049 // Before we rewrite it, put the original message expression in a comment.
5050 SourceLocation startLoc = MessExpr->getLocStart();
5051 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00005052
Steve Narofff4b992a2008-10-28 20:29:00 +00005053 const char *startBuf = SM->getCharacterData(startLoc);
5054 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump11289f42009-09-09 15:08:12 +00005055
Steve Narofff4b992a2008-10-28 20:29:00 +00005056 std::string messString;
5057 messString += "// ";
5058 messString.append(startBuf, endBuf-startBuf+1);
5059 messString += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00005060
5061 // FIXME: Missing definition of
Steve Narofff4b992a2008-10-28 20:29:00 +00005062 // InsertText(clang::SourceLocation, char const*, unsigned int).
5063 // InsertText(startLoc, messString.c_str(), messString.size());
5064 // Tried this, but it didn't work either...
5065 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff4588d0f2008-12-04 16:24:46 +00005066#endif
Steve Narofff4b992a2008-10-28 20:29:00 +00005067 return RewriteMessageExpr(MessExpr);
5068 }
Mike Stump11289f42009-09-09 15:08:12 +00005069
Steve Narofff4b992a2008-10-28 20:29:00 +00005070 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5071 return RewriteObjCTryStmt(StmtTry);
5072
5073 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5074 return RewriteObjCSynchronizedStmt(StmtTry);
5075
5076 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5077 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump11289f42009-09-09 15:08:12 +00005078
Steve Narofff4b992a2008-10-28 20:29:00 +00005079 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5080 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump11289f42009-09-09 15:08:12 +00005081
5082 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofff4b992a2008-10-28 20:29:00 +00005083 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump11289f42009-09-09 15:08:12 +00005084 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofff4b992a2008-10-28 20:29:00 +00005085 OrigStmtRange.getEnd());
5086 if (BreakStmt *StmtBreakStmt =
5087 dyn_cast<BreakStmt>(S))
5088 return RewriteBreakStmt(StmtBreakStmt);
5089 if (ContinueStmt *StmtContinueStmt =
5090 dyn_cast<ContinueStmt>(S))
5091 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump11289f42009-09-09 15:08:12 +00005092
5093 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofff4b992a2008-10-28 20:29:00 +00005094 // and cast exprs.
5095 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5096 // FIXME: What we're doing here is modifying the type-specifier that
5097 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump11289f42009-09-09 15:08:12 +00005098 // a separate type-specifier that we can rewrite.
Steve Naroffe70a52a2009-12-05 15:55:59 +00005099 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5100 // the context of an ObjCForCollectionStmt. For example:
5101 // NSArray *someArray;
5102 // for (id <FooProtocol> index in someArray) ;
5103 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5104 // and it depends on the original text locations/positions.
Benjamin Krameracc5fa12009-12-05 22:16:51 +00005105 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroffe70a52a2009-12-05 15:55:59 +00005106 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump11289f42009-09-09 15:08:12 +00005107
Steve Narofff4b992a2008-10-28 20:29:00 +00005108 // Blocks rewrite rules.
5109 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5110 DI != DE; ++DI) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +00005111 Decl *SD = *DI;
Steve Narofff4b992a2008-10-28 20:29:00 +00005112 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005113 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005114 RewriteBlockPointerDecl(ND);
Mike Stump11289f42009-09-09 15:08:12 +00005115 else if (ND->getType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005116 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00005117 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005118 if (VD->hasAttr<BlocksAttr>()) {
5119 static unsigned uniqueByrefDeclCount = 0;
5120 assert(!BlockByRefDeclNo.count(ND) &&
5121 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5122 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005123 RewriteByRefVar(VD);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005124 }
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00005125 else
5126 RewriteTypeOfDecl(VD);
5127 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005128 }
5129 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005130 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005131 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005132 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005133 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5134 }
5135 }
5136 }
Mike Stump11289f42009-09-09 15:08:12 +00005137
Steve Narofff4b992a2008-10-28 20:29:00 +00005138 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5139 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump11289f42009-09-09 15:08:12 +00005140
5141 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00005142 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5143 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump11289f42009-09-09 15:08:12 +00005144 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5145 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005146 && "Statement stack mismatch");
5147 Stmts.pop_back();
5148 }
5149 // Handle blocks rewriting.
5150 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5151 if (BDRE->isByRef())
Steve Naroffd9803712009-04-29 16:37:50 +00005152 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofff4b992a2008-10-28 20:29:00 +00005153 }
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005154 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5155 ValueDecl *VD = DRE->getDecl();
5156 if (VD->hasAttr<BlocksAttr>())
5157 return RewriteBlockDeclRefExpr(DRE);
5158 }
5159
Steve Narofff4b992a2008-10-28 20:29:00 +00005160 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff350b6652008-10-30 10:07:53 +00005161 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00005162 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00005163 ReplaceStmt(S, BlockCall);
5164 return BlockCall;
5165 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005166 }
Steve Naroffc989a7b2008-11-03 23:29:32 +00005167 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005168 RewriteCastExpr(CE);
5169 }
5170#if 0
5171 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek5a201952009-02-07 01:47:29 +00005172 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00005173 // Get the new text.
5174 std::string SStr;
5175 llvm::raw_string_ostream Buf(SStr);
Eli Friedman0905f142009-05-30 05:19:26 +00005176 Replacement->printPretty(Buf, *Context);
Steve Narofff4b992a2008-10-28 20:29:00 +00005177 const std::string &Str = Buf.str();
5178
5179 printf("CAST = %s\n", &Str[0]);
5180 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5181 delete S;
5182 return Replacement;
5183 }
5184#endif
5185 // Return this stmt unmodified.
5186 return S;
5187}
5188
Steve Naroffe70a52a2009-12-05 15:55:59 +00005189void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5190 for (RecordDecl::field_iterator i = RD->field_begin(),
5191 e = RD->field_end(); i != e; ++i) {
5192 FieldDecl *FD = *i;
5193 if (isTopLevelBlockPointerType(FD->getType()))
5194 RewriteBlockPointerDecl(FD);
5195 if (FD->getType()->isObjCQualifiedIdType() ||
5196 FD->getType()->isObjCQualifiedInterfaceType())
5197 RewriteObjCQualifiedInterfaceTypes(FD);
5198 }
5199}
5200
Steve Narofff4b992a2008-10-28 20:29:00 +00005201/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5202/// main file of the input.
5203void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5204 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffb1368882008-12-17 00:20:22 +00005205 if (FD->isOverloadedOperator())
5206 return;
Mike Stump11289f42009-09-09 15:08:12 +00005207
Steve Narofff4b992a2008-10-28 20:29:00 +00005208 // Since function prototypes don't have ParmDecl's, we check the function
5209 // prototype. This enables us to rewrite function declarations and
5210 // definitions using the same code.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005211 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005212
Sebastian Redla7b98a72009-04-26 20:35:05 +00005213 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005214 if (CompoundStmt *Body = FD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005215 CurFunctionDef = FD;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005216 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005217 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005218 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005219 Body =
5220 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5221 FD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005222 CurrentBody = 0;
5223 if (PropParentMap) {
5224 delete PropParentMap;
5225 PropParentMap = 0;
5226 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005227 // This synthesizes and inserts the block "impl" struct, invoke function,
5228 // and any copy/dispose helper functions.
5229 InsertBlockLiteralsWithinFunction(FD);
5230 CurFunctionDef = 0;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005231 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005232 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005233 return;
5234 }
5235 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005236 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005237 CurMethodDef = MD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005238 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005239 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005240 Body =
5241 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5242 MD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005243 CurrentBody = 0;
5244 if (PropParentMap) {
5245 delete PropParentMap;
5246 PropParentMap = 0;
5247 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005248 InsertBlockLiteralsWithinMethod(MD);
5249 CurMethodDef = 0;
5250 }
5251 }
5252 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5253 ClassImplementation.push_back(CI);
5254 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5255 CategoryImplementation.push_back(CI);
5256 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5257 RewriteForwardClassDecl(CD);
5258 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5259 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroffa5c0db82008-12-11 21:05:33 +00005260 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005261 RewriteBlockPointerDecl(VD);
Steve Naroffd8907b72008-10-29 18:15:37 +00005262 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005263 CheckFunctionPointerDecl(VD->getType(), VD);
5264 if (VD->getInit()) {
Steve Naroffc989a7b2008-11-03 23:29:32 +00005265 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005266 RewriteCastExpr(CE);
5267 }
5268 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00005269 } else if (VD->getType()->isRecordType()) {
5270 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5271 if (RD->isDefinition())
5272 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005273 }
Steve Naroffd8907b72008-10-29 18:15:37 +00005274 if (VD->getInit()) {
5275 GlobalVarDecl = VD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005276 CollectPropertySetters(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005277 CurrentBody = VD->getInit();
Steve Naroffd8907b72008-10-29 18:15:37 +00005278 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005279 CurrentBody = 0;
5280 if (PropParentMap) {
5281 delete PropParentMap;
5282 PropParentMap = 0;
5283 }
Mike Stump11289f42009-09-09 15:08:12 +00005284 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner86d7d912008-11-24 03:54:41 +00005285 VD->getNameAsCString());
Steve Naroffd8907b72008-10-29 18:15:37 +00005286 GlobalVarDecl = 0;
5287
5288 // This is needed for blocks.
Steve Naroffc989a7b2008-11-03 23:29:32 +00005289 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroffd8907b72008-10-29 18:15:37 +00005290 RewriteCastExpr(CE);
5291 }
5292 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005293 return;
5294 }
5295 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005296 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005297 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005298 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005299 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Steve Naroffe70a52a2009-12-05 15:55:59 +00005300 else if (TD->getUnderlyingType()->isRecordType()) {
5301 RecordDecl *RD = TD->getUnderlyingType()->getAs<RecordType>()->getDecl();
5302 if (RD->isDefinition())
5303 RewriteRecordBody(RD);
5304 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005305 return;
5306 }
5307 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroffe70a52a2009-12-05 15:55:59 +00005308 if (RD->isDefinition())
5309 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005310 return;
5311 }
5312 // Nothing yet.
5313}
5314
Chris Lattnercf169832009-03-28 04:11:33 +00005315void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005316 if (Diags.hasErrorOccurred())
5317 return;
Mike Stump11289f42009-09-09 15:08:12 +00005318
Steve Narofff4b992a2008-10-28 20:29:00 +00005319 RewriteInclude();
Mike Stump11289f42009-09-09 15:08:12 +00005320
Steve Naroffd9803712009-04-29 16:37:50 +00005321 // Here's a great place to add any extra declarations that may be needed.
5322 // Write out meta data for each @protocol(<expr>).
Mike Stump11289f42009-09-09 15:08:12 +00005323 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00005324 E = ProtocolExprDecls.end(); I != E; ++I)
5325 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5326
Mike Stump11289f42009-09-09 15:08:12 +00005327 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Narofff4b992a2008-10-28 20:29:00 +00005328 Preamble.c_str(), Preamble.size(), false);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005329 if (ClassImplementation.size() || CategoryImplementation.size())
5330 RewriteImplementations();
Steve Naroffd9803712009-04-29 16:37:50 +00005331
Steve Narofff4b992a2008-10-28 20:29:00 +00005332 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5333 // we are done.
Mike Stump11289f42009-09-09 15:08:12 +00005334 if (const RewriteBuffer *RewriteBuf =
Steve Narofff4b992a2008-10-28 20:29:00 +00005335 Rewrite.getRewriteBufferFor(MainFileID)) {
5336 //printf("Changed:\n");
5337 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5338 } else {
5339 fprintf(stderr, "No changes\n");
5340 }
Steve Narofff8cfd162008-11-13 20:07:04 +00005341
Steve Naroffd9803712009-04-29 16:37:50 +00005342 if (ClassImplementation.size() || CategoryImplementation.size() ||
5343 ProtocolExprDecls.size()) {
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005344 // Rewrite Objective-c meta data*
5345 std::string ResultStr;
5346 SynthesizeMetaDataIntoBuffer(ResultStr);
5347 // Emit metadata.
5348 *OutFile << ResultStr;
5349 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005350 OutFile->flush();
5351}
5352