blob: 74820905c2c7a5b139497f47bcc083e2d3422a71 [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
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000217 void InsertText(SourceLocation Loc, llvm::StringRef Str,
Steve Naroff00a31762008-03-27 22:29:16 +0000218 bool InsertAfter = true) {
Chris Lattner9cc55f52008-01-31 19:51:04 +0000219 // If insertion succeeded or warning disabled return with no warning.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000220 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
Chris Lattner1780a852008-01-31 19:42:41 +0000221 SilenceRewriteMacroWarning)
222 return;
Mike Stump11289f42009-09-09 15:08:12 +0000223
Chris Lattner1780a852008-01-31 19:42:41 +0000224 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
225 }
Mike Stump11289f42009-09-09 15:08:12 +0000226
Chris Lattner9cc55f52008-01-31 19:51:04 +0000227 void RemoveText(SourceLocation Loc, unsigned StrLen) {
228 // If removal succeeded or warning disabled return with no warning.
229 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
230 return;
Mike Stump11289f42009-09-09 15:08:12 +0000231
Chris Lattner9cc55f52008-01-31 19:51:04 +0000232 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
233 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000234
Chris Lattner9cc55f52008-01-31 19:51:04 +0000235 void ReplaceText(SourceLocation Start, unsigned OrigLength,
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000236 llvm::StringRef Str) {
Chris Lattner9cc55f52008-01-31 19:51:04 +0000237 // If removal succeeded or warning disabled return with no warning.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000238 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
Chris Lattner9cc55f52008-01-31 19:51:04 +0000239 SilenceRewriteMacroWarning)
240 return;
Mike Stump11289f42009-09-09 15:08:12 +0000241
Chris Lattner9cc55f52008-01-31 19:51:04 +0000242 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
243 }
Mike Stump11289f42009-09-09 15:08:12 +0000244
Chris Lattner3c799d72007-10-24 17:06:59 +0000245 // Syntactic Rewriting.
Steve Narofff36987c2007-11-04 22:37:50 +0000246 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000247 void RewriteInclude();
Chris Lattner3c799d72007-10-24 17:06:59 +0000248 void RewriteTabs();
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000249 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffc038b3a2008-12-02 17:36:43 +0000250 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
251 ObjCImplementationDecl *IMD,
252 ObjCCategoryImplDecl *CID);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000253 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000254 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000255 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +0000256 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
257 ValueDecl *VD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000258 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
259 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
260 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
261 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000262 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000263 void RewriteFunctionDecl(FunctionDecl *FD);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000264 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000265 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +0000266 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff873bd842008-07-29 18:15:38 +0000267 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroff50d42052007-11-01 13:24:47 +0000268 bool needToScanForQualifiers(QualType T);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000269 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff7fa2f042007-11-15 10:28:18 +0000270 QualType getSuperStructType();
Steve Naroffce8e8862008-03-15 00:55:56 +0000271 QualType getConstantStringStructType();
Steve Naroffcd92aeb2008-05-31 14:15:04 +0000272 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump11289f42009-09-09 15:08:12 +0000273
Chris Lattner3c799d72007-10-24 17:06:59 +0000274 // Expression Rewriting.
Steve Naroff20113382007-11-09 15:20:18 +0000275 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroff4588d0f2008-12-04 16:24:46 +0000276 void CollectPropertySetters(Stmt *S);
Mike Stump11289f42009-09-09 15:08:12 +0000277
Steve Naroff1042ff32008-12-08 16:43:47 +0000278 Stmt *CurrentBody;
279 ParentMap *PropParentMap; // created lazily.
Mike Stump11289f42009-09-09 15:08:12 +0000280
Chris Lattner69534692007-10-24 16:57:36 +0000281 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +0000282 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart,
283 bool &replaced);
284 Stmt *RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced);
Steve Naroff4588d0f2008-12-04 16:24:46 +0000285 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Mike Stump11289f42009-09-09 15:08:12 +0000286 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroff08628db2008-12-09 12:56:34 +0000287 SourceRange SrcRange);
Steve Naroffe4f9b232007-11-05 14:50:49 +0000288 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner69534692007-10-24 16:57:36 +0000289 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffa397efd2007-11-03 11:27:19 +0000290 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian33c0e812007-12-07 18:47:10 +0000291 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffec60b432009-12-05 21:43:12 +0000292 void WarnAboutReturnGotoStmts(Stmt *S);
293 void HasReturnStmts(Stmt *S, bool &hasReturns);
294 void RewriteTryReturnStmts(Stmt *S);
295 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000296 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian284011b2008-01-29 22:59:37 +0000297 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000298 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
299 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
300 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattnera779d692008-01-31 05:10:40 +0000301 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
302 SourceLocation OrigEnd);
Mike Stump11289f42009-09-09 15:08:12 +0000303 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Steve Naroff574440f2007-10-24 22:48:43 +0000304 Expr **args, unsigned nargs);
Fariborz Jahanian965a8962008-01-08 22:06:28 +0000305 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +0000306 Stmt *RewriteBreakStmt(BreakStmt *S);
307 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian965a8962008-01-08 22:06:28 +0000308 void SynthCountByEnumWithState(std::string &buf);
Mike Stump11289f42009-09-09 15:08:12 +0000309
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000310 void SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +0000311 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000312 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +0000313 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000314 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000315 void SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +0000316 void SynthGetMetaClassFunctionDecl();
Fariborz Jahanian31e18502007-12-04 21:47:40 +0000317 void SynthSelGetUidFunctionDecl();
Steve Naroff17978c42008-03-11 17:37:02 +0000318 void SynthSuperContructorFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000319
Chris Lattner3c799d72007-10-24 17:06:59 +0000320 // Metadata emission.
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000321 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000322 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000323
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000324 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000325 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000326
Douglas Gregor29bd76f2009-04-23 01:02:12 +0000327 template<typename MethodIterator>
328 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
329 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +0000330 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +0000331 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +0000332 const char *ClassName,
333 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000334
Steve Naroffd9803712009-04-29 16:37:50 +0000335 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
336 const char *prefix,
337 const char *ClassName,
338 std::string &Result);
339 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Mike Stump11289f42009-09-09 15:08:12 +0000340 const char *prefix,
Steve Naroffd9803712009-04-29 16:37:50 +0000341 const char *ClassName,
342 std::string &Result);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000343 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000344 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000345 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
346 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000347 std::string &Result);
Steve Narofff8cfd162008-11-13 20:07:04 +0000348 void RewriteImplementations();
349 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000350
Steve Naroff677ab3a2008-10-27 17:20:55 +0000351 // Block rewriting.
Mike Stump11289f42009-09-09 15:08:12 +0000352 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000353 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump11289f42009-09-09 15:08:12 +0000354
Steve Naroff677ab3a2008-10-27 17:20:55 +0000355 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
356 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump11289f42009-09-09 15:08:12 +0000357
358 // Block specific rewrite rules.
Steve Naroff677ab3a2008-10-27 17:20:55 +0000359 void RewriteBlockCall(CallExpr *Exp);
360 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000361 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahaniane3891582010-01-05 18:04:40 +0000362 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +0000363 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000364 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump11289f42009-09-09 15:08:12 +0000365
366 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Steve Naroff677ab3a2008-10-27 17:20:55 +0000367 const char *funcName, std::string Tag);
Mike Stump11289f42009-09-09 15:08:12 +0000368 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Steve Naroff677ab3a2008-10-27 17:20:55 +0000369 const char *funcName, std::string Tag);
Steve Naroff30484702009-12-06 21:14:13 +0000370 std::string SynthesizeBlockImpl(BlockExpr *CE,
371 std::string Tag, std::string Desc);
372 std::string SynthesizeBlockDescriptor(std::string DescTag,
373 std::string ImplTag,
374 int i, const char *funcName,
375 unsigned hasCopy);
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +0000376 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000377 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000378 const char *FunName);
Steve Naroffe70a52a2009-12-05 15:55:59 +0000379 void RewriteRecordBody(RecordDecl *RD);
Mike Stump11289f42009-09-09 15:08:12 +0000380
Steve Naroff677ab3a2008-10-27 17:20:55 +0000381 void CollectBlockDeclRefInfo(BlockExpr *Exp);
382 void GetBlockCallExprs(Stmt *S);
383 void GetBlockDeclRefExprs(Stmt *S);
Mike Stump11289f42009-09-09 15:08:12 +0000384
Steve Naroff677ab3a2008-10-27 17:20:55 +0000385 // We avoid calling Type::isBlockPointerType(), since it operates on the
386 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek5a201952009-02-07 01:47:29 +0000387 bool isTopLevelBlockPointerType(QualType T) {
388 return isa<BlockPointerType>(T);
389 }
Mike Stump11289f42009-09-09 15:08:12 +0000390
Steve Naroff677ab3a2008-10-27 17:20:55 +0000391 // FIXME: This predicate seems like it would be useful to add to ASTContext.
392 bool isObjCType(QualType T) {
393 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
394 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000395
Steve Naroff677ab3a2008-10-27 17:20:55 +0000396 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000397
Steve Naroff677ab3a2008-10-27 17:20:55 +0000398 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
399 OCT == Context->getCanonicalType(Context->getObjCClassType()))
400 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000401
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000402 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +0000403 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Narofffb4330f2009-06-17 22:40:22 +0000404 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff677ab3a2008-10-27 17:20:55 +0000405 return true;
406 }
407 return false;
408 }
409 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek5a201952009-02-07 01:47:29 +0000410 void GetExtentOfArgList(const char *Name, const char *&LParen,
411 const char *&RParen);
Steve Naroffc989a7b2008-11-03 23:29:32 +0000412 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump11289f42009-09-09 15:08:12 +0000413
Steve Narofff4b992a2008-10-28 20:29:00 +0000414 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroffd8907b72008-10-29 18:15:37 +0000415 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Mike Stump11289f42009-09-09 15:08:12 +0000416
Steve Naroffd9803712009-04-29 16:37:50 +0000417 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump11289f42009-09-09 15:08:12 +0000418 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroffd9803712009-04-29 16:37:50 +0000419 if (From[i] == '"')
420 To += "\\\"";
421 else
422 To += From[i];
423 }
424 }
Chris Lattnere99c8322007-10-11 00:43:27 +0000425 };
John McCall97513962010-01-15 18:39:57 +0000426
427 // Helper function: create a CStyleCastExpr with trivial type source info.
428 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
429 CastExpr::CastKind Kind, Expr *E) {
430 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
431 return new (Ctx) CStyleCastExpr(Ty, Kind, E, TInfo,
432 SourceLocation(), SourceLocation());
433 }
Chris Lattnere99c8322007-10-11 00:43:27 +0000434}
435
Mike Stump11289f42009-09-09 15:08:12 +0000436void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
437 NamedDecl *D) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000438 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000439 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +0000440 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +0000441 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +0000442 // All the args are checked/rewritten. Don't call twice!
443 RewriteBlockPointerDecl(D);
444 break;
445 }
446 }
447}
448
449void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000450 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +0000451 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000452 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000453}
454
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000455static bool IsHeaderFile(const std::string &Filename) {
456 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump11289f42009-09-09 15:08:12 +0000457
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000458 if (DotPos == std::string::npos) {
459 // no file extension
Mike Stump11289f42009-09-09 15:08:12 +0000460 return false;
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000461 }
Mike Stump11289f42009-09-09 15:08:12 +0000462
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000463 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
464 // C header: .h
465 // C++ header: .hh or .H;
466 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump11289f42009-09-09 15:08:12 +0000467}
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000468
Eli Friedman94cf21e2009-05-18 22:20:00 +0000469RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000470 Diagnostic &D, const LangOptions &LOpts,
471 bool silenceMacroWarn)
472 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
473 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Narofff9e7c902008-03-28 22:26:09 +0000474 IsHeader = IsHeaderFile(inFile);
Mike Stump11289f42009-09-09 15:08:12 +0000475 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Narofff9e7c902008-03-28 22:26:09 +0000476 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump11289f42009-09-09 15:08:12 +0000477 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek5a201952009-02-07 01:47:29 +0000478 "rewriter doesn't support user-specified control flow semantics "
479 "for @try/@finally (code may not execute properly)");
Steve Narofff9e7c902008-03-28 22:26:09 +0000480}
481
Eli Friedmana63ab2d2009-05-18 22:29:17 +0000482ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
483 llvm::raw_ostream* OS,
Mike Stump11289f42009-09-09 15:08:12 +0000484 Diagnostic &Diags,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000485 const LangOptions &LOpts,
486 bool SilenceRewriteMacroWarning) {
487 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere9c810c2007-11-30 22:25:36 +0000488}
Chris Lattnere99c8322007-10-11 00:43:27 +0000489
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000490void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner187f6262008-01-31 19:38:44 +0000491 Context = &context;
492 SM = &Context->getSourceManager();
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +0000493 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner187f6262008-01-31 19:38:44 +0000494 MsgSendFunctionDecl = 0;
495 MsgSendSuperFunctionDecl = 0;
496 MsgSendStretFunctionDecl = 0;
497 MsgSendSuperStretFunctionDecl = 0;
498 MsgSendFpretFunctionDecl = 0;
499 GetClassFunctionDecl = 0;
500 GetMetaClassFunctionDecl = 0;
501 SelGetUidFunctionDecl = 0;
502 CFStringFunctionDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000503 ConstantStringClassReference = 0;
504 NSStringRecord = 0;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000505 CurMethodDef = 0;
506 CurFunctionDef = 0;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000507 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000508 GlobalVarDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000509 SuperStructDecl = 0;
Steve Naroffd9803712009-04-29 16:37:50 +0000510 ProtocolTypeDecl = 0;
Steve Naroff60a9ef62008-03-27 22:59:54 +0000511 ConstantStringDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000512 BcLabelCount = 0;
Steve Naroff17978c42008-03-11 17:37:02 +0000513 SuperContructorFunctionDecl = 0;
Steve Naroffce8e8862008-03-15 00:55:56 +0000514 NumObjCStringLiterals = 0;
Steve Narofff1ab6002008-12-08 20:01:41 +0000515 PropParentMap = 0;
516 CurrentBody = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000517 DisableReplaceStmt = false;
Fariborz Jahanianbc6811c2010-01-07 22:51:18 +0000518 objc_impl_method = false;
Mike Stump11289f42009-09-09 15:08:12 +0000519
Chris Lattner187f6262008-01-31 19:38:44 +0000520 // Get the ID and start/end of the main file.
521 MainFileID = SM->getMainFileID();
522 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
523 MainFileStart = MainBuf->getBufferStart();
524 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000525
Chris Lattner184e65d2009-04-14 23:22:57 +0000526 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump11289f42009-09-09 15:08:12 +0000527
Chris Lattner187f6262008-01-31 19:38:44 +0000528 // declaring objc_selector outside the parameter list removes a silly
529 // scope related warning...
Steve Naroff00a31762008-03-27 22:29:16 +0000530 if (IsHeader)
Steve Narofffcc6fd52009-02-03 20:39:18 +0000531 Preamble = "#pragma once\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000532 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff6ab6dc72008-12-23 20:11:22 +0000533 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroff00a31762008-03-27 22:29:16 +0000534 Preamble += "struct objc_object *superClass; ";
Steve Naroff17978c42008-03-11 17:37:02 +0000535 if (LangOpts.Microsoft) {
536 // Add a constructor for creating temporary objects.
Ted Kremenek5a201952009-02-07 01:47:29 +0000537 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
538 ": ";
Steve Naroff00a31762008-03-27 22:29:16 +0000539 Preamble += "object(o), superClass(s) {} ";
Steve Naroff17978c42008-03-11 17:37:02 +0000540 }
Steve Naroff00a31762008-03-27 22:29:16 +0000541 Preamble += "};\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000542 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
543 Preamble += "typedef struct objc_object Protocol;\n";
544 Preamble += "#define _REWRITER_typedef_Protocol\n";
545 Preamble += "#endif\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000546 if (LangOpts.Microsoft) {
547 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
548 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
549 } else
550 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
551 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroff00a31762008-03-27 22:29:16 +0000552 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000553 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroff00a31762008-03-27 22:29:16 +0000554 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000555 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000556 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000557 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000558 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000559 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroff00a31762008-03-27 22:29:16 +0000560 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000561 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000562 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000563 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000564 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000565 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
566 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
567 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
568 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
569 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroffd30f8c52008-05-09 21:17:56 +0000570 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff8dd15252008-07-16 18:58:11 +0000571 // @synchronized hooks.
Steve Narofff122ff02008-12-08 17:30:33 +0000572 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
573 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
574 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000575 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
576 Preamble += "struct __objcFastEnumerationState {\n\t";
577 Preamble += "unsigned long state;\n\t";
Steve Naroff4dbab8a2008-04-04 22:58:22 +0000578 Preamble += "void **itemsPtr;\n\t";
Steve Naroff00a31762008-03-27 22:29:16 +0000579 Preamble += "unsigned long *mutationsPtr;\n\t";
580 Preamble += "unsigned long extra[5];\n};\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000581 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000582 Preamble += "#define __FASTENUMERATIONSTATE\n";
583 Preamble += "#endif\n";
584 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
585 Preamble += "struct __NSConstantStringImpl {\n";
586 Preamble += " int *isa;\n";
587 Preamble += " int flags;\n";
588 Preamble += " char *str;\n";
589 Preamble += " long length;\n";
590 Preamble += "};\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000591 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
592 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
593 Preamble += "#else\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000594 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000595 Preamble += "#endif\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000596 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
597 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000598 // Blocks preamble.
599 Preamble += "#ifndef BLOCK_IMPL\n";
600 Preamble += "#define BLOCK_IMPL\n";
601 Preamble += "struct __block_impl {\n";
602 Preamble += " void *isa;\n";
603 Preamble += " int Flags;\n";
Steve Naroff30484702009-12-06 21:14:13 +0000604 Preamble += " int Reserved;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000605 Preamble += " void *FuncPtr;\n";
606 Preamble += "};\n";
Steve Naroff61d879e2008-12-16 15:50:30 +0000607 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroff287a2bf2009-12-06 01:52:22 +0000608 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000609 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_assign(void *, const void *, const int);\n";
610 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
611 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
612 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
613 Preamble += "#else\n";
Steve Naroff7bf01ea2010-01-05 18:09:31 +0000614 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
615 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000616 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
617 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
618 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000619 Preamble += "#endif\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000620 if (LangOpts.Microsoft) {
Steve Narofff122ff02008-12-08 17:30:33 +0000621 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
622 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000623 Preamble += "#define __attribute__(X)\n";
Fariborz Jahanianf0462ff2010-01-15 22:29:39 +0000624 Preamble += "#define __weak\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000625 }
Fariborz Jahanian7fac6552010-01-05 19:21:35 +0000626 else {
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000627 Preamble += "#define __block\n";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +0000628 Preamble += "#define __weak\n";
629 }
Chris Lattner187f6262008-01-31 19:38:44 +0000630}
631
632
Chris Lattner3c799d72007-10-24 17:06:59 +0000633//===----------------------------------------------------------------------===//
634// Top Level Driver Code
635//===----------------------------------------------------------------------===//
636
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000637void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremenek31e7f0f2010-02-05 21:28:51 +0000638 if (Diags.hasErrorOccurred())
639 return;
640
Chris Lattner0bd1c972007-10-16 21:07:07 +0000641 // Two cases: either the decl could be in the main file, or it could be in a
642 // #included file. If the former, rewrite it now. If the later, check to see
643 // if we rewrote the #include/#import.
644 SourceLocation Loc = D->getLocation();
Chris Lattner8a425862009-01-16 07:36:28 +0000645 Loc = SM->getInstantiationLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000646
Chris Lattner0bd1c972007-10-16 21:07:07 +0000647 // If this is for a builtin, ignore it.
648 if (Loc.isInvalid()) return;
649
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000650 // Look for built-in declarations that we need to refer during the rewrite.
651 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000652 RewriteFunctionDecl(FD);
Steve Naroff08899ff2008-04-15 22:42:06 +0000653 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000654 // declared in <Foundation/NSString.h>
Chris Lattner86d7d912008-11-24 03:54:41 +0000655 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000656 ConstantStringClassReference = FVD;
657 return;
658 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000659 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff161a92b2007-10-26 20:53:56 +0000660 RewriteInterfaceDecl(MD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000661 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000662 RewriteCategoryDecl(CD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000663 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff921385f2007-10-30 16:42:30 +0000664 RewriteProtocolDecl(PD);
Mike Stump11289f42009-09-09 15:08:12 +0000665 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000666 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000667 RewriteForwardProtocolDecl(FP);
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000668 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
669 // Recurse into linkage specifications
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000670 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
671 DIEnd = LSD->decls_end();
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000672 DI != DIEnd; ++DI)
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000673 HandleTopLevelSingleDecl(*DI);
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000674 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000675 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekd61ed3b2008-04-14 21:24:13 +0000676 if (SM->isFromMainFile(Loc))
Chris Lattner0bd1c972007-10-16 21:07:07 +0000677 return HandleDeclInMainFile(D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000678}
679
Chris Lattner3c799d72007-10-24 17:06:59 +0000680//===----------------------------------------------------------------------===//
681// Syntactic (non-AST) Rewriting Code
682//===----------------------------------------------------------------------===//
683
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000684void RewriteObjC::RewriteInclude() {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000685 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000686 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
687 const char *MainBufStart = MainBuf.first;
688 const char *MainBufEnd = MainBuf.second;
689 size_t ImportLen = strlen("import");
Mike Stump11289f42009-09-09 15:08:12 +0000690
Fariborz Jahanian137d6932008-01-19 01:03:17 +0000691 // Loop over the whole file, looking for includes.
Fariborz Jahanian80258362008-01-19 00:30:35 +0000692 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
693 if (*BufPtr == '#') {
694 if (++BufPtr == MainBufEnd)
695 return;
696 while (*BufPtr == ' ' || *BufPtr == '\t')
697 if (++BufPtr == MainBufEnd)
698 return;
699 if (!strncmp(BufPtr, "import", ImportLen)) {
700 // replace import with include
Mike Stump11289f42009-09-09 15:08:12 +0000701 SourceLocation ImportLoc =
Fariborz Jahanian80258362008-01-19 00:30:35 +0000702 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000703 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian80258362008-01-19 00:30:35 +0000704 BufPtr += ImportLen;
705 }
706 }
707 }
Chris Lattner0bd1c972007-10-16 21:07:07 +0000708}
709
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000710void RewriteObjC::RewriteTabs() {
Chris Lattner3c799d72007-10-24 17:06:59 +0000711 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
712 const char *MainBufStart = MainBuf.first;
713 const char *MainBufEnd = MainBuf.second;
Mike Stump11289f42009-09-09 15:08:12 +0000714
Chris Lattner3c799d72007-10-24 17:06:59 +0000715 // Loop over the whole file, looking for tabs.
716 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
717 if (*BufPtr != '\t')
718 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000719
Chris Lattner3c799d72007-10-24 17:06:59 +0000720 // Okay, we found a tab. This tab will turn into at least one character,
721 // but it depends on which 'virtual column' it is in. Compute that now.
722 unsigned VCol = 0;
723 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
724 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
725 ++VCol;
Mike Stump11289f42009-09-09 15:08:12 +0000726
Chris Lattner3c799d72007-10-24 17:06:59 +0000727 // Okay, now that we know the virtual column, we know how many spaces to
728 // insert. We assume 8-character tab-stops.
729 unsigned Spaces = 8-(VCol & 7);
Mike Stump11289f42009-09-09 15:08:12 +0000730
Chris Lattner3c799d72007-10-24 17:06:59 +0000731 // Get the location of the tab.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000732 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
733 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Mike Stump11289f42009-09-09 15:08:12 +0000734
Chris Lattner3c799d72007-10-24 17:06:59 +0000735 // Rewrite the single tab character into a sequence of spaces.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000736 ReplaceText(TabLoc, 1, llvm::StringRef(" ", Spaces));
Chris Lattner3c799d72007-10-24 17:06:59 +0000737 }
Chris Lattner16a0de42007-10-11 18:38:32 +0000738}
739
Steve Naroff9af94912008-12-02 15:48:25 +0000740static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
741 ObjCIvarDecl *OID) {
742 std::string S;
743 S = "((struct ";
744 S += ClassDecl->getIdentifier()->getName();
745 S += "_IMPL *)self)->";
Daniel Dunbar70e7ead2009-10-18 20:26:27 +0000746 S += OID->getName();
Steve Naroff9af94912008-12-02 15:48:25 +0000747 return S;
748}
749
Steve Naroffc038b3a2008-12-02 17:36:43 +0000750void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
751 ObjCImplementationDecl *IMD,
752 ObjCCategoryImplDecl *CID) {
Steve Naroffe1908e32008-12-01 20:33:01 +0000753 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000754 InsertText(startLoc, "// ");
Steve Naroff9af94912008-12-02 15:48:25 +0000755 const char *startBuf = SM->getCharacterData(startLoc);
756 assert((*startBuf == '@') && "bogus @synthesize location");
757 const char *semiBuf = strchr(startBuf, ';');
758 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek5a201952009-02-07 01:47:29 +0000759 SourceLocation onePastSemiLoc =
760 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroff9af94912008-12-02 15:48:25 +0000761
762 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
763 return; // FIXME: is this correct?
Mike Stump11289f42009-09-09 15:08:12 +0000764
Steve Naroff9af94912008-12-02 15:48:25 +0000765 // Generate the 'getter' function.
Steve Naroff9af94912008-12-02 15:48:25 +0000766 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroff9af94912008-12-02 15:48:25 +0000767 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroff9af94912008-12-02 15:48:25 +0000768 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000769
Steve Naroff003d00e2008-12-02 16:05:55 +0000770 if (!OID)
771 return;
Mike Stump11289f42009-09-09 15:08:12 +0000772
Steve Naroff003d00e2008-12-02 16:05:55 +0000773 std::string Getr;
774 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
775 Getr += "{ ";
776 // Synthesize an explicit cast to gain access to the ivar.
Mike Stump11289f42009-09-09 15:08:12 +0000777 // FIXME: deal with code generation implications for various property
778 // attributes (copy, retain, nonatomic).
Steve Naroff06297042008-12-02 17:54:50 +0000779 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroff003d00e2008-12-02 16:05:55 +0000780 Getr += "return " + getIvarAccessString(ClassDecl, OID);
781 Getr += "; }";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000782 InsertText(onePastSemiLoc, Getr);
Steve Naroff9af94912008-12-02 15:48:25 +0000783 if (PD->isReadOnly())
784 return;
Mike Stump11289f42009-09-09 15:08:12 +0000785
Steve Naroff9af94912008-12-02 15:48:25 +0000786 // Generate the 'setter' function.
787 std::string Setr;
788 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroff9af94912008-12-02 15:48:25 +0000789 Setr += "{ ";
Steve Naroff003d00e2008-12-02 16:05:55 +0000790 // Synthesize an explicit cast to initialize the ivar.
Mike Stump11289f42009-09-09 15:08:12 +0000791 // FIXME: deal with code generation implications for various property
792 // attributes (copy, retain, nonatomic).
Steve Narofff326f402008-12-03 00:56:33 +0000793 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroff003d00e2008-12-02 16:05:55 +0000794 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000795 Setr += PD->getNameAsCString();
Steve Naroff003d00e2008-12-02 16:05:55 +0000796 Setr += "; }";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000797 InsertText(onePastSemiLoc, Setr);
Steve Naroffe1908e32008-12-01 20:33:01 +0000798}
Chris Lattner16a0de42007-10-11 18:38:32 +0000799
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000800void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattner3c799d72007-10-24 17:06:59 +0000801 // Get the start location and compute the semi location.
802 SourceLocation startLoc = ClassDecl->getLocation();
803 const char *startBuf = SM->getCharacterData(startLoc);
804 const char *semiPtr = strchr(startBuf, ';');
Mike Stump11289f42009-09-09 15:08:12 +0000805
Chris Lattner3c799d72007-10-24 17:06:59 +0000806 // Translate to typedef's that forward reference structs with the same name
807 // as the class. As a convenience, we include the original declaration
808 // as a comment.
809 std::string typedefString;
Fariborz Jahanian1c2cb6d2010-01-11 22:48:40 +0000810 typedefString += "// @class ";
811 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
812 I != E; ++I) {
813 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
814 typedefString += ForwardDecl->getNameAsString();
815 if (I+1 != E)
816 typedefString += ", ";
817 else
818 typedefString += ";\n";
819 }
820
Chris Lattner9ee23b72009-02-20 18:04:31 +0000821 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
822 I != E; ++I) {
Ted Kremenek9b124e12009-11-18 00:28:11 +0000823 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff1b232132007-11-09 12:50:28 +0000824 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000825 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000826 typedefString += "\n";
827 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000828 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000829 typedefString += "\n";
Steve Naroff98eb8d12007-11-05 14:36:37 +0000830 typedefString += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000831 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000832 typedefString += ";\n#endif\n";
Steve Naroff574440f2007-10-24 22:48:43 +0000833 }
Mike Stump11289f42009-09-09 15:08:12 +0000834
Steve Naroff574440f2007-10-24 22:48:43 +0000835 // Replace the @class with typedefs corresponding to the classes.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000836 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
Chris Lattner3c799d72007-10-24 17:06:59 +0000837}
838
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000839void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000840 // When method is a synthesized one, such as a getter/setter there is
841 // nothing to rewrite.
842 if (Method->isSynthesized())
843 return;
Steve Naroff3ce37a62007-12-14 23:37:57 +0000844 SourceLocation LocStart = Method->getLocStart();
845 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000846
Chris Lattner88ea93e2009-02-04 01:06:56 +0000847 if (SM->getInstantiationLineNumber(LocEnd) >
848 SM->getInstantiationLineNumber(LocStart)) {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000849 InsertText(LocStart, "#if 0\n");
850 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff3ce37a62007-12-14 23:37:57 +0000851 } else {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000852 InsertText(LocStart, "// ");
Steve Naroff5448cf62007-10-30 13:30:57 +0000853 }
854}
855
Mike Stump11289f42009-09-09 15:08:12 +0000856void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000857 SourceLocation Loc = prop->getAtLoc();
Mike Stump11289f42009-09-09 15:08:12 +0000858
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000859 ReplaceText(Loc, 0, "// ");
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000860 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahaniane8a30162007-11-07 00:09:37 +0000861}
862
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000863void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000864 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000865
Steve Naroff5448cf62007-10-30 13:30:57 +0000866 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000867 ReplaceText(LocStart, 0, "// ");
Mike Stump11289f42009-09-09 15:08:12 +0000868
Fariborz Jahanian68ebe632010-02-10 01:15:09 +0000869 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
870 E = CatDecl->prop_end(); I != E; ++I)
871 RewriteProperty(*I);
872
Mike Stump11289f42009-09-09 15:08:12 +0000873 for (ObjCCategoryDecl::instmeth_iterator
874 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000875 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000876 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +0000877 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000878 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000879 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000880 RewriteMethodDeclaration(*I);
881
Steve Naroff5448cf62007-10-30 13:30:57 +0000882 // Lastly, comment out the @end.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000883 ReplaceText(CatDecl->getAtEndRange().getBegin(), 0, "// ");
Steve Naroff5448cf62007-10-30 13:30:57 +0000884}
885
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000886void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000887 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Mike Stump11289f42009-09-09 15:08:12 +0000888
Steve Narofff921385f2007-10-30 16:42:30 +0000889 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000890
Steve Narofff921385f2007-10-30 16:42:30 +0000891 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000892 ReplaceText(LocStart, 0, "// ");
Mike Stump11289f42009-09-09 15:08:12 +0000893
894 for (ObjCProtocolDecl::instmeth_iterator
895 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000896 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000897 RewriteMethodDeclaration(*I);
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000898 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000899 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000900 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000901 RewriteMethodDeclaration(*I);
902
Steve Narofff921385f2007-10-30 16:42:30 +0000903 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +0000904 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000905 ReplaceText(LocEnd, 0, "// ");
Steve Naroffa509f042007-11-14 15:03:57 +0000906
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000907 // Must comment out @optional/@required
908 const char *startBuf = SM->getCharacterData(LocStart);
909 const char *endBuf = SM->getCharacterData(LocEnd);
910 for (const char *p = startBuf; p < endBuf; p++) {
911 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Steve Naroffa509f042007-11-14 15:03:57 +0000912 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000913 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump11289f42009-09-09 15:08:12 +0000914
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000915 }
916 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Steve Naroffa509f042007-11-14 15:03:57 +0000917 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000918 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump11289f42009-09-09 15:08:12 +0000919
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000920 }
921 }
Steve Narofff921385f2007-10-30 16:42:30 +0000922}
923
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000924void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000925 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffc17b0562007-11-14 03:37:28 +0000926 if (LocStart.isInvalid())
927 assert(false && "Invalid SourceLocation");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000928 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000929 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000930}
931
Mike Stump11289f42009-09-09 15:08:12 +0000932void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000933 std::string &ResultStr) {
Steve Naroff295570a2008-10-30 12:09:33 +0000934 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroffb067bbd2008-07-16 14:40:40 +0000935 const FunctionType *FPRetType = 0;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000936 ResultStr += "\nstatic ";
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000937 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +0000938 ResultStr += "id";
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000939 else if (OMD->getResultType()->isFunctionPointerType() ||
940 OMD->getResultType()->isBlockPointerType()) {
Steve Naroffb067bbd2008-07-16 14:40:40 +0000941 // needs special handling, since pointer-to-functions have special
942 // syntax (where a decaration models use).
943 QualType retType = OMD->getResultType();
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000944 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000945 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000946 PointeeTy = PT->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000947 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000948 PointeeTy = BPT->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +0000949 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000950 ResultStr += FPRetType->getResultType().getAsString();
951 ResultStr += "(*";
Steve Naroffb067bbd2008-07-16 14:40:40 +0000952 }
953 } else
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +0000954 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian7262fca2008-01-10 01:39:52 +0000955 ResultStr += " ";
Mike Stump11289f42009-09-09 15:08:12 +0000956
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000957 // Unique method name
Fariborz Jahanian56338352007-11-13 21:02:00 +0000958 std::string NameStr;
Mike Stump11289f42009-09-09 15:08:12 +0000959
Douglas Gregorffca3a22009-01-09 17:18:27 +0000960 if (OMD->isInstanceMethod())
Fariborz Jahanian56338352007-11-13 21:02:00 +0000961 NameStr += "_I_";
962 else
963 NameStr += "_C_";
Mike Stump11289f42009-09-09 15:08:12 +0000964
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000965 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +0000966 NameStr += "_";
Mike Stump11289f42009-09-09 15:08:12 +0000967
968 if (ObjCCategoryImplDecl *CID =
Steve Naroff11b387f2009-01-08 19:41:02 +0000969 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000970 NameStr += CID->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +0000971 NameStr += "_";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000972 }
Mike Stump11289f42009-09-09 15:08:12 +0000973 // Append selector names, replacing ':' with '_'
Chris Lattnere4b95692008-11-24 03:33:13 +0000974 {
975 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000976 int len = selString.size();
977 for (int i = 0; i < len; i++)
978 if (selString[i] == ':')
979 selString[i] = '_';
Fariborz Jahanian56338352007-11-13 21:02:00 +0000980 NameStr += selString;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000981 }
Fariborz Jahanian56338352007-11-13 21:02:00 +0000982 // Remember this name for metadata emission
983 MethodInternalNames[OMD] = NameStr;
984 ResultStr += NameStr;
Mike Stump11289f42009-09-09 15:08:12 +0000985
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000986 // Rewrite arguments
987 ResultStr += "(";
Mike Stump11289f42009-09-09 15:08:12 +0000988
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000989 // invisible arguments
Douglas Gregorffca3a22009-01-09 17:18:27 +0000990 if (OMD->isInstanceMethod()) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000991 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000992 selfTy = Context->getPointerType(selfTy);
Steve Naroffdc5b6b22008-03-12 00:25:36 +0000993 if (!LangOpts.Microsoft) {
994 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
995 ResultStr += "struct ";
996 }
997 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000998 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +0000999 ResultStr += " *";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001000 }
1001 else
Steve Naroffd9803712009-04-29 16:37:50 +00001002 ResultStr += Context->getObjCClassType().getAsString();
Mike Stump11289f42009-09-09 15:08:12 +00001003
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001004 ResultStr += " self, ";
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001005 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001006 ResultStr += " _cmd";
Mike Stump11289f42009-09-09 15:08:12 +00001007
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001008 // Method arguments.
Chris Lattnera4997152009-02-20 18:43:26 +00001009 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1010 E = OMD->param_end(); PI != E; ++PI) {
1011 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001012 ResultStr += ", ";
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001013 if (PDecl->getType()->isObjCQualifiedIdType()) {
1014 ResultStr += "id ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001015 ResultStr += PDecl->getNameAsString();
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001016 } else {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001017 std::string Name = PDecl->getNameAsString();
Steve Naroffa5c0db82008-12-11 21:05:33 +00001018 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroff44df6a22008-10-30 14:45:29 +00001019 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001020 const BlockPointerType *BPT = PDecl->getType()->getAs<BlockPointerType>();
Douglas Gregor7de59662009-05-29 20:38:28 +00001021 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name,
1022 Context->PrintingPolicy);
Steve Naroff44df6a22008-10-30 14:45:29 +00001023 } else
Douglas Gregor7de59662009-05-29 20:38:28 +00001024 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001025 ResultStr += Name;
1026 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001027 }
Fariborz Jahanianeab81cd2008-01-21 20:14:23 +00001028 if (OMD->isVariadic())
1029 ResultStr += ", ...";
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001030 ResultStr += ") ";
Mike Stump11289f42009-09-09 15:08:12 +00001031
Steve Naroffb067bbd2008-07-16 14:40:40 +00001032 if (FPRetType) {
1033 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump11289f42009-09-09 15:08:12 +00001034
Steve Naroffb067bbd2008-07-16 14:40:40 +00001035 // Now, emit the argument types (if any).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001036 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001037 ResultStr += "(";
1038 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1039 if (i) ResultStr += ", ";
1040 std::string ParamStr = FT->getArgType(i).getAsString();
1041 ResultStr += ParamStr;
1042 }
1043 if (FT->isVariadic()) {
1044 if (FT->getNumArgs()) ResultStr += ", ";
1045 ResultStr += "...";
1046 }
1047 ResultStr += ")";
1048 } else {
1049 ResultStr += "()";
1050 }
1051 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001052}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001053void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001054 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1055 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump11289f42009-09-09 15:08:12 +00001056
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001057 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Mike Stump11289f42009-09-09 15:08:12 +00001058
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001059 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001060 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1061 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001062 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001063 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001064 ObjCMethodDecl *OMD = *I;
1065 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001066 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001067 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redla7b98a72009-04-26 20:35:05 +00001068
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001069 const char *startBuf = SM->getCharacterData(LocStart);
1070 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001071 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001072 }
Mike Stump11289f42009-09-09 15:08:12 +00001073
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001074 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001075 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1076 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001077 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001078 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001079 ObjCMethodDecl *OMD = *I;
1080 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001081 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001082 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +00001083
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001084 const char *startBuf = SM->getCharacterData(LocStart);
1085 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001086 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001087 }
Steve Naroffe1908e32008-12-01 20:33:01 +00001088 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001089 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001090 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001091 I != E; ++I) {
Steve Naroffc038b3a2008-12-02 17:36:43 +00001092 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffe1908e32008-12-01 20:33:01 +00001093 }
1094
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001095 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001096}
1097
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001098void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffc5484042007-10-30 02:23:23 +00001099 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001100 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff2f55b982007-11-01 03:35:41 +00001101 // we haven't seen a forward decl - generate a typedef.
Steve Naroff03f27672007-11-14 23:02:56 +00001102 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001103 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001104 ResultStr += "\n";
1105 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001106 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001107 ResultStr += "\n";
Steve Naroffa1e115e2008-03-10 23:16:54 +00001108 ResultStr += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001109 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001110 ResultStr += ";\n#endif\n";
Steve Naroff2f55b982007-11-01 03:35:41 +00001111 // Mark this typedef as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001112 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff2f55b982007-11-01 03:35:41 +00001113 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001114 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump11289f42009-09-09 15:08:12 +00001115
1116 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001117 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff0c0f5ba2009-01-11 01:06:09 +00001118 RewriteProperty(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001119 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001120 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001121 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001122 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001123 for (ObjCInterfaceDecl::classmeth_iterator
1124 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001125 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001126 RewriteMethodDeclaration(*I);
1127
Steve Naroff4cd61ac2007-10-30 03:43:13 +00001128 // Lastly, comment out the @end.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001129 ReplaceText(ClassDecl->getAtEndRange().getBegin(), 0, "// ");
Steve Naroff161a92b2007-10-26 20:53:56 +00001130}
1131
Steve Naroff08628db2008-12-09 12:56:34 +00001132Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1133 SourceRange SrcRange) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00001134 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1135 // This allows us to reuse all the fun and games in SynthMessageExpr().
1136 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1137 ObjCMessageExpr *MsgExpr;
1138 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1139 llvm::SmallVector<Expr *, 1> ExprVec;
1140 ExprVec.push_back(newStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001141
Steve Naroff1042ff32008-12-08 16:43:47 +00001142 Stmt *Receiver = PropRefExpr->getBase();
1143 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1144 if (PRE && PropGetters[PRE]) {
1145 // This allows us to handle chain/nested property getters.
1146 Receiver = PropGetters[PRE];
1147 }
Ted Kremenek2c809302010-02-11 22:41:21 +00001148 MsgExpr = new (Context) ObjCMessageExpr(*Context, dyn_cast<Expr>(Receiver),
Mike Stump11289f42009-09-09 15:08:12 +00001149 PDecl->getSetterName(), PDecl->getType(),
1150 PDecl->getSetterMethodDecl(),
1151 SourceLocation(), SourceLocation(),
Steve Naroff4588d0f2008-12-04 16:24:46 +00001152 &ExprVec[0], 1);
1153 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001154
Steve Naroff4588d0f2008-12-04 16:24:46 +00001155 // Now do the actual rewrite.
Steve Naroff08628db2008-12-09 12:56:34 +00001156 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffdf705772008-12-10 14:53:27 +00001157 //delete BinOp;
Ted Kremenek5a201952009-02-07 01:47:29 +00001158 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1159 // to things that stay around.
1160 Context->Deallocate(MsgExpr);
Steve Naroff4588d0f2008-12-04 16:24:46 +00001161 return ReplacingStmt;
Steve Narofff326f402008-12-03 00:56:33 +00001162}
1163
Steve Naroff4588d0f2008-12-04 16:24:46 +00001164Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Narofff326f402008-12-03 00:56:33 +00001165 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1166 // This allows us to reuse all the fun and games in SynthMessageExpr().
1167 ObjCMessageExpr *MsgExpr;
1168 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
Mike Stump11289f42009-09-09 15:08:12 +00001169
Steve Naroff1042ff32008-12-08 16:43:47 +00001170 Stmt *Receiver = PropRefExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00001171
Steve Naroff1042ff32008-12-08 16:43:47 +00001172 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1173 if (PRE && PropGetters[PRE]) {
1174 // This allows us to handle chain/nested property getters.
1175 Receiver = PropGetters[PRE];
1176 }
Ted Kremenek2c809302010-02-11 22:41:21 +00001177 MsgExpr = new (Context) ObjCMessageExpr(*Context, dyn_cast<Expr>(Receiver),
Mike Stump11289f42009-09-09 15:08:12 +00001178 PDecl->getGetterName(), PDecl->getType(),
1179 PDecl->getGetterMethodDecl(),
1180 SourceLocation(), SourceLocation(),
Steve Narofff326f402008-12-03 00:56:33 +00001181 0, 0);
1182
Steve Naroff22216db2008-12-04 23:50:32 +00001183 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001184
1185 if (!PropParentMap)
1186 PropParentMap = new ParentMap(CurrentBody);
1187
1188 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1189 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1190 // We stash away the ReplacingStmt since actually doing the
1191 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1192 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek5a201952009-02-07 01:47:29 +00001193 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1194 // to things that stay around.
1195 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001196 return PropRefExpr; // return the original...
1197 } else {
1198 ReplaceStmt(PropRefExpr, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001199 // delete PropRefExpr; elsewhere...
Ted Kremenek5a201952009-02-07 01:47:29 +00001200 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1201 // to things that stay around.
1202 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001203 return ReplacingStmt;
1204 }
Steve Narofff326f402008-12-03 00:56:33 +00001205}
1206
Mike Stump11289f42009-09-09 15:08:12 +00001207Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001208 SourceLocation OrigStart,
1209 bool &replaced) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001210 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001211 const Expr *BaseExpr = IV->getBase();
Steve Naroff677ab3a2008-10-27 17:20:55 +00001212 if (CurMethodDef) {
Fariborz Jahanianf9e8c2b2010-01-26 18:28:51 +00001213 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001214 ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001215 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianf0ed69c2010-01-26 20:37:44 +00001216 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Naroffb1c02372008-05-08 17:52:16 +00001217 // lookup which class implements the instance variable.
1218 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001219 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001220 clsDeclared);
Steve Naroffb1c02372008-05-08 17:52:16 +00001221 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001222
Steve Naroffb1c02372008-05-08 17:52:16 +00001223 // Synthesize an explicit cast to gain access to the ivar.
1224 std::string RecName = clsDeclared->getIdentifier()->getName();
1225 RecName += "_IMPL";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001226 IdentifierInfo *II = &Context->Idents.get(RecName);
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001227 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001228 SourceLocation(), II);
Steve Naroffb1c02372008-05-08 17:52:16 +00001229 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1230 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall97513962010-01-15 18:39:57 +00001231 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1232 CastExpr::CK_Unknown,
1233 IV->getBase());
Steve Naroffb1c02372008-05-08 17:52:16 +00001234 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001235 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1236 IV->getBase()->getLocEnd(),
1237 castExpr);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001238 replaced = true;
Mike Stump11289f42009-09-09 15:08:12 +00001239 if (IV->isFreeIvar() &&
Steve Naroff677ab3a2008-10-27 17:20:55 +00001240 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001241 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1242 IV->getLocation(),
1243 D->getType());
Steve Naroff22216db2008-12-04 23:50:32 +00001244 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb1c02372008-05-08 17:52:16 +00001245 return ME;
Steve Naroff05caa482007-11-15 11:33:00 +00001246 }
Fariborz Jahanian81310812010-01-28 01:41:20 +00001247 // Get the new text
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001248 // Cannot delete IV->getBase(), since PE points to it.
1249 // Replace the old base with the cast. This is important when doing
1250 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001251 IV->setBase(PE);
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001252 return IV;
Steve Naroff05caa482007-11-15 11:33:00 +00001253 }
Steve Naroff24840f62008-04-18 21:55:08 +00001254 } else { // we are outside a method.
Steve Naroff29ce4e52008-05-06 23:20:07 +00001255 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump11289f42009-09-09 15:08:12 +00001256
Steve Naroff29ce4e52008-05-06 23:20:07 +00001257 // Explicit ivar refs need to have a cast inserted.
1258 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian12e2e862010-01-12 17:31:23 +00001259 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Fariborz Jahanian9146e442010-01-11 17:50:35 +00001260 ObjCInterfaceType *iFaceDecl =
1261 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001262 // lookup which class implements the instance variable.
1263 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001264 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001265 clsDeclared);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001266 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001267
Steve Naroff29ce4e52008-05-06 23:20:07 +00001268 // Synthesize an explicit cast to gain access to the ivar.
1269 std::string RecName = clsDeclared->getIdentifier()->getName();
1270 RecName += "_IMPL";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001271 IdentifierInfo *II = &Context->Idents.get(RecName);
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001272 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001273 SourceLocation(), II);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001274 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1275 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall97513962010-01-15 18:39:57 +00001276 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1277 CastExpr::CK_Unknown,
1278 IV->getBase());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001279 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001280 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner34873d22008-05-28 16:38:23 +00001281 IV->getBase()->getLocEnd(), castExpr);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001282 replaced = true;
Steve Naroff29ce4e52008-05-06 23:20:07 +00001283 // Cannot delete IV->getBase(), since PE points to it.
1284 // Replace the old base with the cast. This is important when doing
1285 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001286 IV->setBase(PE);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001287 return IV;
1288 }
Steve Naroff05caa482007-11-15 11:33:00 +00001289 }
Steve Naroff24840f62008-04-18 21:55:08 +00001290 return IV;
Steve Narofff60782b2007-11-15 02:58:25 +00001291}
1292
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001293Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
1294 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1295 CI != E; ++CI) {
1296 if (*CI) {
1297 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1298 if (newStmt)
1299 *CI = newStmt;
1300 }
1301 }
1302 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1303 SourceRange OrigStmtRange = S->getSourceRange();
1304 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1305 replaced);
1306 return newStmt;
Fariborz Jahanian31433382010-02-05 17:48:10 +00001307 }
1308 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1309 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1310 return newStmt;
1311 }
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001312 return S;
1313}
1314
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001315/// SynthCountByEnumWithState - To print:
1316/// ((unsigned int (*)
1317/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001318/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001319/// sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001320/// "countByEnumeratingWithState:objects:count:"),
1321/// &enumState,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001322/// (id *)items, (unsigned int)16)
1323///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001324void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001325 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1326 "id *, unsigned int))(void *)objc_msgSend)";
1327 buf += "\n\t\t";
1328 buf += "((id)l_collection,\n\t\t";
1329 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1330 buf += "\n\t\t";
1331 buf += "&enumState, "
1332 "(id *)items, (unsigned int)16)";
1333}
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001334
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001335/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1336/// statement to exit to its outer synthesized loop.
1337///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001338Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001339 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1340 return S;
1341 // replace break with goto __break_label
1342 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001343
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001344 SourceLocation startLoc = S->getLocStart();
1345 buf = "goto __break_label_";
1346 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001347 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001348
1349 return 0;
1350}
1351
1352/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1353/// statement to continue with its inner synthesized loop.
1354///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001355Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001356 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1357 return S;
1358 // replace continue with goto __continue_label
1359 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001360
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001361 SourceLocation startLoc = S->getLocStart();
1362 buf = "goto __continue_label_";
1363 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001364 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump11289f42009-09-09 15:08:12 +00001365
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001366 return 0;
1367}
1368
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001369/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001370/// It rewrites:
1371/// for ( type elem in collection) { stmts; }
Mike Stump11289f42009-09-09 15:08:12 +00001372
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001373/// Into:
1374/// {
Mike Stump11289f42009-09-09 15:08:12 +00001375/// type elem;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001376/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001377/// id items[16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001378/// id l_collection = (id)collection;
Mike Stump11289f42009-09-09 15:08:12 +00001379/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001380/// objects:items count:16];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001381/// if (limit) {
1382/// unsigned long startMutations = *enumState.mutationsPtr;
1383/// do {
1384/// unsigned long counter = 0;
1385/// do {
Mike Stump11289f42009-09-09 15:08:12 +00001386/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001387/// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001388/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001389/// stmts;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001390/// __continue_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001391/// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001392/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001393/// objects:items count:16]);
1394/// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001395/// __break_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001396/// }
1397/// else
1398/// elem = nil;
1399/// }
1400///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001401Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattnera779d692008-01-31 05:10:40 +00001402 SourceLocation OrigEnd) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001403 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001404 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001405 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump11289f42009-09-09 15:08:12 +00001406 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001407 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001408
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001409 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001410 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001411 const char *elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001412 std::string elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001413 std::string buf;
1414 buf = "\n{\n\t";
1415 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1416 // type elem;
Chris Lattner529efc72009-03-28 06:33:19 +00001417 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek292b3842008-10-06 22:16:13 +00001418 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001419 if (ElementType->isObjCQualifiedIdType() ||
1420 ElementType->isObjCQualifiedInterfaceType())
1421 // Simply use 'id' for all qualified types.
1422 elementTypeAsString = "id";
1423 else
1424 elementTypeAsString = ElementType.getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001425 buf += elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001426 buf += " ";
Chris Lattner86d7d912008-11-24 03:54:41 +00001427 elementName = D->getNameAsCString();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001428 buf += elementName;
1429 buf += ";\n\t";
1430 }
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001431 else {
1432 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner86d7d912008-11-24 03:54:41 +00001433 elementName = DR->getDecl()->getNameAsCString();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001434 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1435 if (VD->getType()->isObjCQualifiedIdType() ||
1436 VD->getType()->isObjCQualifiedInterfaceType())
1437 // Simply use 'id' for all qualified types.
1438 elementTypeAsString = "id";
1439 else
1440 elementTypeAsString = VD->getType().getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001441 }
Mike Stump11289f42009-09-09 15:08:12 +00001442
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001443 // struct __objcFastEnumerationState enumState = { 0 };
1444 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1445 // id items[16];
1446 buf += "id items[16];\n\t";
1447 // id l_collection = (id)
1448 buf += "id l_collection = (id)";
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001449 // Find start location of 'collection' the hard way!
1450 const char *startCollectionBuf = startBuf;
1451 startCollectionBuf += 3; // skip 'for'
1452 startCollectionBuf = strchr(startCollectionBuf, '(');
1453 startCollectionBuf++; // skip '('
1454 // find 'in' and skip it.
1455 while (*startCollectionBuf != ' ' ||
1456 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1457 (*(startCollectionBuf+3) != ' ' &&
1458 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1459 startCollectionBuf++;
1460 startCollectionBuf += 3;
Mike Stump11289f42009-09-09 15:08:12 +00001461
1462 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001463 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001464 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001465 SourceLocation rightParenLoc = S->getRParenLoc();
1466 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1467 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001468 buf = ";\n\t";
Mike Stump11289f42009-09-09 15:08:12 +00001469
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001470 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1471 // objects:items count:16];
1472 // which is synthesized into:
Mike Stump11289f42009-09-09 15:08:12 +00001473 // unsigned int limit =
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001474 // ((unsigned int (*)
1475 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001476 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001477 // sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001478 // "countByEnumeratingWithState:objects:count:"),
1479 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001480 // (id *)items, (unsigned int)16);
1481 buf += "unsigned long limit =\n\t\t";
1482 SynthCountByEnumWithState(buf);
1483 buf += ";\n\t";
1484 /// if (limit) {
1485 /// unsigned long startMutations = *enumState.mutationsPtr;
1486 /// do {
1487 /// unsigned long counter = 0;
1488 /// do {
Mike Stump11289f42009-09-09 15:08:12 +00001489 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001490 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001491 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001492 buf += "if (limit) {\n\t";
1493 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1494 buf += "do {\n\t\t";
1495 buf += "unsigned long counter = 0;\n\t\t";
1496 buf += "do {\n\t\t\t";
1497 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1498 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1499 buf += elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001500 buf += " = (";
1501 buf += elementTypeAsString;
1502 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001503 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001504 ReplaceText(lparenLoc, 1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001505
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001506 /// __continue_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001507 /// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001508 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001509 /// objects:items count:16]);
1510 /// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001511 /// __break_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001512 /// }
1513 /// else
1514 /// elem = nil;
1515 /// }
Mike Stump11289f42009-09-09 15:08:12 +00001516 ///
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001517 buf = ";\n\t";
1518 buf += "__continue_label_";
1519 buf += utostr(ObjCBcLabelNo.back());
1520 buf += ": ;";
1521 buf += "\n\t\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001522 buf += "} while (counter < limit);\n\t";
1523 buf += "} while (limit = ";
1524 SynthCountByEnumWithState(buf);
1525 buf += ");\n\t";
1526 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001527 buf += " = ((";
1528 buf += elementTypeAsString;
1529 buf += ")0);\n\t";
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001530 buf += "__break_label_";
1531 buf += utostr(ObjCBcLabelNo.back());
1532 buf += ": ;\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001533 buf += "}\n\t";
1534 buf += "else\n\t\t";
1535 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001536 buf += " = ((";
1537 buf += elementTypeAsString;
1538 buf += ")0);\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001539 buf += "}\n";
Mike Stump11289f42009-09-09 15:08:12 +00001540
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001541 // Insert all these *after* the statement body.
Sebastian Redla7b98a72009-04-26 20:35:05 +00001542 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Narofff0ff8792008-07-21 18:26:02 +00001543 if (isa<CompoundStmt>(S->getBody())) {
1544 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001545 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001546 } else {
1547 /* Need to treat single statements specially. For example:
1548 *
1549 * for (A *a in b) if (stuff()) break;
1550 * for (A *a in b) xxxyy;
1551 *
1552 * The following code simply scans ahead to the semi to find the actual end.
1553 */
1554 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1555 const char *semiBuf = strchr(stmtBuf, ';');
1556 assert(semiBuf && "Can't find ';'");
1557 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001558 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001559 }
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001560 Stmts.pop_back();
1561 ObjCBcLabelNo.pop_back();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001562 return 0;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001563}
1564
Mike Stump11289f42009-09-09 15:08:12 +00001565/// RewriteObjCSynchronizedStmt -
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001566/// This routine rewrites @synchronized(expr) stmt;
1567/// into:
1568/// objc_sync_enter(expr);
1569/// @try stmt @finally { objc_sync_exit(expr); }
1570///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001571Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001572 // Get the start location and compute the semi location.
1573 SourceLocation startLoc = S->getLocStart();
1574 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001575
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001576 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump11289f42009-09-09 15:08:12 +00001577
1578 std::string buf;
Steve Naroffb2fc0522008-08-21 13:03:03 +00001579 buf = "objc_sync_enter((id)";
1580 const char *lparenBuf = startBuf;
1581 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001582 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001583 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1584 // the sync expression is typically a message expression that's already
Steve Naroffad7013b2008-08-19 13:04:19 +00001585 // been rewritten! (which implies the SourceLocation's are invalid).
1586 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001587 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffad7013b2008-08-19 13:04:19 +00001588 while (*endBuf != ')') endBuf--;
1589 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001590 buf = ");\n";
1591 // declare a new scope with two variables, _stack and _rethrow.
1592 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1593 buf += "int buf[18/*32-bit i386*/];\n";
1594 buf += "char *pointers[4];} _stack;\n";
1595 buf += "id volatile _rethrow = 0;\n";
1596 buf += "objc_exception_try_enter(&_stack);\n";
1597 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001598 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001599 startLoc = S->getSynchBody()->getLocEnd();
1600 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001601
Steve Naroffad7013b2008-08-19 13:04:19 +00001602 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001603 SourceLocation lastCurlyLoc = startLoc;
1604 buf = "}\nelse {\n";
1605 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroffd9803712009-04-29 16:37:50 +00001606 buf += "}\n";
1607 buf += "{ /* implicit finally clause */\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001608 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffec60b432009-12-05 21:43:12 +00001609
1610 std::string syncBuf;
1611 syncBuf += " objc_sync_exit(";
John McCall97513962010-01-15 18:39:57 +00001612 Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1613 CastExpr::CK_Unknown,
1614 S->getSynchExpr());
Ted Kremenek2d470fc2008-09-13 05:16:45 +00001615 std::string syncExprBufS;
1616 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00001617 syncExpr->printPretty(syncExprBuf, *Context, 0,
1618 PrintingPolicy(LangOpts));
Steve Naroffec60b432009-12-05 21:43:12 +00001619 syncBuf += syncExprBuf.str();
1620 syncBuf += ");";
1621
1622 buf += syncBuf;
1623 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001624 buf += "}\n";
1625 buf += "}";
Mike Stump11289f42009-09-09 15:08:12 +00001626
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001627 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00001628
1629 bool hasReturns = false;
1630 HasReturnStmts(S->getSynchBody(), hasReturns);
1631 if (hasReturns)
1632 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1633
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001634 return 0;
1635}
1636
Steve Naroffec60b432009-12-05 21:43:12 +00001637void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1638{
Steve Naroff6d6da252008-12-05 17:03:39 +00001639 // Perform a bottom up traversal of all children.
1640 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1641 CI != E; ++CI)
1642 if (*CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001643 WarnAboutReturnGotoStmts(*CI);
Steve Naroff6d6da252008-12-05 17:03:39 +00001644
Steve Naroffec60b432009-12-05 21:43:12 +00001645 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump11289f42009-09-09 15:08:12 +00001646 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff6d6da252008-12-05 17:03:39 +00001647 TryFinallyContainsReturnDiag);
1648 }
1649 return;
1650}
1651
Steve Naroffec60b432009-12-05 21:43:12 +00001652void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1653{
1654 // Perform a bottom up traversal of all children.
1655 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1656 CI != E; ++CI)
1657 if (*CI)
1658 HasReturnStmts(*CI, hasReturns);
1659
1660 if (isa<ReturnStmt>(S))
1661 hasReturns = true;
1662 return;
1663}
1664
1665void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1666 // Perform a bottom up traversal of all children.
1667 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1668 CI != E; ++CI)
1669 if (*CI) {
1670 RewriteTryReturnStmts(*CI);
1671 }
1672 if (isa<ReturnStmt>(S)) {
1673 SourceLocation startLoc = S->getLocStart();
1674 const char *startBuf = SM->getCharacterData(startLoc);
1675
1676 const char *semiBuf = strchr(startBuf, ';');
1677 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1678 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1679
1680 std::string buf;
1681 buf = "{ objc_exception_try_exit(&_stack); return";
1682
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001683 ReplaceText(startLoc, 6, buf);
1684 InsertText(onePastSemiLoc, "}");
Steve Naroffec60b432009-12-05 21:43:12 +00001685 }
1686 return;
1687}
1688
1689void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1690 // Perform a bottom up traversal of all children.
1691 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1692 CI != E; ++CI)
1693 if (*CI) {
1694 RewriteSyncReturnStmts(*CI, syncExitBuf);
1695 }
1696 if (isa<ReturnStmt>(S)) {
1697 SourceLocation startLoc = S->getLocStart();
1698 const char *startBuf = SM->getCharacterData(startLoc);
1699
1700 const char *semiBuf = strchr(startBuf, ';');
1701 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1702 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1703
1704 std::string buf;
1705 buf = "{ objc_exception_try_exit(&_stack);";
1706 buf += syncExitBuf;
1707 buf += " return";
1708
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001709 ReplaceText(startLoc, 6, buf);
1710 InsertText(onePastSemiLoc, "}");
Steve Naroffec60b432009-12-05 21:43:12 +00001711 }
1712 return;
1713}
1714
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001715Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001716 // Get the start location and compute the semi location.
1717 SourceLocation startLoc = S->getLocStart();
1718 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001719
Steve Naroffbf478ec2007-11-07 04:08:17 +00001720 assert((*startBuf == '@') && "bogus @try location");
1721
1722 std::string buf;
1723 // declare a new scope with two variables, _stack and _rethrow.
1724 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1725 buf += "int buf[18/*32-bit i386*/];\n";
1726 buf += "char *pointers[4];} _stack;\n";
1727 buf += "id volatile _rethrow = 0;\n";
1728 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff16018582007-11-07 18:43:40 +00001729 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffbf478ec2007-11-07 04:08:17 +00001730
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001731 ReplaceText(startLoc, 4, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001732
Steve Naroffbf478ec2007-11-07 04:08:17 +00001733 startLoc = S->getTryBody()->getLocEnd();
1734 startBuf = SM->getCharacterData(startLoc);
1735
1736 assert((*startBuf == '}') && "bogus @try block");
Mike Stump11289f42009-09-09 15:08:12 +00001737
Steve Naroffbf478ec2007-11-07 04:08:17 +00001738 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffce2dca12008-07-16 15:31:30 +00001739 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1740 if (catchList) {
1741 startLoc = startLoc.getFileLocWithOffset(1);
1742 buf = " /* @catch begin */ else {\n";
1743 buf += " id _caught = objc_exception_extract(&_stack);\n";
1744 buf += " objc_exception_try_enter (&_stack);\n";
1745 buf += " if (_setjmp(_stack.buf))\n";
1746 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1747 buf += " else { /* @catch continue */";
Mike Stump11289f42009-09-09 15:08:12 +00001748
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001749 InsertText(startLoc, buf);
Steve Narofffac18fe2008-09-09 19:59:12 +00001750 } else { /* no catch list */
1751 buf = "}\nelse {\n";
1752 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1753 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001754 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffce2dca12008-07-16 15:31:30 +00001755 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001756 bool sawIdTypedCatch = false;
1757 Stmt *lastCatchBody = 0;
Steve Naroffbf478ec2007-11-07 04:08:17 +00001758 while (catchList) {
Steve Naroff371b8fb2009-03-03 19:52:17 +00001759 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001760
Mike Stump11289f42009-09-09 15:08:12 +00001761 if (catchList == S->getCatchStmts())
Steve Naroffbf478ec2007-11-07 04:08:17 +00001762 buf = "if ("; // we are generating code for the first catch clause
1763 else
1764 buf = "else if (";
1765 startLoc = catchList->getLocStart();
1766 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001767
Steve Naroffbf478ec2007-11-07 04:08:17 +00001768 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump11289f42009-09-09 15:08:12 +00001769
Steve Naroffbf478ec2007-11-07 04:08:17 +00001770 const char *lParenLoc = strchr(startBuf, '(');
1771
Steve Naroffe6b7ffd2008-02-01 22:08:12 +00001772 if (catchList->hasEllipsis()) {
Steve Naroffedb5bc62008-02-01 20:02:07 +00001773 // Now rewrite the body...
1774 lastCatchBody = catchList->getCatchBody();
Steve Naroffedb5bc62008-02-01 20:02:07 +00001775 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1776 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001777 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1778 "bogus @catch paren location");
Steve Naroffedb5bc62008-02-01 20:02:07 +00001779 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001780
Steve Naroffedb5bc62008-02-01 20:02:07 +00001781 buf += "1) { id _tmp = _caught;";
Daniel Dunbardec484a2009-08-19 19:10:30 +00001782 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff371b8fb2009-03-03 19:52:17 +00001783 } else if (catchDecl) {
1784 QualType t = catchDecl->getType();
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001785 if (t == Context->getObjCIdType()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001786 buf += "1) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001787 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroffbf478ec2007-11-07 04:08:17 +00001788 sawIdTypedCatch = true;
Fariborz Jahanian59516092010-01-12 01:22:23 +00001789 } else if (t->isObjCObjectPointerType()) {
1790 QualType InterfaceTy = t->getPointeeType();
1791 const ObjCInterfaceType *cls = // Should be a pointer to a class.
1792 InterfaceTy->getAs<ObjCInterfaceType>();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001793 if (cls) {
Steve Naroff16018582007-11-07 18:43:40 +00001794 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001795 buf += cls->getDecl()->getNameAsString();
Steve Naroff16018582007-11-07 18:43:40 +00001796 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001797 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroffbf478ec2007-11-07 04:08:17 +00001798 }
1799 }
1800 // Now rewrite the body...
1801 lastCatchBody = catchList->getCatchBody();
1802 SourceLocation rParenLoc = catchList->getRParenLoc();
1803 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1804 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1805 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1806 assert((*rParenBuf == ')') && "bogus @catch paren location");
1807 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001808
Mike Stump11289f42009-09-09 15:08:12 +00001809 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroffbf478ec2007-11-07 04:08:17 +00001810 // declares the @catch parameter).
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001811 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff371b8fb2009-03-03 19:52:17 +00001812 } else {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001813 assert(false && "@catch rewrite bug");
Steve Naroffa733c7f2007-11-07 15:32:26 +00001814 }
Steve Naroffedb5bc62008-02-01 20:02:07 +00001815 // make sure all the catch bodies get rewritten!
Steve Naroffbf478ec2007-11-07 04:08:17 +00001816 catchList = catchList->getNextCatchStmt();
1817 }
1818 // Complete the catch list...
1819 if (lastCatchBody) {
1820 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001821 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1822 "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001823
Steve Naroff4adbe312008-09-11 15:29:03 +00001824 // Insert the last (implicit) else clause *before* the right curly brace.
1825 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1826 buf = "} /* last catch end */\n";
1827 buf += "else {\n";
1828 buf += " _rethrow = _caught;\n";
1829 buf += " objc_exception_try_exit(&_stack);\n";
1830 buf += "} } /* @catch end */\n";
1831 if (!S->getFinallyStmt())
1832 buf += "}\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001833 InsertText(bodyLoc, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001834
Steve Naroffbf478ec2007-11-07 04:08:17 +00001835 // Set lastCurlyLoc
1836 lastCurlyLoc = lastCatchBody->getLocEnd();
1837 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001838 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001839 startLoc = finalStmt->getLocStart();
1840 startBuf = SM->getCharacterData(startLoc);
1841 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump11289f42009-09-09 15:08:12 +00001842
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001843 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump11289f42009-09-09 15:08:12 +00001844
Steve Naroffbf478ec2007-11-07 04:08:17 +00001845 Stmt *body = finalStmt->getFinallyBody();
1846 SourceLocation startLoc = body->getLocStart();
1847 SourceLocation endLoc = body->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001848 assert(*SM->getCharacterData(startLoc) == '{' &&
1849 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001850 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001851 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001852
Steve Naroffbf478ec2007-11-07 04:08:17 +00001853 startLoc = startLoc.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001854 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Steve Naroffbf478ec2007-11-07 04:08:17 +00001855 endLoc = endLoc.getFileLocWithOffset(-1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001856 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump11289f42009-09-09 15:08:12 +00001857
Steve Naroffbf478ec2007-11-07 04:08:17 +00001858 // Set lastCurlyLoc
1859 lastCurlyLoc = body->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00001860
Steve Naroff6d6da252008-12-05 17:03:39 +00001861 // Now check for any return/continue/go statements within the @try.
Steve Naroffec60b432009-12-05 21:43:12 +00001862 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff4adbe312008-09-11 15:29:03 +00001863 } else { /* no finally clause - make sure we synthesize an implicit one */
1864 buf = "{ /* implicit finally clause */\n";
1865 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1866 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1867 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001868 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00001869
1870 // Now check for any return/continue/go statements within the @try.
1871 // The implicit finally clause won't called if the @try contains any
1872 // jump statements.
1873 bool hasReturns = false;
1874 HasReturnStmts(S->getTryBody(), hasReturns);
1875 if (hasReturns)
1876 RewriteTryReturnStmts(S->getTryBody());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001877 }
1878 // Now emit the final closing curly brace...
1879 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001880 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001881 return 0;
1882}
1883
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001884Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001885 return 0;
1886}
1887
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001888Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001889 return 0;
1890}
1891
Mike Stump11289f42009-09-09 15:08:12 +00001892// This can't be done with ReplaceStmt(S, ThrowExpr), since
1893// the throw expression is typically a message expression that's already
Steve Naroffa733c7f2007-11-07 15:32:26 +00001894// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001895Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroffa733c7f2007-11-07 15:32:26 +00001896 // Get the start location and compute the semi location.
1897 SourceLocation startLoc = S->getLocStart();
1898 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001899
Steve Naroffa733c7f2007-11-07 15:32:26 +00001900 assert((*startBuf == '@') && "bogus @throw location");
1901
1902 std::string buf;
1903 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffc7d2df22008-01-19 00:42:38 +00001904 if (S->getThrowExpr())
1905 buf = "objc_exception_throw(";
1906 else // add an implicit argument
1907 buf = "objc_exception_throw(_caught";
Mike Stump11289f42009-09-09 15:08:12 +00001908
Steve Naroff29788342008-07-25 15:41:30 +00001909 // handle "@ throw" correctly.
1910 const char *wBuf = strchr(startBuf, 'w');
1911 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001912 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001913
Steve Naroffa733c7f2007-11-07 15:32:26 +00001914 const char *semiBuf = strchr(startBuf, ';');
1915 assert((*semiBuf == ';') && "@throw: can't find ';'");
1916 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001917 ReplaceText(semiLoc, 1, ");");
Steve Naroffa733c7f2007-11-07 15:32:26 +00001918 return 0;
1919}
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001920
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001921Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerc6d91c02007-10-17 22:35:30 +00001922 // Create a new string expression.
1923 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlssond8499822007-10-29 05:01:08 +00001924 std::string StrEncoding;
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00001925 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00001926 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
1927 StrEncoding.length(), false,StrType,
1928 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00001929 ReplaceStmt(Exp, Replacement);
Mike Stump11289f42009-09-09 15:08:12 +00001930
Chris Lattner4431a1b2007-11-30 22:53:43 +00001931 // Replace this subexpr in the parent.
Steve Naroff22216db2008-12-04 23:50:32 +00001932 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattner69534692007-10-24 16:57:36 +00001933 return Replacement;
Chris Lattnera7c19fe2007-10-16 22:36:42 +00001934}
1935
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001936Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff2654e182008-12-22 22:16:07 +00001937 if (!SelGetUidFunctionDecl)
1938 SynthSelGetUidFunctionDecl();
Steve Naroffe4f9b232007-11-05 14:50:49 +00001939 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1940 // Create a call to sel_registerName("selName").
1941 llvm::SmallVector<Expr*, 8> SelExprs;
1942 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00001943 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00001944 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00001945 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00001946 false, argType, SourceLocation()));
Steve Naroffe4f9b232007-11-05 14:50:49 +00001947 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1948 &SelExprs[0], SelExprs.size());
Chris Lattner2e0d2602008-01-31 19:37:57 +00001949 ReplaceStmt(Exp, SelExp);
Steve Naroff22216db2008-12-04 23:50:32 +00001950 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffe4f9b232007-11-05 14:50:49 +00001951 return SelExp;
1952}
1953
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001954CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff574440f2007-10-24 22:48:43 +00001955 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001956 // Get the type, we will need to reference it in a couple spots.
Steve Naroff574440f2007-10-24 22:48:43 +00001957 QualType msgSendType = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001958
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001959 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek5a201952009-02-07 01:47:29 +00001960 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001961
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001962 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattner3c799d72007-10-24 17:06:59 +00001963 QualType pToFunc = Context->getPointerType(msgSendType);
Mike Stump11289f42009-09-09 15:08:12 +00001964 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc,
Anders Carlssona2615922009-07-31 00:48:10 +00001965 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00001966 DRE,
Douglas Gregora11693b2008-11-12 17:17:38 +00001967 /*isLvalue=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001968
John McCall9dd450b2009-09-21 23:43:11 +00001969 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00001970
Ted Kremenekd7b4f402009-02-09 20:51:47 +00001971 return new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
1972 SourceLocation());
Steve Naroff574440f2007-10-24 22:48:43 +00001973}
1974
Steve Naroff50d42052007-11-01 13:24:47 +00001975static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1976 const char *&startRef, const char *&endRef) {
1977 while (startBuf < endBuf) {
1978 if (*startBuf == '<')
1979 startRef = startBuf; // mark the start.
1980 if (*startBuf == '>') {
Steve Naroff1b232132007-11-09 12:50:28 +00001981 if (startRef && *startRef == '<') {
1982 endRef = startBuf; // mark the end.
1983 return true;
1984 }
1985 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00001986 }
1987 startBuf++;
1988 }
1989 return false;
1990}
1991
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001992static void scanToNextArgument(const char *&argRef) {
1993 int angle = 0;
1994 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1995 if (*argRef == '<')
1996 angle++;
1997 else if (*argRef == '>')
1998 angle--;
1999 argRef++;
2000 }
2001 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2002}
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002003
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002004bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian80c54b02010-02-03 21:29:28 +00002005 if (T->isObjCQualifiedIdType())
2006 return true;
Fariborz Jahanian06769f92010-02-02 18:35:07 +00002007 if (const PointerType *PT = T->getAs<PointerType>()) {
2008 if (PT->getPointeeType()->isObjCQualifiedIdType())
2009 return true;
2010 }
2011 if (T->isObjCObjectPointerType()) {
2012 T = T->getPointeeType();
2013 return T->isObjCQualifiedInterfaceType();
2014 }
2015 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002016}
2017
Steve Naroff873bd842008-07-29 18:15:38 +00002018void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2019 QualType Type = E->getType();
2020 if (needToScanForQualifiers(Type)) {
Steve Naroffdbfc6932008-11-19 21:15:47 +00002021 SourceLocation Loc, EndLoc;
Mike Stump11289f42009-09-09 15:08:12 +00002022
Steve Naroffdbfc6932008-11-19 21:15:47 +00002023 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2024 Loc = ECE->getLParenLoc();
2025 EndLoc = ECE->getRParenLoc();
2026 } else {
2027 Loc = E->getLocStart();
2028 EndLoc = E->getLocEnd();
2029 }
2030 // This will defend against trying to rewrite synthesized expressions.
2031 if (Loc.isInvalid() || EndLoc.isInvalid())
2032 return;
2033
Steve Naroff873bd842008-07-29 18:15:38 +00002034 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffdbfc6932008-11-19 21:15:47 +00002035 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff873bd842008-07-29 18:15:38 +00002036 const char *startRef = 0, *endRef = 0;
2037 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2038 // Get the locations of the startRef, endRef.
2039 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2040 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2041 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002042 InsertText(LessLoc, "/*");
2043 InsertText(GreaterLoc, "*/");
Steve Naroff873bd842008-07-29 18:15:38 +00002044 }
2045 }
2046}
2047
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002048void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002049 SourceLocation Loc;
2050 QualType Type;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002051 const FunctionProtoType *proto = 0;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002052 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2053 Loc = VD->getLocation();
2054 Type = VD->getType();
2055 }
2056 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2057 Loc = FD->getLocation();
2058 // Check for ObjC 'id' and class types that have been adorned with protocol
2059 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall9dd450b2009-09-21 23:43:11 +00002060 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002061 assert(funcType && "missing function type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002062 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002063 if (!proto)
2064 return;
2065 Type = proto->getResultType();
2066 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00002067 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2068 Loc = FD->getLocation();
2069 Type = FD->getType();
2070 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002071 else
2072 return;
Mike Stump11289f42009-09-09 15:08:12 +00002073
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002074 if (needToScanForQualifiers(Type)) {
Steve Naroff50d42052007-11-01 13:24:47 +00002075 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002076
Steve Naroff50d42052007-11-01 13:24:47 +00002077 const char *endBuf = SM->getCharacterData(Loc);
2078 const char *startBuf = endBuf;
Steve Naroff930e0992008-05-31 05:02:17 +00002079 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroff50d42052007-11-01 13:24:47 +00002080 startBuf--; // scan backward (from the decl location) for return type.
2081 const char *startRef = 0, *endRef = 0;
2082 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2083 // Get the locations of the startRef, endRef.
2084 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2085 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2086 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002087 InsertText(LessLoc, "/*");
2088 InsertText(GreaterLoc, "*/");
Steve Naroff37e011c2007-10-31 04:38:33 +00002089 }
2090 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002091 if (!proto)
2092 return; // most likely, was a variable
Steve Naroff50d42052007-11-01 13:24:47 +00002093 // Now check arguments.
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002094 const char *startBuf = SM->getCharacterData(Loc);
2095 const char *startFuncBuf = startBuf;
Steve Naroff50d42052007-11-01 13:24:47 +00002096 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2097 if (needToScanForQualifiers(proto->getArgType(i))) {
2098 // 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 = startBuf;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002101 // scan forward (from the decl location) for argument types.
2102 scanToNextArgument(endBuf);
Steve Naroff50d42052007-11-01 13:24:47 +00002103 const char *startRef = 0, *endRef = 0;
2104 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2105 // Get the locations of the startRef, endRef.
Mike Stump11289f42009-09-09 15:08:12 +00002106 SourceLocation LessLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002107 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump11289f42009-09-09 15:08:12 +00002108 SourceLocation GreaterLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002109 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002110 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002111 InsertText(LessLoc, "/*");
2112 InsertText(GreaterLoc, "*/");
Steve Naroff50d42052007-11-01 13:24:47 +00002113 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002114 startBuf = ++endBuf;
2115 }
2116 else {
Steve Naroffc884aa82008-08-06 15:58:23 +00002117 // If the function name is derived from a macro expansion, then the
2118 // argument buffer will not follow the name. Need to speak with Chris.
2119 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002120 startBuf++; // scan forward (from the decl location) for argument types.
2121 startBuf++;
2122 }
Steve Naroff50d42052007-11-01 13:24:47 +00002123 }
Steve Naroff37e011c2007-10-31 04:38:33 +00002124}
2125
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002126void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2127 QualType QT = ND->getType();
2128 const Type* TypePtr = QT->getAs<Type>();
2129 if (!isa<TypeOfExprType>(TypePtr))
2130 return;
2131 while (isa<TypeOfExprType>(TypePtr)) {
2132 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2133 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2134 TypePtr = QT->getAs<Type>();
2135 }
2136 // FIXME. This will not work for multiple declarators; as in:
2137 // __typeof__(a) b,c,d;
2138 std::string TypeAsString(QT.getAsString());
2139 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2140 const char *startBuf = SM->getCharacterData(DeclLoc);
2141 if (ND->getInit()) {
2142 std::string Name(ND->getNameAsString());
2143 TypeAsString += " " + Name + " = ";
2144 Expr *E = ND->getInit();
2145 SourceLocation startLoc;
2146 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2147 startLoc = ECE->getLParenLoc();
2148 else
2149 startLoc = E->getLocStart();
2150 startLoc = SM->getInstantiationLoc(startLoc);
2151 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002152 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002153 }
2154 else {
2155 SourceLocation X = ND->getLocEnd();
2156 X = SM->getInstantiationLoc(X);
2157 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002158 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002159 }
2160}
2161
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002162// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002163void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002164 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2165 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002166 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002167 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002168 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002169 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002170 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002171 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002172 SelGetUidIdent, getFuncType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002173 FunctionDecl::Extern, false);
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002174}
2175
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002176void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002177 // declared in <objc/objc.h>
Douglas Gregor1e21c192009-01-09 01:47:02 +00002178 if (FD->getIdentifier() &&
2179 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002180 SelGetUidFunctionDecl = FD;
Steve Naroff37e011c2007-10-31 04:38:33 +00002181 return;
2182 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002183 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002184}
2185
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002186static void RewriteBlockPointerType(std::string& Str, QualType Type) {
2187 std::string TypeString(Type.getAsString());
2188 const char *argPtr = TypeString.c_str();
2189 if (!strchr(argPtr, '^')) {
2190 Str += TypeString;
2191 return;
2192 }
2193 while (*argPtr) {
2194 Str += (*argPtr == '^' ? '*' : *argPtr);
2195 argPtr++;
2196 }
2197}
2198
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002199void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2200 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2201 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2202 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2203 if (!proto)
2204 return;
2205 QualType Type = proto->getResultType();
2206 std::string FdStr = Type.getAsString();
2207 FdStr += " ";
2208 FdStr += FD->getNameAsCString();
2209 FdStr += "(";
2210 unsigned numArgs = proto->getNumArgs();
2211 for (unsigned i = 0; i < numArgs; i++) {
2212 QualType ArgType = proto->getArgType(i);
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002213 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002214 if (i+1 < numArgs)
2215 FdStr += ", ";
2216 }
2217 FdStr += ");\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002218 InsertText(FunLocStart, FdStr);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002219 CurFunctionDeclToDeclareForBlock = 0;
2220}
2221
Steve Naroff17978c42008-03-11 17:37:02 +00002222// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002223void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroff17978c42008-03-11 17:37:02 +00002224 if (SuperContructorFunctionDecl)
2225 return;
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002226 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroff17978c42008-03-11 17:37:02 +00002227 llvm::SmallVector<QualType, 16> ArgTys;
2228 QualType argT = Context->getObjCIdType();
2229 assert(!argT.isNull() && "Can't find 'id' type");
2230 ArgTys.push_back(argT);
2231 ArgTys.push_back(argT);
2232 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2233 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002234 false, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002235 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002236 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002237 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002238 FunctionDecl::Extern, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002239}
2240
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002241// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002242void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002243 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2244 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002245 QualType argT = Context->getObjCIdType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002246 assert(!argT.isNull() && "Can't find 'id' type");
2247 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002248 argT = Context->getObjCSelType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002249 assert(!argT.isNull() && "Can't find 'SEL' type");
2250 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002251 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002252 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002253 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002254 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002255 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002256 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002257 FunctionDecl::Extern, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002258}
2259
Steve Naroff7fa2f042007-11-15 10:28:18 +00002260// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002261void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002262 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2263 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002264 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002265 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002266 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002267 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2268 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2269 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002270 argT = Context->getObjCSelType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002271 assert(!argT.isNull() && "Can't find 'SEL' type");
2272 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002273 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff7fa2f042007-11-15 10:28:18 +00002274 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002275 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002276 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002277 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002278 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002279 FunctionDecl::Extern, false);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002280}
2281
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002282// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002283void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002284 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2285 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002286 QualType argT = Context->getObjCIdType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002287 assert(!argT.isNull() && "Can't find 'id' type");
2288 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002289 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002290 assert(!argT.isNull() && "Can't find 'SEL' type");
2291 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002292 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002293 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002294 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002295 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002296 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002297 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002298 FunctionDecl::Extern, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002299}
2300
Mike Stump11289f42009-09-09 15:08:12 +00002301// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002302// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002303void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump11289f42009-09-09 15:08:12 +00002304 IdentifierInfo *msgSendIdent =
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002305 &Context->Idents.get("objc_msgSendSuper_stret");
2306 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002307 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002308 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002309 &Context->Idents.get("objc_super"));
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002310 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2311 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2312 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002313 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002314 assert(!argT.isNull() && "Can't find 'SEL' type");
2315 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002316 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002317 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002318 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002319 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002320 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002321 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002322 FunctionDecl::Extern, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002323}
2324
Steve Naroff2e4e3852008-05-08 22:02:18 +00002325// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002326void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002327 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2328 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002329 QualType argT = Context->getObjCIdType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002330 assert(!argT.isNull() && "Can't find 'id' type");
2331 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002332 argT = Context->getObjCSelType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002333 assert(!argT.isNull() && "Can't find 'SEL' type");
2334 ArgTys.push_back(argT);
Steve Naroff2e4e3852008-05-08 22:02:18 +00002335 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002336 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002337 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002338 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002339 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002340 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002341 FunctionDecl::Extern, false);
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002342}
2343
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002344// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002345void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002346 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2347 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002348 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002349 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002350 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002351 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002352 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002353 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002354 getClassIdent, getClassType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002355 FunctionDecl::Extern, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002356}
2357
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002358// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002359void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002360 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2361 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002362 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002363 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002364 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002365 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002366 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002367 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002368 getClassIdent, getClassType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002369 FunctionDecl::Extern, false);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002370}
2371
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002372Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffce8e8862008-03-15 00:55:56 +00002373 QualType strType = getConstantStringStructType();
2374
2375 std::string S = "__NSConstantStringImpl_";
Steve Naroffa6141f02008-05-31 03:35:42 +00002376
2377 std::string tmpName = InFileName;
2378 unsigned i;
2379 for (i=0; i < tmpName.length(); i++) {
2380 char c = tmpName.at(i);
2381 // replace any non alphanumeric characters with '_'.
2382 if (!isalpha(c) && (c < '0' || c > '9'))
2383 tmpName[i] = '_';
2384 }
2385 S += tmpName;
2386 S += "_";
Steve Naroffce8e8862008-03-15 00:55:56 +00002387 S += utostr(NumObjCStringLiterals++);
2388
Steve Naroff00a31762008-03-27 22:29:16 +00002389 Preamble += "static __NSConstantStringImpl " + S;
2390 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2391 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffce8e8862008-03-15 00:55:56 +00002392 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek2d470fc2008-09-13 05:16:45 +00002393 std::string prettyBufS;
2394 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00002395 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2396 PrintingPolicy(LangOpts));
Steve Naroff00a31762008-03-27 22:29:16 +00002397 Preamble += prettyBuf.str();
2398 Preamble += ",";
Steve Naroff94ed6dc2009-12-06 01:48:44 +00002399 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002400
2401 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002402 &Context->Idents.get(S), strType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002403 VarDecl::Static);
Ted Kremenek5a201952009-02-07 01:47:29 +00002404 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2405 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002406 Context->getPointerType(DRE->getType()),
Steve Naroffce8e8862008-03-15 00:55:56 +00002407 SourceLocation());
Steve Naroff265a6b92007-11-08 14:30:50 +00002408 // cast to NSConstantString *
John McCall97513962010-01-15 18:39:57 +00002409 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2410 CastExpr::CK_Unknown, Unop);
Chris Lattner2e0d2602008-01-31 19:37:57 +00002411 ReplaceStmt(Exp, cast);
Steve Naroff22216db2008-12-04 23:50:32 +00002412 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff265a6b92007-11-08 14:30:50 +00002413 return cast;
Steve Naroffa397efd2007-11-03 11:27:19 +00002414}
2415
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002416ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002417 // check if we are sending a message to 'super'
Douglas Gregorffca3a22009-01-09 17:18:27 +00002418 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002419
Douglas Gregor8ea1f532008-11-04 14:56:14 +00002420 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
Mike Stump11289f42009-09-09 15:08:12 +00002421 const ObjCObjectPointerType *OPT =
John McCall9dd450b2009-09-21 23:43:11 +00002422 Super->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00002423 assert(OPT);
2424 const ObjCInterfaceType *IT = OPT->getInterfaceType();
Chris Lattnera9b3cae2008-06-21 18:04:54 +00002425 return IT->getDecl();
2426 }
2427 return 0;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002428}
2429
2430// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002431QualType RewriteObjC::getSuperStructType() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002432 if (!SuperStructDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002433 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002434 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002435 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002436 QualType FieldTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002437
Steve Naroff7fa2f042007-11-15 10:28:18 +00002438 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002439 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002440 // struct objc_class *super;
Mike Stump11289f42009-09-09 15:08:12 +00002441 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor91f84212008-12-11 16:49:14 +00002442
Steve Naroff7fa2f042007-11-15 10:28:18 +00002443 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002444 for (unsigned i = 0; i < 2; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002445 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2446 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002447 FieldTypes[i], 0,
2448 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002449 /*Mutable=*/false));
Douglas Gregor91f84212008-12-11 16:49:14 +00002450 }
Mike Stump11289f42009-09-09 15:08:12 +00002451
Douglas Gregord5058122010-02-11 01:19:42 +00002452 SuperStructDecl->completeDefinition();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002453 }
2454 return Context->getTagDeclType(SuperStructDecl);
2455}
2456
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002457QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffce8e8862008-03-15 00:55:56 +00002458 if (!ConstantStringDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002459 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002460 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002461 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffce8e8862008-03-15 00:55:56 +00002462 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002463
Steve Naroffce8e8862008-03-15 00:55:56 +00002464 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002465 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffce8e8862008-03-15 00:55:56 +00002466 // int flags;
Mike Stump11289f42009-09-09 15:08:12 +00002467 FieldTypes[1] = Context->IntTy;
Steve Naroffce8e8862008-03-15 00:55:56 +00002468 // char *str;
Mike Stump11289f42009-09-09 15:08:12 +00002469 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffce8e8862008-03-15 00:55:56 +00002470 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002471 FieldTypes[3] = Context->LongTy;
Douglas Gregor91f84212008-12-11 16:49:14 +00002472
Steve Naroffce8e8862008-03-15 00:55:56 +00002473 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002474 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002475 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2476 ConstantStringDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002477 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002478 FieldTypes[i], 0,
Douglas Gregor91f84212008-12-11 16:49:14 +00002479 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002480 /*Mutable=*/true));
Douglas Gregor91f84212008-12-11 16:49:14 +00002481 }
2482
Douglas Gregord5058122010-02-11 01:19:42 +00002483 ConstantStringDecl->completeDefinition();
Steve Naroffce8e8862008-03-15 00:55:56 +00002484 }
2485 return Context->getTagDeclType(ConstantStringDecl);
2486}
2487
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002488Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002489 if (!SelGetUidFunctionDecl)
2490 SynthSelGetUidFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002491 if (!MsgSendFunctionDecl)
2492 SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002493 if (!MsgSendSuperFunctionDecl)
2494 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002495 if (!MsgSendStretFunctionDecl)
2496 SynthMsgSendStretFunctionDecl();
2497 if (!MsgSendSuperStretFunctionDecl)
2498 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002499 if (!MsgSendFpretFunctionDecl)
2500 SynthMsgSendFpretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002501 if (!GetClassFunctionDecl)
2502 SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002503 if (!GetMetaClassFunctionDecl)
2504 SynthGetMetaClassFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002505
Steve Naroff7fa2f042007-11-15 10:28:18 +00002506 // default to objc_msgSend().
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002507 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2508 // May need to use objc_msgSend_stret() as well.
2509 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroffd9803712009-04-29 16:37:50 +00002510 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2511 QualType resultType = mDecl->getResultType();
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002512 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002513 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002514 else if (resultType->isRealFloatingType())
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002515 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002516 }
Mike Stump11289f42009-09-09 15:08:12 +00002517
Steve Naroff574440f2007-10-24 22:48:43 +00002518 // Synthesize a call to objc_msgSend().
2519 llvm::SmallVector<Expr*, 8> MsgExprs;
2520 IdentifierInfo *clsName = Exp->getClassName();
Mike Stump11289f42009-09-09 15:08:12 +00002521
Steve Naroff574440f2007-10-24 22:48:43 +00002522 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2523 if (clsName) { // class message.
Steve Naroff6c79f972008-07-24 19:44:33 +00002524 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2525 // the 'super' idiom within a class method.
Daniel Dunbar07d07852009-10-18 21:17:35 +00002526 if (clsName->getName() == "super") {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002527 MsgSendFlavor = MsgSendSuperFunctionDecl;
2528 if (MsgSendStretFlavor)
2529 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2530 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002531
2532 ObjCInterfaceDecl *SuperDecl =
Steve Naroff677ab3a2008-10-27 17:20:55 +00002533 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002534
2535 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002536
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002537 // set the receiver to self, the first argument to all methods.
Steve Naroffd9803712009-04-29 16:37:50 +00002538 InitExprs.push_back(
John McCall97513962010-01-15 18:39:57 +00002539 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2540 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002541 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroffd9803712009-04-29 16:37:50 +00002542 Context->getObjCIdType(),
John McCall97513962010-01-15 18:39:57 +00002543 SourceLocation()))
2544 ); // set the 'receiver'.
Steve Naroffd9803712009-04-29 16:37:50 +00002545
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002546 llvm::SmallVector<Expr*, 8> ClsExprs;
2547 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002548 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002549 SuperDecl->getIdentifier()->getNameStart(),
2550 SuperDecl->getIdentifier()->getLength(),
2551 false, argType, SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002552 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002553 &ClsExprs[0],
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002554 ClsExprs.size());
2555 // To turn off a warning, type-cast to 'id'
Douglas Gregore200adc2008-10-27 19:41:14 +00002556 InitExprs.push_back( // set 'super class', using objc_getClass().
John McCall97513962010-01-15 18:39:57 +00002557 NoTypeInfoCStyleCastExpr(Context,
2558 Context->getObjCIdType(),
2559 CastExpr::CK_Unknown, Cls));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002560 // struct objc_super
2561 QualType superType = getSuperStructType();
Steve Naroff0b844f02008-03-11 18:14:26 +00002562 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002563
Steve Naroff0b844f02008-03-11 18:14:26 +00002564 if (LangOpts.Microsoft) {
2565 SynthSuperContructorFunctionDecl();
2566 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002567 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff0b844f02008-03-11 18:14:26 +00002568 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002569 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002570 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002571 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002572 // The code for super is a little tricky to prevent collision with
2573 // the structure definition in the header. The rewriter has it's own
2574 // internal definition (__rw_objc_super) that is uses. This is why
2575 // we need the cast below. For example:
2576 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2577 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002578 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002579 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002580 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00002581 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2582 Context->getPointerType(superType),
2583 CastExpr::CK_Unknown, SuperRep);
Mike Stump11289f42009-09-09 15:08:12 +00002584 } else {
Steve Naroff0b844f02008-03-11 18:14:26 +00002585 // (struct objc_super) { <exprs from above> }
Mike Stump11289f42009-09-09 15:08:12 +00002586 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2587 &InitExprs[0], InitExprs.size(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002588 SourceLocation());
John McCalle15bbff2010-01-18 19:35:47 +00002589 TypeSourceInfo *superTInfo
2590 = Context->getTrivialTypeSourceInfo(superType);
John McCall5d7aa7f2010-01-19 22:33:45 +00002591 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2592 superType, ILE, false);
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002593 // struct objc_super *
Ted Kremenek5a201952009-02-07 01:47:29 +00002594 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002595 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002596 SourceLocation());
Steve Naroff0b844f02008-03-11 18:14:26 +00002597 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002598 MsgExprs.push_back(SuperRep);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002599 } else {
2600 llvm::SmallVector<Expr*, 8> ClsExprs;
2601 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002602 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002603 clsName->getNameStart(),
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002604 clsName->getLength(),
2605 false, argType,
2606 SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002607 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002608 &ClsExprs[0],
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002609 ClsExprs.size());
2610 MsgExprs.push_back(Cls);
2611 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002612 } else { // instance message.
2613 Expr *recExpr = Exp->getReceiver();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002614
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002615 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002616 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002617 if (MsgSendStretFlavor)
2618 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002619 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002620
Steve Naroff7fa2f042007-11-15 10:28:18 +00002621 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002622
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002623 InitExprs.push_back(
John McCall97513962010-01-15 18:39:57 +00002624 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2625 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002626 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff97adf602008-07-16 22:35:27 +00002627 Context->getObjCIdType(),
John McCall97513962010-01-15 18:39:57 +00002628 SourceLocation()))
2629 ); // set the 'receiver'.
Mike Stump11289f42009-09-09 15:08:12 +00002630
Steve Naroff7fa2f042007-11-15 10:28:18 +00002631 llvm::SmallVector<Expr*, 8> ClsExprs;
2632 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002633 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002634 SuperDecl->getIdentifier()->getNameStart(),
2635 SuperDecl->getIdentifier()->getLength(),
2636 false, argType, SourceLocation()));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002637 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002638 &ClsExprs[0],
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002639 ClsExprs.size());
Fariborz Jahaniand5db92b2007-12-05 17:29:46 +00002640 // To turn off a warning, type-cast to 'id'
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002641 InitExprs.push_back(
Douglas Gregore200adc2008-10-27 19:41:14 +00002642 // set 'super class', using objc_getClass().
John McCall97513962010-01-15 18:39:57 +00002643 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2644 CastExpr::CK_Unknown, Cls));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002645 // struct objc_super
2646 QualType superType = getSuperStructType();
Steve Naroff17978c42008-03-11 17:37:02 +00002647 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002648
Steve Naroff17978c42008-03-11 17:37:02 +00002649 if (LangOpts.Microsoft) {
2650 SynthSuperContructorFunctionDecl();
2651 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002652 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff17978c42008-03-11 17:37:02 +00002653 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002654 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002655 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002656 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002657 // The code for super is a little tricky to prevent collision with
2658 // the structure definition in the header. The rewriter has it's own
2659 // internal definition (__rw_objc_super) that is uses. This is why
2660 // we need the cast below. For example:
2661 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2662 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002663 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002664 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002665 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00002666 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2667 Context->getPointerType(superType),
2668 CastExpr::CK_Unknown, SuperRep);
Steve Naroff17978c42008-03-11 17:37:02 +00002669 } else {
2670 // (struct objc_super) { <exprs from above> }
Mike Stump11289f42009-09-09 15:08:12 +00002671 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2672 &InitExprs[0], InitExprs.size(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002673 SourceLocation());
John McCalle15bbff2010-01-18 19:35:47 +00002674 TypeSourceInfo *superTInfo
2675 = Context->getTrivialTypeSourceInfo(superType);
John McCall5d7aa7f2010-01-19 22:33:45 +00002676 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2677 superType, ILE, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002678 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002679 MsgExprs.push_back(SuperRep);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002680 } else {
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002681 // Remove all type-casts because it may contain objc-style types; e.g.
2682 // Foo<Proto> *.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002683 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002684 recExpr = CE->getSubExpr();
John McCall97513962010-01-15 18:39:57 +00002685 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2686 CastExpr::CK_Unknown, recExpr);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002687 MsgExprs.push_back(recExpr);
2688 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002689 }
Steve Naroffa397efd2007-11-03 11:27:19 +00002690 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff574440f2007-10-24 22:48:43 +00002691 llvm::SmallVector<Expr*, 8> SelExprs;
2692 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002693 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002694 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002695 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00002696 false, argType, SourceLocation()));
Steve Naroff574440f2007-10-24 22:48:43 +00002697 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2698 &SelExprs[0], SelExprs.size());
2699 MsgExprs.push_back(SelExp);
Mike Stump11289f42009-09-09 15:08:12 +00002700
Steve Naroff574440f2007-10-24 22:48:43 +00002701 // Now push any user supplied arguments.
2702 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroffe7f18192007-11-14 23:54:14 +00002703 Expr *userExpr = Exp->getArg(i);
Steve Narofff60782b2007-11-15 02:58:25 +00002704 // Make all implicit casts explicit...ICE comes in handy:-)
2705 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2706 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregore200adc2008-10-27 19:41:14 +00002707 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002708 ? Context->getObjCIdType()
Douglas Gregore200adc2008-10-27 19:41:14 +00002709 : ICE->getType();
John McCall97513962010-01-15 18:39:57 +00002710 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CastExpr::CK_Unknown,
2711 userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002712 }
2713 // Make id<P...> cast into an 'id' cast.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002714 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002715 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregorf19b2312008-10-28 15:36:24 +00002716 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002717 userExpr = CE->getSubExpr();
John McCall97513962010-01-15 18:39:57 +00002718 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2719 CastExpr::CK_Unknown, userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002720 }
Mike Stump11289f42009-09-09 15:08:12 +00002721 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002722 MsgExprs.push_back(userExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00002723 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2724 // out the argument in the original expression (since we aren't deleting
2725 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2726 //Exp->setArg(i, 0);
Steve Naroff574440f2007-10-24 22:48:43 +00002727 }
Steve Narofff36987c2007-11-04 22:37:50 +00002728 // Generate the funky cast.
2729 CastExpr *cast;
2730 llvm::SmallVector<QualType, 8> ArgTypes;
2731 QualType returnType;
Mike Stump11289f42009-09-09 15:08:12 +00002732
Steve Narofff36987c2007-11-04 22:37:50 +00002733 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff44864e42007-11-15 10:43:57 +00002734 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2735 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2736 else
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002737 ArgTypes.push_back(Context->getObjCIdType());
2738 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattnera4997152009-02-20 18:43:26 +00002739 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Narofff36987c2007-11-04 22:37:50 +00002740 // Push any user argument types.
Chris Lattnera4997152009-02-20 18:43:26 +00002741 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2742 E = OMD->param_end(); PI != E; ++PI) {
2743 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump11289f42009-09-09 15:08:12 +00002744 ? Context->getObjCIdType()
Chris Lattnera4997152009-02-20 18:43:26 +00002745 : (*PI)->getType();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002746 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00002747 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002748 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002749 t = Context->getPointerType(BPT->getPointeeType());
2750 }
Steve Naroff98eb8d12007-11-05 14:36:37 +00002751 ArgTypes.push_back(t);
2752 }
Chris Lattnera4997152009-02-20 18:43:26 +00002753 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2754 ? Context->getObjCIdType() : OMD->getResultType();
Steve Narofff36987c2007-11-04 22:37:50 +00002755 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002756 returnType = Context->getObjCIdType();
Steve Narofff36987c2007-11-04 22:37:50 +00002757 }
2758 // Get the type, we will need to reference it in a couple spots.
Steve Naroff7fa2f042007-11-15 10:28:18 +00002759 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002760
Steve Narofff36987c2007-11-04 22:37:50 +00002761 // Create a reference to the objc_msgSend() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002762 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002763 SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002764
Mike Stump11289f42009-09-09 15:08:12 +00002765 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Narofff36987c2007-11-04 22:37:50 +00002766 // If we don't do this cast, we get the following bizarre warning/note:
2767 // xx.m:13: warning: function called through a non-compatible type
2768 // xx.m:13: note: if this code is reached, the program will abort
John McCall97513962010-01-15 18:39:57 +00002769 cast = NoTypeInfoCStyleCastExpr(Context,
2770 Context->getPointerType(Context->VoidTy),
2771 CastExpr::CK_Unknown, DRE);
Mike Stump11289f42009-09-09 15:08:12 +00002772
Steve Narofff36987c2007-11-04 22:37:50 +00002773 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002774 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002775 &ArgTypes[0], ArgTypes.size(),
Steve Naroff327f0f42008-03-18 02:02:04 +00002776 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002777 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Narofff36987c2007-11-04 22:37:50 +00002778 castType = Context->getPointerType(castType);
John McCall97513962010-01-15 18:39:57 +00002779 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
2780 cast);
Steve Narofff36987c2007-11-04 22:37:50 +00002781
2782 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00002783 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00002784
John McCall9dd450b2009-09-21 23:43:11 +00002785 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002786 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002787 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002788 FT->getResultType(), SourceLocation());
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002789 Stmt *ReplacingStmt = CE;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002790 if (MsgSendStretFlavor) {
2791 // We have the method which returns a struct/union. Must also generate
2792 // call to objc_msgSend_stret and hang both varieties on a conditional
2793 // expression which dictate which one to envoke depending on size of
2794 // method's return type.
Mike Stump11289f42009-09-09 15:08:12 +00002795
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002796 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002797 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002798 SourceLocation());
2799 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall97513962010-01-15 18:39:57 +00002800 cast = NoTypeInfoCStyleCastExpr(Context,
2801 Context->getPointerType(Context->VoidTy),
2802 CastExpr::CK_Unknown, STDRE);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002803 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002804 castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002805 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002806 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002807 castType = Context->getPointerType(castType);
John McCall97513962010-01-15 18:39:57 +00002808 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
2809 cast);
Mike Stump11289f42009-09-09 15:08:12 +00002810
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002811 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00002812 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00002813
John McCall9dd450b2009-09-21 23:43:11 +00002814 FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002815 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002816 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002817 FT->getResultType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002818
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002819 // Build sizeof(returnType)
Mike Stump11289f42009-09-09 15:08:12 +00002820 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCallbcd03502009-12-07 02:54:59 +00002821 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl6f282892008-11-11 17:56:53 +00002822 Context->getSizeType(),
2823 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002824 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2825 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2826 // For X86 it is more complicated and some kind of target specific routine
2827 // is needed to decide what to do.
Mike Stump11289f42009-09-09 15:08:12 +00002828 unsigned IntSize =
Chris Lattner37e05872008-03-05 18:54:05 +00002829 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Mike Stump11289f42009-09-09 15:08:12 +00002830 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002831 Context->IntTy,
2832 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002833 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
2834 BinaryOperator::LE,
2835 Context->IntTy,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002836 SourceLocation());
2837 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump11289f42009-09-09 15:08:12 +00002838 ConditionalOperator *CondExpr =
Douglas Gregor7e112b02009-08-26 14:37:04 +00002839 new (Context) ConditionalOperator(lessThanExpr,
2840 SourceLocation(), CE,
2841 SourceLocation(), STCE, returnType);
Ted Kremenek5a201952009-02-07 01:47:29 +00002842 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002843 }
Mike Stump11289f42009-09-09 15:08:12 +00002844 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002845 return ReplacingStmt;
2846}
2847
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002848Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002849 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Mike Stump11289f42009-09-09 15:08:12 +00002850
Steve Naroff574440f2007-10-24 22:48:43 +00002851 // Now do the actual rewrite.
Chris Lattner2e0d2602008-01-31 19:37:57 +00002852 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00002853
2854 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002855 return ReplacingStmt;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002856}
2857
Steve Naroffd9803712009-04-29 16:37:50 +00002858// typedef struct objc_object Protocol;
2859QualType RewriteObjC::getProtocolType() {
2860 if (!ProtocolTypeDecl) {
John McCallbcd03502009-12-07 02:54:59 +00002861 TypeSourceInfo *TInfo
2862 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroffd9803712009-04-29 16:37:50 +00002863 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002864 SourceLocation(),
Steve Naroffd9803712009-04-29 16:37:50 +00002865 &Context->Idents.get("Protocol"),
John McCallbcd03502009-12-07 02:54:59 +00002866 TInfo);
Steve Naroffd9803712009-04-29 16:37:50 +00002867 }
2868 return Context->getTypeDeclType(ProtocolTypeDecl);
2869}
2870
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00002871/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroffd9803712009-04-29 16:37:50 +00002872/// a synthesized/forward data reference (to the protocol's metadata).
2873/// The forward references (and metadata) are generated in
2874/// RewriteObjC::HandleTranslationUnit().
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002875Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroffd9803712009-04-29 16:37:50 +00002876 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
2877 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump11289f42009-09-09 15:08:12 +00002878 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregored6c7442009-11-23 11:41:28 +00002879 ID, getProtocolType(), 0, VarDecl::Extern);
Steve Naroffd9803712009-04-29 16:37:50 +00002880 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
2881 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
2882 Context->getPointerType(DRE->getType()),
2883 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00002884 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
2885 CastExpr::CK_Unknown,
2886 DerefExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00002887 ReplaceStmt(Exp, castExpr);
2888 ProtocolExprDecls.insert(Exp->getProtocol());
Mike Stump11289f42009-09-09 15:08:12 +00002889 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00002890 return castExpr;
Mike Stump11289f42009-09-09 15:08:12 +00002891
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00002892}
2893
Mike Stump11289f42009-09-09 15:08:12 +00002894bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002895 const char *endBuf) {
2896 while (startBuf < endBuf) {
2897 if (*startBuf == '#') {
2898 // Skip whitespace.
2899 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2900 ;
2901 if (!strncmp(startBuf, "if", strlen("if")) ||
2902 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2903 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2904 !strncmp(startBuf, "define", strlen("define")) ||
2905 !strncmp(startBuf, "undef", strlen("undef")) ||
2906 !strncmp(startBuf, "else", strlen("else")) ||
2907 !strncmp(startBuf, "elif", strlen("elif")) ||
2908 !strncmp(startBuf, "endif", strlen("endif")) ||
2909 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2910 !strncmp(startBuf, "include", strlen("include")) ||
2911 !strncmp(startBuf, "import", strlen("import")) ||
2912 !strncmp(startBuf, "include_next", strlen("include_next")))
2913 return true;
2914 }
2915 startBuf++;
2916 }
2917 return false;
2918}
2919
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002920/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002921/// an objective-c class with ivars.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002922void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002923 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002924 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Mike Stump11289f42009-09-09 15:08:12 +00002925 assert(CDecl->getNameAsCString() &&
Douglas Gregor77324f32008-11-17 14:58:09 +00002926 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00002927 // Do not synthesize more than once.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002928 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00002929 return;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002930 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattner8d1c04f2008-03-16 21:08:55 +00002931 int NumIvars = CDecl->ivar_size();
Steve Naroffdde78982007-11-14 19:25:57 +00002932 SourceLocation LocStart = CDecl->getLocStart();
2933 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00002934
Steve Naroffdde78982007-11-14 19:25:57 +00002935 const char *startBuf = SM->getCharacterData(LocStart);
2936 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00002937
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002938 // If no ivars and no root or if its root, directly or indirectly,
2939 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattner8d1c04f2008-03-16 21:08:55 +00002940 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2941 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner184e65d2009-04-14 23:22:57 +00002942 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002943 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002944 return;
2945 }
Mike Stump11289f42009-09-09 15:08:12 +00002946
2947 // FIXME: This has potential of causing problem. If
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002948 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002949 Result += "\nstruct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002950 Result += CDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00002951 if (LangOpts.Microsoft)
2952 Result += "_IMPL";
Steve Naroffdc5b6b22008-03-12 00:25:36 +00002953
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002954 if (NumIvars > 0) {
Steve Naroffdde78982007-11-14 19:25:57 +00002955 const char *cursor = strchr(startBuf, '{');
Mike Stump11289f42009-09-09 15:08:12 +00002956 assert((cursor && endBuf)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002957 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002958 // If the buffer contains preprocessor directives, we do more fine-grained
2959 // rewrites. This is intended to fix code that looks like (which occurs in
2960 // NSURL.h, for example):
2961 //
2962 // #ifdef XYZ
2963 // @interface Foo : NSObject
2964 // #else
2965 // @interface FooBar : NSObject
2966 // #endif
2967 // {
2968 // int i;
2969 // }
2970 // @end
2971 //
2972 // This clause is segregated to avoid breaking the common case.
2973 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump11289f42009-09-09 15:08:12 +00002974 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002975 CDecl->getClassLoc();
2976 const char *endHeader = SM->getCharacterData(L);
Chris Lattner184e65d2009-04-14 23:22:57 +00002977 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002978
Chris Lattnerf5b77512009-02-20 18:18:36 +00002979 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002980 // advance to the end of the referenced protocols.
2981 while (endHeader < cursor && *endHeader != '>') endHeader++;
2982 endHeader++;
2983 }
2984 // rewrite the original header
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002985 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002986 } else {
2987 // rewrite the original header *without* disturbing the '{'
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002988 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002989 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002990 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroffdde78982007-11-14 19:25:57 +00002991 Result = "\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002992 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00002993 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002994 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00002995 Result += "_IVARS;\n";
Mike Stump11289f42009-09-09 15:08:12 +00002996
Steve Naroffdde78982007-11-14 19:25:57 +00002997 // insert the super class structure definition.
Chris Lattner1780a852008-01-31 19:42:41 +00002998 SourceLocation OnePastCurly =
2999 LocStart.getFileLocWithOffset(cursor-startBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003000 InsertText(OnePastCurly, Result);
Steve Naroffdde78982007-11-14 19:25:57 +00003001 }
3002 cursor++; // past '{'
Mike Stump11289f42009-09-09 15:08:12 +00003003
Steve Naroffdde78982007-11-14 19:25:57 +00003004 // Now comment out any visibility specifiers.
3005 while (cursor < endBuf) {
3006 if (*cursor == '@') {
3007 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner174a8252007-11-14 22:57:51 +00003008 // Skip whitespace.
3009 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3010 /*scan*/;
3011
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003012 // FIXME: presence of @public, etc. inside comment results in
3013 // this transformation as well, which is still correct c-code.
Steve Naroffdde78982007-11-14 19:25:57 +00003014 if (!strncmp(cursor, "public", strlen("public")) ||
3015 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffaf91b9a2008-04-04 22:34:24 +00003016 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003017 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003018 InsertText(atLoc, "// ");
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003019 }
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003020 // FIXME: If there are cases where '<' is used in ivar declaration part
3021 // of user code, then scan the ivar list and use needToScanForQualifiers
3022 // for type checking.
3023 else if (*cursor == '<') {
3024 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003025 InsertText(atLoc, "/* ");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003026 cursor = strchr(cursor, '>');
3027 cursor++;
3028 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003029 InsertText(atLoc, " */");
Steve Naroff295570a2008-10-30 12:09:33 +00003030 } else if (*cursor == '^') { // rewrite block specifier.
3031 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003032 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003033 }
Steve Naroffdde78982007-11-14 19:25:57 +00003034 cursor++;
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003035 }
Steve Naroffdde78982007-11-14 19:25:57 +00003036 // Don't forget to add a ';'!!
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003037 InsertText(LocEnd.getFileLocWithOffset(1), ";");
Steve Naroffdde78982007-11-14 19:25:57 +00003038 } else { // we don't have any instance variables - insert super struct.
Chris Lattner184e65d2009-04-14 23:22:57 +00003039 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroffdde78982007-11-14 19:25:57 +00003040 Result += " {\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003041 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003042 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003043 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003044 Result += "_IVARS;\n};\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003045 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003046 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003047 // Mark this struct as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003048 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff13e74872008-05-06 18:26:51 +00003049 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003050}
3051
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003052// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003053/// class methods.
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003054template<typename MethodIterator>
3055void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3056 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +00003057 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003058 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +00003059 const char *ClassName,
3060 std::string &Result) {
Chris Lattner31bc07e2007-12-12 07:46:12 +00003061 if (MethodBegin == MethodEnd) return;
Mike Stump11289f42009-09-09 15:08:12 +00003062
Chris Lattner31bc07e2007-12-12 07:46:12 +00003063 if (!objc_impl_method) {
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003064 /* struct _objc_method {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003065 SEL _cmd;
3066 char *method_types;
3067 void *_imp;
3068 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003069 */
Chris Lattner211f8b82007-10-25 17:07:24 +00003070 Result += "\nstruct _objc_method {\n";
3071 Result += "\tSEL _cmd;\n";
3072 Result += "\tchar *method_types;\n";
3073 Result += "\tvoid *_imp;\n";
3074 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003075
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003076 objc_impl_method = true;
Fariborz Jahanian74a1cfa2007-10-19 00:36:46 +00003077 }
Mike Stump11289f42009-09-09 15:08:12 +00003078
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003079 // Build _objc_method_list for class's methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003080
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003081 /* struct {
3082 struct _objc_method_list *next_method;
3083 int method_count;
3084 struct _objc_method method_list[];
3085 }
3086 */
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003087 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003088 Result += "\nstatic struct {\n";
3089 Result += "\tstruct _objc_method_list *next_method;\n";
3090 Result += "\tint method_count;\n";
3091 Result += "\tstruct _objc_method method_list[";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003092 Result += utostr(NumMethods);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003093 Result += "];\n} _OBJC_";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003094 Result += prefix;
3095 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3096 Result += "_METHODS_";
3097 Result += ClassName;
Steve Naroffb327e492008-03-12 17:18:30 +00003098 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003099 Result += IsInstanceMethod ? "inst" : "cls";
3100 Result += "_meth\")))= ";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003101 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003102
Chris Lattner31bc07e2007-12-12 07:46:12 +00003103 Result += "\t,{{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003104 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattner31bc07e2007-12-12 07:46:12 +00003105 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003106 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattner31bc07e2007-12-12 07:46:12 +00003107 Result += "\", \"";
3108 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003109 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003110 Result += MethodInternalNames[*MethodBegin];
3111 Result += "}\n";
3112 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3113 Result += "\t ,{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003114 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003115 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003116 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003117 Result += "\", \"";
3118 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003119 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003120 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanian56338352007-11-13 21:02:00 +00003121 Result += "}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003122 }
Chris Lattner31bc07e2007-12-12 07:46:12 +00003123 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003124}
3125
Steve Naroffd9803712009-04-29 16:37:50 +00003126/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner390d39a2008-07-21 21:32:27 +00003127void RewriteObjC::
Steve Naroffd9803712009-04-29 16:37:50 +00003128RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
3129 const char *ClassName, std::string &Result) {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003130 static bool objc_protocol_methods = false;
Steve Naroffd9803712009-04-29 16:37:50 +00003131
3132 // Output struct protocol_methods holder of method selector and type.
3133 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3134 /* struct protocol_methods {
3135 SEL _cmd;
3136 char *method_types;
3137 }
3138 */
3139 Result += "\nstruct _protocol_methods {\n";
3140 Result += "\tstruct objc_selector *_cmd;\n";
3141 Result += "\tchar *method_types;\n";
3142 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003143
Steve Naroffd9803712009-04-29 16:37:50 +00003144 objc_protocol_methods = true;
3145 }
3146 // Do not synthesize the protocol more than once.
3147 if (ObjCSynthesizedProtocols.count(PDecl))
3148 return;
Mike Stump11289f42009-09-09 15:08:12 +00003149
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003150 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3151 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3152 PDecl->instmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003153 /* struct _objc_protocol_method_list {
3154 int protocol_method_count;
3155 struct protocol_methods protocols[];
3156 }
Steve Naroff251084d2008-03-12 01:06:30 +00003157 */
Steve Naroffd9803712009-04-29 16:37:50 +00003158 Result += "\nstatic struct {\n";
3159 Result += "\tint protocol_method_count;\n";
3160 Result += "\tstruct _protocol_methods protocol_methods[";
3161 Result += utostr(NumMethods);
3162 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3163 Result += PDecl->getNameAsString();
3164 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3165 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003166
Steve Naroffd9803712009-04-29 16:37:50 +00003167 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003168 for (ObjCProtocolDecl::instmeth_iterator
3169 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003170 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003171 if (I == PDecl->instmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003172 Result += "\t ,{{(struct objc_selector *)\"";
3173 else
3174 Result += "\t ,{(struct objc_selector *)\"";
3175 Result += (*I)->getSelector().getAsString().c_str();
3176 std::string MethodTypeString;
3177 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3178 Result += "\", \"";
3179 Result += MethodTypeString;
3180 Result += "\"}\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003181 }
Steve Naroffd9803712009-04-29 16:37:50 +00003182 Result += "\t }\n};\n";
3183 }
Mike Stump11289f42009-09-09 15:08:12 +00003184
Steve Naroffd9803712009-04-29 16:37:50 +00003185 // Output class methods declared in this protocol.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003186 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3187 PDecl->classmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003188 if (NumMethods > 0) {
3189 /* struct _objc_protocol_method_list {
3190 int protocol_method_count;
3191 struct protocol_methods protocols[];
3192 }
3193 */
3194 Result += "\nstatic struct {\n";
3195 Result += "\tint protocol_method_count;\n";
3196 Result += "\tstruct _protocol_methods protocol_methods[";
3197 Result += utostr(NumMethods);
3198 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3199 Result += PDecl->getNameAsString();
3200 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3201 "{\n\t";
3202 Result += utostr(NumMethods);
3203 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003204
Steve Naroffd9803712009-04-29 16:37:50 +00003205 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003206 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003207 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003208 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003209 if (I == PDecl->classmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003210 Result += "\t ,{{(struct objc_selector *)\"";
3211 else
3212 Result += "\t ,{(struct objc_selector *)\"";
3213 Result += (*I)->getSelector().getAsString().c_str();
3214 std::string MethodTypeString;
3215 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3216 Result += "\", \"";
3217 Result += MethodTypeString;
3218 Result += "\"}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003219 }
Steve Naroffd9803712009-04-29 16:37:50 +00003220 Result += "\t }\n};\n";
3221 }
3222
3223 // Output:
3224 /* struct _objc_protocol {
3225 // Objective-C 1.0 extensions
3226 struct _objc_protocol_extension *isa;
3227 char *protocol_name;
3228 struct _objc_protocol **protocol_list;
3229 struct _objc_protocol_method_list *instance_methods;
3230 struct _objc_protocol_method_list *class_methods;
Mike Stump11289f42009-09-09 15:08:12 +00003231 };
Steve Naroffd9803712009-04-29 16:37:50 +00003232 */
3233 static bool objc_protocol = false;
3234 if (!objc_protocol) {
3235 Result += "\nstruct _objc_protocol {\n";
3236 Result += "\tstruct _objc_protocol_extension *isa;\n";
3237 Result += "\tchar *protocol_name;\n";
3238 Result += "\tstruct _objc_protocol **protocol_list;\n";
3239 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3240 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003241 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003242
Steve Naroffd9803712009-04-29 16:37:50 +00003243 objc_protocol = true;
Chris Lattner388f6e92008-07-21 21:33:21 +00003244 }
Mike Stump11289f42009-09-09 15:08:12 +00003245
Steve Naroffd9803712009-04-29 16:37:50 +00003246 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3247 Result += PDecl->getNameAsString();
3248 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3249 "{\n\t0, \"";
3250 Result += PDecl->getNameAsString();
3251 Result += "\", 0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003252 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003253 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3254 Result += PDecl->getNameAsString();
3255 Result += ", ";
3256 }
3257 else
3258 Result += "0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003259 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003260 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3261 Result += PDecl->getNameAsString();
3262 Result += "\n";
3263 }
3264 else
3265 Result += "0\n";
3266 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003267
Steve Naroffd9803712009-04-29 16:37:50 +00003268 // Mark this protocol as having been generated.
3269 if (!ObjCSynthesizedProtocols.insert(PDecl))
3270 assert(false && "protocol already synthesized");
3271
3272}
3273
3274void RewriteObjC::
3275RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3276 const char *prefix, const char *ClassName,
3277 std::string &Result) {
3278 if (Protocols.empty()) return;
Mike Stump11289f42009-09-09 15:08:12 +00003279
Steve Naroffd9803712009-04-29 16:37:50 +00003280 for (unsigned i = 0; i != Protocols.size(); i++)
3281 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3282
Chris Lattner388f6e92008-07-21 21:33:21 +00003283 // Output the top lovel protocol meta-data for the class.
3284 /* struct _objc_protocol_list {
3285 struct _objc_protocol_list *next;
3286 int protocol_count;
3287 struct _objc_protocol *class_protocols[];
3288 }
3289 */
3290 Result += "\nstatic struct {\n";
3291 Result += "\tstruct _objc_protocol_list *next;\n";
3292 Result += "\tint protocol_count;\n";
3293 Result += "\tstruct _objc_protocol *class_protocols[";
3294 Result += utostr(Protocols.size());
3295 Result += "];\n} _OBJC_";
3296 Result += prefix;
3297 Result += "_PROTOCOLS_";
3298 Result += ClassName;
3299 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3300 "{\n\t0, ";
3301 Result += utostr(Protocols.size());
3302 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003303
Chris Lattner388f6e92008-07-21 21:33:21 +00003304 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003305 Result += Protocols[0]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003306 Result += " \n";
Mike Stump11289f42009-09-09 15:08:12 +00003307
Chris Lattner388f6e92008-07-21 21:33:21 +00003308 for (unsigned i = 1; i != Protocols.size(); i++) {
3309 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003310 Result += Protocols[i]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003311 Result += "\n";
3312 }
3313 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003314}
3315
Steve Naroffd9803712009-04-29 16:37:50 +00003316
Mike Stump11289f42009-09-09 15:08:12 +00003317/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003318/// implementation.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003319void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003320 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003321 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003322 // Find category declaration for this implementation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003323 ObjCCategoryDecl *CDecl;
Mike Stump11289f42009-09-09 15:08:12 +00003324 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003325 CDecl = CDecl->getNextClassCategory())
3326 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3327 break;
Mike Stump11289f42009-09-09 15:08:12 +00003328
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003329 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003330 FullCategoryName += '_';
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003331 FullCategoryName += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003332
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003333 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003334 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003335 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003336
3337 // If any of our property implementations have associated getters or
3338 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003339 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3340 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003341 Prop != PropEnd; ++Prop) {
3342 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3343 continue;
3344 if (!(*Prop)->getPropertyIvarDecl())
3345 continue;
3346 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3347 if (!PD)
3348 continue;
3349 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3350 InstanceMethods.push_back(Getter);
3351 if (PD->isReadOnly())
3352 continue;
3353 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3354 InstanceMethods.push_back(Setter);
3355 }
3356 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003357 true, "CATEGORY_", FullCategoryName.c_str(),
3358 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003359
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003360 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003361 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003362 false, "CATEGORY_", FullCategoryName.c_str(),
3363 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003364
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003365 // Protocols referenced in class declaration?
Fariborz Jahanian989e0392007-11-13 22:09:49 +00003366 // Null CDecl is case of a category implementation with no category interface
3367 if (CDecl)
Steve Naroffd9803712009-04-29 16:37:50 +00003368 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3369 FullCategoryName.c_str(), Result);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003370 /* struct _objc_category {
3371 char *category_name;
3372 char *class_name;
3373 struct _objc_method_list *instance_methods;
3374 struct _objc_method_list *class_methods;
3375 struct _objc_protocol_list *protocols;
3376 // Objective-C 1.0 extensions
3377 uint32_t size; // sizeof (struct _objc_category)
Mike Stump11289f42009-09-09 15:08:12 +00003378 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003379 // @property decl.
Mike Stump11289f42009-09-09 15:08:12 +00003380 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003381 */
Mike Stump11289f42009-09-09 15:08:12 +00003382
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003383 static bool objc_category = false;
3384 if (!objc_category) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003385 Result += "\nstruct _objc_category {\n";
3386 Result += "\tchar *category_name;\n";
3387 Result += "\tchar *class_name;\n";
3388 Result += "\tstruct _objc_method_list *instance_methods;\n";
3389 Result += "\tstruct _objc_method_list *class_methods;\n";
3390 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003391 Result += "\tunsigned int size;\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003392 Result += "\tstruct _objc_property_list *instance_properties;\n";
3393 Result += "};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003394 objc_category = true;
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003395 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003396 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3397 Result += FullCategoryName;
Steve Naroffb327e492008-03-12 17:18:30 +00003398 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003399 Result += IDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003400 Result += "\"\n\t, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003401 Result += ClassDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003402 Result += "\"\n";
Mike Stump11289f42009-09-09 15:08:12 +00003403
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003404 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003405 Result += "\t, (struct _objc_method_list *)"
3406 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3407 Result += FullCategoryName;
3408 Result += "\n";
3409 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003410 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003411 Result += "\t, 0\n";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003412 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003413 Result += "\t, (struct _objc_method_list *)"
3414 "&_OBJC_CATEGORY_CLASS_METHODS_";
3415 Result += FullCategoryName;
3416 Result += "\n";
3417 }
3418 else
3419 Result += "\t, 0\n";
Mike Stump11289f42009-09-09 15:08:12 +00003420
Chris Lattnerf5b77512009-02-20 18:18:36 +00003421 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump11289f42009-09-09 15:08:12 +00003422 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003423 Result += FullCategoryName;
3424 Result += "\n";
3425 }
3426 else
3427 Result += "\t, 0\n";
3428 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003429}
3430
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003431/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3432/// ivar offset.
Mike Stump11289f42009-09-09 15:08:12 +00003433void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
3434 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003435 std::string &Result) {
Steve Naroffde7d0f62008-07-16 18:22:22 +00003436 if (ivar->isBitField()) {
3437 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3438 // place all bitfields at offset 0.
3439 Result += "0";
3440 } else {
3441 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003442 Result += IDecl->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003443 if (LangOpts.Microsoft)
3444 Result += "_IMPL";
3445 Result += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003446 Result += ivar->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003447 Result += ")";
3448 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003449}
3450
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003451//===----------------------------------------------------------------------===//
3452// Meta Data Emission
3453//===----------------------------------------------------------------------===//
3454
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003455void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003456 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003457 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00003458
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003459 // Explictly declared @interface's are already synthesized.
Steve Naroffaac654a2009-04-20 20:09:33 +00003460 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump11289f42009-09-09 15:08:12 +00003461 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003462 // produce correct synthesis as yet.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003463 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003464 }
Mike Stump11289f42009-09-09 15:08:12 +00003465
Chris Lattner30d23e82007-12-12 07:56:42 +00003466 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003467 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump11289f42009-09-09 15:08:12 +00003468 ? IDecl->ivar_size()
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003469 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003470 if (NumIvars > 0) {
3471 static bool objc_ivar = false;
3472 if (!objc_ivar) {
3473 /* struct _objc_ivar {
3474 char *ivar_name;
3475 char *ivar_type;
3476 int ivar_offset;
Mike Stump11289f42009-09-09 15:08:12 +00003477 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003478 */
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003479 Result += "\nstruct _objc_ivar {\n";
3480 Result += "\tchar *ivar_name;\n";
3481 Result += "\tchar *ivar_type;\n";
3482 Result += "\tint ivar_offset;\n";
3483 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003484
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003485 objc_ivar = true;
3486 }
3487
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003488 /* struct {
3489 int ivar_count;
3490 struct _objc_ivar ivar_list[nIvars];
Mike Stump11289f42009-09-09 15:08:12 +00003491 };
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003492 */
Mike Stump11289f42009-09-09 15:08:12 +00003493 Result += "\nstatic struct {\n";
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003494 Result += "\tint ivar_count;\n";
3495 Result += "\tstruct _objc_ivar ivar_list[";
3496 Result += utostr(NumIvars);
3497 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003498 Result += IDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003499 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003500 "{\n\t";
3501 Result += utostr(NumIvars);
3502 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003503
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003504 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor5f662052009-04-23 03:23:08 +00003505 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003506 if (!IDecl->ivar_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00003507 for (ObjCImplementationDecl::ivar_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003508 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor5f662052009-04-23 03:23:08 +00003509 IV != IVEnd; ++IV)
3510 IVars.push_back(*IV);
3511 IVI = IVars.begin();
3512 IVE = IVars.end();
Chris Lattner30d23e82007-12-12 07:56:42 +00003513 } else {
3514 IVI = CDecl->ivar_begin();
3515 IVE = CDecl->ivar_end();
3516 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003517 Result += "\t,{{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003518 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003519 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003520 std::string TmpString, StrEncoding;
3521 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3522 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003523 Result += StrEncoding;
3524 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003525 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003526 Result += "}\n";
Chris Lattner30d23e82007-12-12 07:56:42 +00003527 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003528 Result += "\t ,{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003529 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003530 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003531 std::string TmpString, StrEncoding;
3532 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3533 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003534 Result += StrEncoding;
3535 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003536 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003537 Result += "}\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003538 }
Mike Stump11289f42009-09-09 15:08:12 +00003539
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003540 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003541 }
Mike Stump11289f42009-09-09 15:08:12 +00003542
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003543 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003544 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003545 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003546
3547 // If any of our property implementations have associated getters or
3548 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003549 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3550 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003551 Prop != PropEnd; ++Prop) {
3552 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3553 continue;
3554 if (!(*Prop)->getPropertyIvarDecl())
3555 continue;
3556 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3557 if (!PD)
3558 continue;
3559 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3560 InstanceMethods.push_back(Getter);
3561 if (PD->isReadOnly())
3562 continue;
3563 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3564 InstanceMethods.push_back(Setter);
3565 }
3566 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003567 true, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003568
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003569 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003570 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003571 false, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003572
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003573 // Protocols referenced in class declaration?
Steve Naroffd9803712009-04-29 16:37:50 +00003574 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3575 "CLASS", CDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003576
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003577 // Declaration of class/meta-class metadata
3578 /* struct _objc_class {
3579 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003580 const char *super_class_name;
3581 char *name;
3582 long version;
3583 long info;
3584 long instance_size;
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003585 struct _objc_ivar_list *ivars;
3586 struct _objc_method_list *methods;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003587 struct objc_cache *cache;
3588 struct objc_protocol_list *protocols;
3589 const char *ivar_layout;
3590 struct _objc_class_ext *ext;
Mike Stump11289f42009-09-09 15:08:12 +00003591 };
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003592 */
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003593 static bool objc_class = false;
3594 if (!objc_class) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003595 Result += "\nstruct _objc_class {\n";
3596 Result += "\tstruct _objc_class *isa;\n";
3597 Result += "\tconst char *super_class_name;\n";
3598 Result += "\tchar *name;\n";
3599 Result += "\tlong version;\n";
3600 Result += "\tlong info;\n";
3601 Result += "\tlong instance_size;\n";
3602 Result += "\tstruct _objc_ivar_list *ivars;\n";
3603 Result += "\tstruct _objc_method_list *methods;\n";
3604 Result += "\tstruct objc_cache *cache;\n";
3605 Result += "\tstruct _objc_protocol_list *protocols;\n";
3606 Result += "\tconst char *ivar_layout;\n";
3607 Result += "\tstruct _objc_class_ext *ext;\n";
3608 Result += "};\n";
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003609 objc_class = true;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003610 }
Mike Stump11289f42009-09-09 15:08:12 +00003611
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003612 // Meta-class metadata generation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003613 ObjCInterfaceDecl *RootClass = 0;
3614 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003615 while (SuperClass) {
3616 RootClass = SuperClass;
3617 SuperClass = SuperClass->getSuperClass();
3618 }
3619 SuperClass = CDecl->getSuperClass();
Mike Stump11289f42009-09-09 15:08:12 +00003620
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003621 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003622 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003623 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003624 "{\n\t(struct _objc_class *)\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003625 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003626 Result += "\"";
3627
3628 if (SuperClass) {
3629 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003630 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003631 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003632 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003633 Result += "\"";
3634 }
3635 else {
3636 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003637 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003638 Result += "\"";
3639 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003640 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003641 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003642 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003643 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff0b844f02008-03-11 18:14:26 +00003644 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003645 Result += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003646 Result += "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003647 }
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003648 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003649 Result += ", 0\n";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003650 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003651 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003652 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003653 Result += ",0,0\n";
3654 }
Fariborz Jahanian486f7182007-10-24 20:54:23 +00003655 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003656 Result += "\t,0,0,0,0\n";
3657 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003658
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003659 // class metadata generation.
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003660 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003661 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003662 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003663 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003664 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003665 if (SuperClass) {
3666 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003667 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003668 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003669 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003670 Result += "\"";
3671 }
3672 else {
3673 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003674 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003675 Result += "\"";
3676 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003677 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003678 Result += ", 0,1";
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003679 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003680 Result += ",0";
3681 else {
3682 // class has size. Must synthesize its size.
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00003683 Result += ",sizeof(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003684 Result += CDecl->getNameAsString();
Steve Naroff14a07462008-03-10 23:33:22 +00003685 if (LangOpts.Microsoft)
3686 Result += "_IMPL";
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003687 Result += ")";
3688 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003689 if (NumIvars > 0) {
Steve Naroff17978c42008-03-11 17:37:02 +00003690 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003691 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003692 Result += "\n\t";
3693 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003694 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003695 Result += ",0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003696 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003697 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003698 Result += CDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003699 Result += ", 0\n\t";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003700 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003701 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003702 Result += ",0,0";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003703 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003704 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003705 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003706 Result += ", 0,0\n";
3707 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003708 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003709 Result += ",0,0,0\n";
3710 Result += "};\n";
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003711}
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003712
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003713/// RewriteImplementations - This routine rewrites all method implementations
3714/// and emits meta-data.
3715
Steve Narofff8cfd162008-11-13 20:07:04 +00003716void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003717 int ClsDefCount = ClassImplementation.size();
3718 int CatDefCount = CategoryImplementation.size();
Mike Stump11289f42009-09-09 15:08:12 +00003719
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003720 // Rewrite implemented methods
3721 for (int i = 0; i < ClsDefCount; i++)
3722 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003723
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00003724 for (int i = 0; i < CatDefCount; i++)
3725 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofff8cfd162008-11-13 20:07:04 +00003726}
Mike Stump11289f42009-09-09 15:08:12 +00003727
Steve Narofff8cfd162008-11-13 20:07:04 +00003728void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3729 int ClsDefCount = ClassImplementation.size();
3730 int CatDefCount = CategoryImplementation.size();
3731
Steve Naroff30ac2222008-05-07 21:23:49 +00003732 // This is needed for determining instance variable offsets.
Fariborz Jahanian9ab63492010-01-07 18:31:42 +00003733 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003734 // For each implemented class, write out all its meta data.
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003735 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003736 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump11289f42009-09-09 15:08:12 +00003737
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003738 // For each implemented category, write out all its meta data.
3739 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003740 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroffd9803712009-04-29 16:37:50 +00003741
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003742 // Write objc_symtab metadata
3743 /*
3744 struct _objc_symtab
3745 {
3746 long sel_ref_cnt;
3747 SEL *refs;
3748 short cls_def_cnt;
3749 short cat_def_cnt;
3750 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump11289f42009-09-09 15:08:12 +00003751 };
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003752 */
Mike Stump11289f42009-09-09 15:08:12 +00003753
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003754 Result += "\nstruct _objc_symtab {\n";
3755 Result += "\tlong sel_ref_cnt;\n";
3756 Result += "\tSEL *refs;\n";
3757 Result += "\tshort cls_def_cnt;\n";
3758 Result += "\tshort cat_def_cnt;\n";
3759 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3760 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003761
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003762 Result += "static struct _objc_symtab "
Steve Naroffb327e492008-03-12 17:18:30 +00003763 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003764 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003765 + ", " + utostr(CatDefCount) + "\n";
3766 for (int i = 0; i < ClsDefCount; i++) {
3767 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003768 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003769 Result += "\n";
3770 }
Mike Stump11289f42009-09-09 15:08:12 +00003771
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003772 for (int i = 0; i < CatDefCount; i++) {
3773 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003774 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003775 Result += "_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003776 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003777 Result += "\n";
3778 }
Mike Stump11289f42009-09-09 15:08:12 +00003779
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003780 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003781
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003782 // Write objc_module metadata
Mike Stump11289f42009-09-09 15:08:12 +00003783
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003784 /*
3785 struct _objc_module {
3786 long version;
3787 long size;
3788 const char *name;
3789 struct _objc_symtab *symtab;
3790 }
3791 */
Mike Stump11289f42009-09-09 15:08:12 +00003792
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003793 Result += "\nstruct _objc_module {\n";
3794 Result += "\tlong version;\n";
3795 Result += "\tlong size;\n";
3796 Result += "\tconst char *name;\n";
3797 Result += "\tstruct _objc_symtab *symtab;\n";
3798 Result += "};\n\n";
3799 Result += "static struct _objc_module "
Steve Naroffb327e492008-03-12 17:18:30 +00003800 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003801 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003802 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003803 Result += "};\n\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003804
3805 if (LangOpts.Microsoft) {
Steve Naroffd9803712009-04-29 16:37:50 +00003806 if (ProtocolExprDecls.size()) {
3807 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
3808 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump11289f42009-09-09 15:08:12 +00003809 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00003810 E = ProtocolExprDecls.end(); I != E; ++I) {
3811 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
3812 Result += (*I)->getNameAsString();
3813 Result += " = &_OBJC_PROTOCOL_";
3814 Result += (*I)->getNameAsString();
3815 Result += ";\n";
3816 }
3817 Result += "#pragma data_seg(pop)\n\n";
3818 }
Steve Naroff945a3b12008-03-10 20:43:59 +00003819 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffcab93d52008-05-07 00:06:16 +00003820 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003821 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3822 Result += "&_OBJC_MODULES;\n";
3823 Result += "#pragma data_seg(pop)\n\n";
3824 }
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003825}
Chris Lattnera7c19fe2007-10-16 22:36:42 +00003826
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003827void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3828 const std::string &Name,
3829 ValueDecl *VD) {
3830 assert(BlockByRefDeclNo.count(VD) &&
3831 "RewriteByRefString: ByRef decl missing");
3832 ResultStr += "struct __Block_byref_" + Name +
3833 "_" + utostr(BlockByRefDeclNo[VD]) ;
3834}
3835
Steve Naroff677ab3a2008-10-27 17:20:55 +00003836std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3837 const char *funcName,
3838 std::string Tag) {
3839 const FunctionType *AFT = CE->getFunctionType();
3840 QualType RT = AFT->getResultType();
3841 std::string StructRef = "struct " + Tag;
3842 std::string S = "static " + RT.getAsString() + " __" +
3843 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00003844
Steve Naroff677ab3a2008-10-27 17:20:55 +00003845 BlockDecl *BD = CE->getBlockDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003846
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003847 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump11289f42009-09-09 15:08:12 +00003848 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Narofff26a1d42009-02-02 17:19:26 +00003849 // block (to reference imported block decl refs).
3850 S += "(" + StructRef + " *__cself)";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003851 } else if (BD->param_empty()) {
3852 S += "(" + StructRef + " *__cself)";
3853 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003854 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003855 assert(FT && "SynthesizeBlockFunc: No function proto");
3856 S += '(';
3857 // first add the implicit argument.
3858 S += StructRef + " *__cself, ";
3859 std::string ParamStr;
3860 for (BlockDecl::param_iterator AI = BD->param_begin(),
3861 E = BD->param_end(); AI != E; ++AI) {
3862 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003863 ParamStr = (*AI)->getNameAsString();
Douglas Gregor7de59662009-05-29 20:38:28 +00003864 (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003865 S += ParamStr;
3866 }
3867 if (FT->isVariadic()) {
3868 if (!BD->param_empty()) S += ", ";
3869 S += "...";
3870 }
3871 S += ')';
3872 }
3873 S += " {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003874
Steve Naroff677ab3a2008-10-27 17:20:55 +00003875 // Create local declarations to avoid rewriting all closure decl ref exprs.
3876 // First, emit a declaration for all "by ref" decls.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00003877 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003878 E = BlockByRefDecls.end(); I != E; ++I) {
3879 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003880 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003881 std::string TypeString;
3882 RewriteByRefString(TypeString, Name, (*I));
3883 TypeString += " *";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003884 Name = TypeString + Name;
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003885 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump11289f42009-09-09 15:08:12 +00003886 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003887 // Next, emit a declaration for all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00003888 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003889 E = BlockByCopyDecls.end(); I != E; ++I) {
3890 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003891 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003892 // Handle nested closure invocation. For example:
3893 //
3894 // void (^myImportedClosure)(void);
3895 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003896 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003897 // void (^anotherClosure)(void);
3898 // anotherClosure = ^(void) {
3899 // myImportedClosure(); // import and invoke the closure
3900 // };
3901 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003902 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003903 S += "struct __block_impl *";
3904 else
Douglas Gregor7de59662009-05-29 20:38:28 +00003905 (*I)->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003906 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003907 }
3908 std::string RewrittenStr = RewrittenBlockExprs[CE];
3909 const char *cstr = RewrittenStr.c_str();
3910 while (*cstr++ != '{') ;
3911 S += cstr;
3912 S += "\n";
3913 return S;
3914}
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00003915
Steve Naroff677ab3a2008-10-27 17:20:55 +00003916std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3917 const char *funcName,
3918 std::string Tag) {
3919 std::string StructRef = "struct " + Tag;
3920 std::string S = "static void __";
Mike Stump11289f42009-09-09 15:08:12 +00003921
Steve Naroff677ab3a2008-10-27 17:20:55 +00003922 S += funcName;
3923 S += "_block_copy_" + utostr(i);
3924 S += "(" + StructRef;
3925 S += "*dst, " + StructRef;
3926 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003927 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003928 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003929 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003930 S += (*I)->getNameAsString();
Steve Naroff5ac4eac2008-12-11 20:51:38 +00003931 S += ", (void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003932 S += (*I)->getNameAsString();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00003933 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003934 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003935 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003936 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003937 }
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003938 S += "}\n";
3939
Steve Naroff677ab3a2008-10-27 17:20:55 +00003940 S += "\nstatic void __";
3941 S += funcName;
3942 S += "_block_dispose_" + utostr(i);
3943 S += "(" + StructRef;
3944 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003945 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003946 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003947 S += "_Block_object_dispose((void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003948 S += (*I)->getNameAsString();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00003949 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003950 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003951 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003952 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003953 }
Mike Stump11289f42009-09-09 15:08:12 +00003954 S += "}\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003955 return S;
3956}
3957
Steve Naroff30484702009-12-06 21:14:13 +00003958std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3959 std::string Desc) {
Steve Naroff295570a2008-10-30 12:09:33 +00003960 std::string S = "\nstruct " + Tag;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003961 std::string Constructor = " " + Tag;
Mike Stump11289f42009-09-09 15:08:12 +00003962
Steve Naroff677ab3a2008-10-27 17:20:55 +00003963 S += " {\n struct __block_impl impl;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003964 S += " struct " + Desc;
3965 S += "* Desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003966
Steve Naroff30484702009-12-06 21:14:13 +00003967 Constructor += "(void *fp, "; // Invoke function pointer.
3968 Constructor += "struct " + Desc; // Descriptor pointer.
3969 Constructor += " *desc";
Mike Stump11289f42009-09-09 15:08:12 +00003970
Steve Naroff677ab3a2008-10-27 17:20:55 +00003971 if (BlockDeclRefs.size()) {
3972 // Output all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00003973 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003974 E = BlockByCopyDecls.end(); I != E; ++I) {
3975 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003976 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003977 std::string ArgName = "_" + FieldName;
3978 // Handle nested closure invocation. For example:
3979 //
3980 // void (^myImportedBlock)(void);
3981 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003982 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003983 // void (^anotherBlock)(void);
3984 // anotherBlock = ^(void) {
3985 // myImportedBlock(); // import and invoke the closure
3986 // };
3987 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003988 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003989 S += "struct __block_impl *";
3990 Constructor += ", void *" + ArgName;
3991 } else {
Douglas Gregor7de59662009-05-29 20:38:28 +00003992 (*I)->getType().getAsStringInternal(FieldName, Context->PrintingPolicy);
3993 (*I)->getType().getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003994 Constructor += ", " + ArgName;
3995 }
3996 S += FieldName + ";\n";
3997 }
3998 // Output all "by ref" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00003999 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004000 E = BlockByRefDecls.end(); I != E; ++I) {
4001 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004002 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004003 std::string ArgName = "_" + FieldName;
4004 // Handle nested closure invocation. For example:
4005 //
4006 // void (^myImportedBlock)(void);
4007 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00004008 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00004009 // void (^anotherBlock)(void);
4010 // anotherBlock = ^(void) {
4011 // myImportedBlock(); // import and invoke the closure
4012 // };
4013 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00004014 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004015 S += "struct __block_impl *";
4016 Constructor += ", void *" + ArgName;
4017 } else {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004018 std::string TypeString;
4019 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004020 TypeString += " *";
4021 FieldName = TypeString + FieldName;
4022 ArgName = TypeString + ArgName;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004023 Constructor += ", " + ArgName;
4024 }
4025 S += FieldName + "; // by ref\n";
4026 }
4027 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004028 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00004029 if (GlobalVarDecl)
4030 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4031 else
4032 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004033 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00004034
Steve Naroff30484702009-12-06 21:14:13 +00004035 Constructor += " Desc = desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00004036
Steve Naroff677ab3a2008-10-27 17:20:55 +00004037 // Initialize all "by copy" arguments.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004038 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004039 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004040 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004041 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00004042 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004043 Constructor += Name + " = (struct __block_impl *)_";
4044 else
4045 Constructor += Name + " = _";
4046 Constructor += Name + ";\n";
4047 }
4048 // Initialize all "by ref" arguments.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004049 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004050 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004051 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004052 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00004053 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004054 Constructor += Name + " = (struct __block_impl *)_";
4055 else
4056 Constructor += Name + " = _";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004057 Constructor += Name + "->__forwarding;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004058 }
4059 } else {
4060 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004061 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00004062 if (GlobalVarDecl)
4063 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4064 else
4065 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004066 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4067 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004068 }
4069 Constructor += " ";
4070 Constructor += "}\n";
4071 S += Constructor;
4072 S += "};\n";
4073 return S;
4074}
4075
Steve Naroff30484702009-12-06 21:14:13 +00004076std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4077 std::string ImplTag, int i,
4078 const char *FunName,
4079 unsigned hasCopy) {
4080 std::string S = "\nstatic struct " + DescTag;
4081
4082 S += " {\n unsigned long reserved;\n";
4083 S += " unsigned long Block_size;\n";
4084 if (hasCopy) {
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004085 S += " void (*copy)(struct ";
4086 S += ImplTag; S += "*, struct ";
4087 S += ImplTag; S += "*);\n";
4088
4089 S += " void (*dispose)(struct ";
4090 S += ImplTag; S += "*);\n";
Steve Naroff30484702009-12-06 21:14:13 +00004091 }
4092 S += "} ";
4093
4094 S += DescTag + "_DATA = { 0, sizeof(struct ";
4095 S += ImplTag + ")";
4096 if (hasCopy) {
4097 S += ", __" + std::string(FunName) + "_block_copy_" + utostr(i);
4098 S += ", __" + std::string(FunName) + "_block_dispose_" + utostr(i);
4099 }
4100 S += "};\n";
4101 return S;
4102}
4103
Steve Naroff677ab3a2008-10-27 17:20:55 +00004104void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004105 const char *FunName) {
4106 // Insert declaration for the function in which block literal is used.
Fariborz Jahanian5c26eee2010-01-15 18:14:52 +00004107 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004108 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004109 // Insert closures that were part of the function.
4110 for (unsigned i = 0; i < Blocks.size(); i++) {
4111
4112 CollectBlockDeclRefInfo(Blocks[i]);
4113
Steve Naroff30484702009-12-06 21:14:13 +00004114 std::string ImplTag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
4115 std::string DescTag = "__" + std::string(FunName) + "_block_desc_" + utostr(i);
Mike Stump11289f42009-09-09 15:08:12 +00004116
Steve Naroff30484702009-12-06 21:14:13 +00004117 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004118
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004119 InsertText(FunLocStart, CI);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004120
Steve Naroff30484702009-12-06 21:14:13 +00004121 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump11289f42009-09-09 15:08:12 +00004122
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004123 InsertText(FunLocStart, CF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004124
4125 if (ImportedBlockDecls.size()) {
Steve Naroff30484702009-12-06 21:14:13 +00004126 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004127 InsertText(FunLocStart, HF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004128 }
Steve Naroff30484702009-12-06 21:14:13 +00004129 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4130 ImportedBlockDecls.size() > 0);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004131 InsertText(FunLocStart, BD);
Mike Stump11289f42009-09-09 15:08:12 +00004132
Steve Naroff677ab3a2008-10-27 17:20:55 +00004133 BlockDeclRefs.clear();
4134 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004135 BlockByRefDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004136 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004137 BlockByCopyDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004138 BlockCallExprs.clear();
4139 ImportedBlockDecls.clear();
4140 }
4141 Blocks.clear();
4142 RewrittenBlockExprs.clear();
4143}
4144
4145void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4146 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner86d7d912008-11-24 03:54:41 +00004147 const char *FuncName = FD->getNameAsCString();
Mike Stump11289f42009-09-09 15:08:12 +00004148
Steve Naroff677ab3a2008-10-27 17:20:55 +00004149 SynthesizeBlockLiterals(FunLocStart, FuncName);
4150}
4151
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004152static void BuildUniqueMethodName(std::string &Name,
4153 ObjCMethodDecl *MD) {
4154 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4155 Name = IFace->getNameAsCString();
4156 Name += "__" + MD->getSelector().getAsString();
4157 // Convert colons to underscores.
4158 std::string::size_type loc = 0;
4159 while ((loc = Name.find(":", loc)) != std::string::npos)
4160 Name.replace(loc, 1, "_");
4161}
4162
Steve Naroff677ab3a2008-10-27 17:20:55 +00004163void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff295570a2008-10-30 12:09:33 +00004164 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4165 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianb5f99c32010-01-29 01:55:49 +00004166 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004167 std::string FuncName;
4168 BuildUniqueMethodName(FuncName, MD);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004169 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
4170}
4171
4172void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4173 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4174 CI != E; ++CI)
4175 if (*CI) {
4176 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4177 GetBlockDeclRefExprs(CBE->getBody());
4178 else
4179 GetBlockDeclRefExprs(*CI);
4180 }
4181 // Handle specific things.
4182 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
4183 // FIXME: Handle enums.
4184 if (!isa<FunctionDecl>(CDRE->getDecl()))
4185 BlockDeclRefs.push_back(CDRE);
4186 return;
4187}
4188
4189void RewriteObjC::GetBlockCallExprs(Stmt *S) {
4190 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4191 CI != E; ++CI)
4192 if (*CI) {
4193 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4194 GetBlockCallExprs(CBE->getBody());
4195 else
4196 GetBlockCallExprs(*CI);
4197 }
Mike Stump11289f42009-09-09 15:08:12 +00004198
Steve Naroff677ab3a2008-10-27 17:20:55 +00004199 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4200 if (CE->getCallee()->getType()->isBlockPointerType()) {
4201 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
4202 }
4203 }
4204 return;
4205}
4206
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004207Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004208 // Navigate to relevant type information.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004209 const BlockPointerType *CPT = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004210
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004211 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004212 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004213 } else if (const BlockDeclRefExpr *CDRE =
4214 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004215 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004216 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004217 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004218 }
4219 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4220 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4221 }
4222 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4223 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4224 else if (const ConditionalOperator *CEXPR =
4225 dyn_cast<ConditionalOperator>(BlockExp)) {
4226 Expr *LHSExp = CEXPR->getLHS();
4227 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4228 Expr *RHSExp = CEXPR->getRHS();
4229 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4230 Expr *CONDExp = CEXPR->getCond();
4231 ConditionalOperator *CondExpr =
4232 new (Context) ConditionalOperator(CONDExp,
4233 SourceLocation(), cast<Expr>(LHSStmt),
4234 SourceLocation(), cast<Expr>(RHSStmt),
4235 Exp->getType());
4236 return CondExpr;
Fariborz Jahanian6ab7ed42009-12-18 01:15:21 +00004237 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4238 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004239 } else {
4240 assert(1 && "RewriteBlockClass: Bad type");
4241 }
4242 assert(CPT && "RewriteBlockClass: Bad type");
John McCall9dd450b2009-09-21 23:43:11 +00004243 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004244 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004245 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004246 // FTP will be null for closures that don't take arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004247
Steve Naroff350b6652008-10-30 10:07:53 +00004248 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
4249 SourceLocation(),
4250 &Context->Idents.get("__block_impl"));
4251 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff677ab3a2008-10-27 17:20:55 +00004252
Steve Naroff350b6652008-10-30 10:07:53 +00004253 // Generate a funky cast.
4254 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00004255
Steve Naroff350b6652008-10-30 10:07:53 +00004256 // Push the block argument type.
4257 ArgTypes.push_back(PtrBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004258 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004259 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff350b6652008-10-30 10:07:53 +00004260 E = FTP->arg_type_end(); I && (I != E); ++I) {
4261 QualType t = *I;
4262 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00004263 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004264 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff350b6652008-10-30 10:07:53 +00004265 t = Context->getPointerType(BPT->getPointeeType());
4266 }
4267 ArgTypes.push_back(t);
4268 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004269 }
Steve Naroff350b6652008-10-30 10:07:53 +00004270 // Now do the pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00004271 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Steve Naroff350b6652008-10-30 10:07:53 +00004272 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004273
Steve Naroff350b6652008-10-30 10:07:53 +00004274 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump11289f42009-09-09 15:08:12 +00004275
John McCall97513962010-01-15 18:39:57 +00004276 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4277 CastExpr::CK_Unknown,
4278 const_cast<Expr*>(BlockExp));
Steve Naroff350b6652008-10-30 10:07:53 +00004279 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00004280 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4281 BlkCast);
Steve Naroff350b6652008-10-30 10:07:53 +00004282 //PE->dump();
Mike Stump11289f42009-09-09 15:08:12 +00004283
Douglas Gregor91f84212008-12-11 16:49:14 +00004284 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00004285 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004286 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek5a201952009-02-07 01:47:29 +00004287 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4288 FD->getType());
Mike Stump11289f42009-09-09 15:08:12 +00004289
John McCall97513962010-01-15 18:39:57 +00004290 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4291 CastExpr::CK_Unknown, ME);
Ted Kremenek5a201952009-02-07 01:47:29 +00004292 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump11289f42009-09-09 15:08:12 +00004293
Steve Naroff350b6652008-10-30 10:07:53 +00004294 llvm::SmallVector<Expr*, 8> BlkExprs;
4295 // Add the implicit argument.
4296 BlkExprs.push_back(BlkCast);
4297 // Add the user arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004298 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004299 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00004300 BlkExprs.push_back(*I);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004301 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004302 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4303 BlkExprs.size(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004304 Exp->getType(), SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004305 return CE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004306}
4307
4308void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004309 Stmt *BlockCall = SynthesizeBlockCall(Exp, Exp->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00004310 ReplaceStmt(Exp, BlockCall);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004311}
4312
Steve Naroffd9803712009-04-29 16:37:50 +00004313// We need to return the rewritten expression to handle cases where the
4314// BlockDeclRefExpr is embedded in another expression being rewritten.
4315// For example:
4316//
4317// int main() {
4318// __block Foo *f;
4319// __block int i;
Mike Stump11289f42009-09-09 15:08:12 +00004320//
Steve Naroffd9803712009-04-29 16:37:50 +00004321// void (^myblock)() = ^() {
4322// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4323// i = 77;
4324// };
4325//}
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004326Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanian25c07fa2009-12-23 19:26:34 +00004327 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004328 // for each DeclRefExp where BYREFVAR is name of the variable.
4329 ValueDecl *VD;
4330 bool isArrow = true;
4331 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4332 VD = BDRE->getDecl();
4333 else {
4334 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4335 isArrow = false;
4336 }
4337
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004338 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4339 &Context->Idents.get("__forwarding"),
4340 Context->VoidPtrTy, 0,
4341 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004342 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4343 FD, SourceLocation(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004344 FD->getType());
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004345
4346 const char *Name = VD->getNameAsCString();
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004347 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4348 &Context->Idents.get(Name),
4349 Context->VoidPtrTy, 0,
4350 /*BitWidth=*/0, /*Mutable=*/true);
4351 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004352 DeclRefExp->getType());
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004353
4354
4355
Steve Narofff26a1d42009-02-02 17:19:26 +00004356 // Need parens to enforce precedence.
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004357 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4358 ME);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004359 ReplaceStmt(DeclRefExp, PE);
Steve Naroffd9803712009-04-29 16:37:50 +00004360 return PE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004361}
4362
Steve Naroffc989a7b2008-11-03 23:29:32 +00004363void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4364 SourceLocation LocStart = CE->getLParenLoc();
4365 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofff4b992a2008-10-28 20:29:00 +00004366
4367 // Need to avoid trying to rewrite synthesized casts.
4368 if (LocStart.isInvalid())
4369 return;
Steve Naroff3e7ced12008-11-03 11:20:24 +00004370 // Need to avoid trying to rewrite casts contained in macros.
4371 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4372 return;
Mike Stump11289f42009-09-09 15:08:12 +00004373
Steve Naroff677ab3a2008-10-27 17:20:55 +00004374 const char *startBuf = SM->getCharacterData(LocStart);
4375 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004376 QualType QT = CE->getType();
4377 const Type* TypePtr = QT->getAs<Type>();
4378 if (isa<TypeOfExprType>(TypePtr)) {
4379 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4380 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4381 std::string TypeAsString = "(";
4382 TypeAsString += QT.getAsString();
4383 TypeAsString += ")";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004384 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004385 return;
4386 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004387 // advance the location to startArgList.
4388 const char *argPtr = startBuf;
Mike Stump11289f42009-09-09 15:08:12 +00004389
Steve Naroff677ab3a2008-10-27 17:20:55 +00004390 while (*argPtr++ && (argPtr < endBuf)) {
4391 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004392 case '^':
4393 // Replace the '^' with '*'.
4394 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004395 ReplaceText(LocStart, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00004396 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004397 }
4398 }
4399 return;
4400}
4401
4402void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4403 SourceLocation DeclLoc = FD->getLocation();
4404 unsigned parenCount = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004405
Steve Naroff677ab3a2008-10-27 17:20:55 +00004406 // We have 1 or more arguments that have closure pointers.
4407 const char *startBuf = SM->getCharacterData(DeclLoc);
4408 const char *startArgList = strchr(startBuf, '(');
Mike Stump11289f42009-09-09 15:08:12 +00004409
Steve Naroff677ab3a2008-10-27 17:20:55 +00004410 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004411
Steve Naroff677ab3a2008-10-27 17:20:55 +00004412 parenCount++;
4413 // advance the location to startArgList.
4414 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4415 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump11289f42009-09-09 15:08:12 +00004416
Steve Naroff677ab3a2008-10-27 17:20:55 +00004417 const char *argPtr = startArgList;
Mike Stump11289f42009-09-09 15:08:12 +00004418
Steve Naroff677ab3a2008-10-27 17:20:55 +00004419 while (*argPtr++ && parenCount) {
4420 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004421 case '^':
4422 // Replace the '^' with '*'.
4423 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004424 ReplaceText(DeclLoc, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00004425 break;
4426 case '(':
4427 parenCount++;
4428 break;
4429 case ')':
4430 parenCount--;
4431 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004432 }
4433 }
4434 return;
4435}
4436
4437bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004438 const FunctionProtoType *FTP;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004439 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004440 if (PT) {
John McCall9dd450b2009-09-21 23:43:11 +00004441 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004442 } else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004443 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004444 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall9dd450b2009-09-21 23:43:11 +00004445 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004446 }
4447 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004448 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004449 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +00004450 if (isTopLevelBlockPointerType(*I))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004451 return true;
4452 }
4453 return false;
4454}
4455
Ted Kremenek5a201952009-02-07 01:47:29 +00004456void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4457 const char *&RParen) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004458 const char *argPtr = strchr(Name, '(');
4459 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004460
Steve Naroff677ab3a2008-10-27 17:20:55 +00004461 LParen = argPtr; // output the start.
4462 argPtr++; // skip past the left paren.
4463 unsigned parenCount = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004464
Steve Naroff677ab3a2008-10-27 17:20:55 +00004465 while (*argPtr && parenCount) {
4466 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004467 case '(': parenCount++; break;
4468 case ')': parenCount--; break;
4469 default: break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004470 }
4471 if (parenCount) argPtr++;
4472 }
4473 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4474 RParen = argPtr; // output the end
4475}
4476
4477void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4478 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4479 RewriteBlockPointerFunctionArgs(FD);
4480 return;
Mike Stump11289f42009-09-09 15:08:12 +00004481 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004482 // Handle Variables and Typedefs.
4483 SourceLocation DeclLoc = ND->getLocation();
4484 QualType DeclT;
4485 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4486 DeclT = VD->getType();
4487 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4488 DeclT = TDD->getUnderlyingType();
4489 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4490 DeclT = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004491 else
Steve Naroff677ab3a2008-10-27 17:20:55 +00004492 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump11289f42009-09-09 15:08:12 +00004493
Steve Naroff677ab3a2008-10-27 17:20:55 +00004494 const char *startBuf = SM->getCharacterData(DeclLoc);
4495 const char *endBuf = startBuf;
4496 // scan backward (from the decl location) for the end of the previous decl.
4497 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4498 startBuf--;
Mike Stump11289f42009-09-09 15:08:12 +00004499
Steve Naroff677ab3a2008-10-27 17:20:55 +00004500 // *startBuf != '^' if we are dealing with a pointer to function that
4501 // may take block argument types (which will be handled below).
4502 if (*startBuf == '^') {
4503 // Replace the '^' with '*', computing a negative offset.
4504 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004505 ReplaceText(DeclLoc, 1, "*");
Steve Naroff677ab3a2008-10-27 17:20:55 +00004506 }
4507 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4508 // Replace the '^' with '*' for arguments.
4509 DeclLoc = ND->getLocation();
4510 startBuf = SM->getCharacterData(DeclLoc);
4511 const char *argListBegin, *argListEnd;
4512 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4513 while (argListBegin < argListEnd) {
4514 if (*argListBegin == '^') {
4515 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004516 ReplaceText(CaretLoc, 1, "*");
Steve Naroff677ab3a2008-10-27 17:20:55 +00004517 }
4518 argListBegin++;
4519 }
4520 }
4521 return;
4522}
4523
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004524
4525/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4526/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4527/// struct Block_byref_id_object *src) {
4528/// _Block_object_assign (&_dest->object, _src->object,
4529/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4530/// [|BLOCK_FIELD_IS_WEAK]) // object
4531/// _Block_object_assign(&_dest->object, _src->object,
4532/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4533/// [|BLOCK_FIELD_IS_WEAK]) // block
4534/// }
4535/// And:
4536/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4537/// _Block_object_dispose(_src->object,
4538/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4539/// [|BLOCK_FIELD_IS_WEAK]) // object
4540/// _Block_object_dispose(_src->object,
4541/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4542/// [|BLOCK_FIELD_IS_WEAK]) // block
4543/// }
4544
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004545std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4546 int flag) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004547 std::string S;
Benjamin Kramere056cea2010-01-10 19:57:50 +00004548 if (CopyDestroyCache.count(flag))
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004549 return S;
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004550 CopyDestroyCache.insert(flag);
4551 S = "static void __Block_byref_id_object_copy_";
4552 S += utostr(flag);
4553 S += "(void *dst, void *src) {\n";
4554
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004555 // offset into the object pointer is computed as:
4556 // void * + void* + int + int + void* + void *
4557 unsigned IntSize =
4558 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4559 unsigned VoidPtrSize =
4560 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4561
4562 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
4563 S += " _Block_object_assign((char*)dst + ";
4564 S += utostr(offset);
4565 S += ", *(void * *) ((char*)src + ";
4566 S += utostr(offset);
4567 S += "), ";
4568 S += utostr(flag);
4569 S += ");\n}\n";
4570
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004571 S += "static void __Block_byref_id_object_dispose_";
4572 S += utostr(flag);
4573 S += "(void *src) {\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004574 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4575 S += utostr(offset);
4576 S += "), ";
4577 S += utostr(flag);
4578 S += ");\n}\n";
4579 return S;
4580}
4581
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004582/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4583/// the declaration into:
4584/// struct __Block_byref_ND {
4585/// void *__isa; // NULL for everything except __weak pointers
4586/// struct __Block_byref_ND *__forwarding;
4587/// int32_t __flags;
4588/// int32_t __size;
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004589/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4590/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004591/// typex ND;
4592/// };
4593///
4594/// It then replaces declaration of ND variable with:
4595/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4596/// __size=sizeof(struct __Block_byref_ND),
4597/// ND=initializer-if-any};
4598///
4599///
4600void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004601 // Insert declaration for the function in which block literal is
4602 // used.
4603 if (CurFunctionDeclToDeclareForBlock)
4604 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004605 int flag = 0;
4606 int isa = 0;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004607 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4608 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian92368a12009-12-30 20:38:08 +00004609 SourceLocation X = ND->getLocEnd();
4610 X = SM->getInstantiationLoc(X);
4611 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004612 std::string Name(ND->getNameAsString());
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004613 std::string ByrefType;
4614 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004615 ByrefType += " {\n";
4616 ByrefType += " void *__isa;\n";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004617 RewriteByRefString(ByrefType, Name, ND);
4618 ByrefType += " *__forwarding;\n";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004619 ByrefType += " int __flags;\n";
4620 ByrefType += " int __size;\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004621 // Add void *__Block_byref_id_object_copy;
4622 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004623 QualType Ty = ND->getType();
4624 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4625 if (HasCopyAndDispose) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004626 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4627 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004628 }
4629
4630 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004631 ByrefType += " " + Name + ";\n";
4632 ByrefType += "};\n";
4633 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004634 SourceLocation FunLocStart;
4635 if (CurFunctionDef)
4636 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4637 else {
4638 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4639 FunLocStart = CurMethodDef->getLocStart();
4640 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004641 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004642 if (Ty.isObjCGCWeak()) {
4643 flag |= BLOCK_FIELD_IS_WEAK;
4644 isa = 1;
4645 }
4646
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004647 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004648 flag = BLOCK_BYREF_CALLER;
4649 QualType Ty = ND->getType();
4650 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4651 if (Ty->isBlockPointerType())
4652 flag |= BLOCK_FIELD_IS_BLOCK;
4653 else
4654 flag |= BLOCK_FIELD_IS_OBJECT;
4655 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004656 if (!HF.empty())
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004657 InsertText(FunLocStart, HF);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004658 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004659
4660 // struct __Block_byref_ND ND =
4661 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4662 // initializer-if-any};
4663 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanianf7945432010-01-05 18:15:57 +00004664 unsigned flags = 0;
4665 if (HasCopyAndDispose)
4666 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004667 Name = ND->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004668 ByrefType.clear();
4669 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004670 std::string ForwardingCastType("(");
4671 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004672 if (!hasInit) {
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004673 ByrefType += " " + Name + " = {(void*)";
4674 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004675 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004676 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004677 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004678 ByrefType += "sizeof(";
4679 RewriteByRefString(ByrefType, Name, ND);
4680 ByrefType += ")";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004681 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004682 ByrefType += ", __Block_byref_id_object_copy_";
4683 ByrefType += utostr(flag);
4684 ByrefType += ", __Block_byref_id_object_dispose_";
4685 ByrefType += utostr(flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004686 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004687 ByrefType += "};\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004688 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(), ByrefType);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004689 }
4690 else {
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004691 SourceLocation startLoc;
4692 Expr *E = ND->getInit();
4693 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4694 startLoc = ECE->getLParenLoc();
4695 else
4696 startLoc = E->getLocStart();
Fariborz Jahanianb8646ed2010-01-05 23:06:29 +00004697 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004698 endBuf = SM->getCharacterData(startLoc);
4699
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004700 ByrefType += " " + Name;
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004701 ByrefType += " = {(void*)";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004702 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004703 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004704 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004705 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004706 ByrefType += "sizeof(";
4707 RewriteByRefString(ByrefType, Name, ND);
4708 ByrefType += "), ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004709 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004710 ByrefType += "__Block_byref_id_object_copy_";
4711 ByrefType += utostr(flag);
4712 ByrefType += ", __Block_byref_id_object_dispose_";
4713 ByrefType += utostr(flag);
4714 ByrefType += ", ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004715 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004716 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroff13468372009-12-23 17:24:33 +00004717
4718 // Complete the newly synthesized compound expression by inserting a right
4719 // curly brace before the end of the declaration.
4720 // FIXME: This approach avoids rewriting the initializer expression. It
4721 // also assumes there is only one declarator. For example, the following
4722 // isn't currently supported by this routine (in general):
4723 //
4724 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4725 //
4726 const char *startBuf = SM->getCharacterData(startLoc);
4727 const char *semiBuf = strchr(startBuf, ';');
4728 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4729 SourceLocation semiLoc =
4730 startLoc.getFileLocWithOffset(semiBuf-startBuf);
4731
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004732 InsertText(semiLoc, "}");
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004733 }
Fariborz Jahanian81203462009-12-22 00:48:54 +00004734 return;
4735}
4736
Mike Stump11289f42009-09-09 15:08:12 +00004737void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004738 // Add initializers for any closure decl refs.
4739 GetBlockDeclRefExprs(Exp->getBody());
4740 if (BlockDeclRefs.size()) {
4741 // Unique all "by copy" declarations.
4742 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004743 if (!BlockDeclRefs[i]->isByRef()) {
4744 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4745 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4746 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4747 }
4748 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004749 // Unique all "by ref" declarations.
4750 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4751 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004752 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4753 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4754 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4755 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004756 }
4757 // Find any imported blocks...they will need special attention.
4758 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004759 if (BlockDeclRefs[i]->isByRef() ||
4760 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4761 BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroff832d8902008-11-13 17:40:07 +00004762 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004763 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4764 }
4765 }
4766}
4767
Steve Narofff4b992a2008-10-28 20:29:00 +00004768FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4769 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004770 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump11289f42009-09-09 15:08:12 +00004771 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004772 ID, FType, 0, FunctionDecl::Extern, false,
Douglas Gregor739ef0c2009-02-25 16:33:18 +00004773 false);
Steve Narofff4b992a2008-10-28 20:29:00 +00004774}
4775
Steve Naroffd8907b72008-10-29 18:15:37 +00004776Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004777 Blocks.push_back(Exp);
4778
4779 CollectBlockDeclRefInfo(Exp);
4780 std::string FuncName;
Mike Stump11289f42009-09-09 15:08:12 +00004781
Steve Narofff4b992a2008-10-28 20:29:00 +00004782 if (CurFunctionDef)
Chris Lattnere4b95692008-11-24 03:33:13 +00004783 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004784 else if (CurMethodDef)
4785 BuildUniqueMethodName(FuncName, CurMethodDef);
4786 else if (GlobalVarDecl)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004787 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump11289f42009-09-09 15:08:12 +00004788
Steve Narofff4b992a2008-10-28 20:29:00 +00004789 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump11289f42009-09-09 15:08:12 +00004790
Steve Narofff4b992a2008-10-28 20:29:00 +00004791 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4792 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump11289f42009-09-09 15:08:12 +00004793
Steve Narofff4b992a2008-10-28 20:29:00 +00004794 // Get a pointer to the function type so we can cast appropriately.
4795 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4796
4797 FunctionDecl *FD;
4798 Expr *NewRep;
Mike Stump11289f42009-09-09 15:08:12 +00004799
Steve Narofff4b992a2008-10-28 20:29:00 +00004800 // Simulate a contructor call...
4801 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004802 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004803
Steve Narofff4b992a2008-10-28 20:29:00 +00004804 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00004805
Steve Naroffe2514232008-10-29 21:23:59 +00004806 // Initialize the block function.
Steve Narofff4b992a2008-10-28 20:29:00 +00004807 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004808 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4809 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00004810 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4811 CastExpr::CK_Unknown, Arg);
Mike Stump11289f42009-09-09 15:08:12 +00004812 InitExprs.push_back(castExpr);
4813
Steve Naroff30484702009-12-06 21:14:13 +00004814 // Initialize the block descriptor.
4815 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump11289f42009-09-09 15:08:12 +00004816
Steve Naroff30484702009-12-06 21:14:13 +00004817 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
4818 &Context->Idents.get(DescData.c_str()),
4819 Context->VoidPtrTy, 0,
4820 VarDecl::Static);
4821 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
4822 new (Context) DeclRefExpr(NewVD,
4823 Context->VoidPtrTy, SourceLocation()),
4824 UnaryOperator::AddrOf,
4825 Context->getPointerType(Context->VoidPtrTy),
4826 SourceLocation());
4827 InitExprs.push_back(DescRefExpr);
4828
Steve Narofff4b992a2008-10-28 20:29:00 +00004829 // Add initializers for any closure decl refs.
4830 if (BlockDeclRefs.size()) {
Steve Naroffe2514232008-10-29 21:23:59 +00004831 Expr *Exp;
Steve Narofff4b992a2008-10-28 20:29:00 +00004832 // Output all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004833 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004834 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004835 if (isObjCType((*I)->getType())) {
Steve Naroffe2514232008-10-29 21:23:59 +00004836 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner86d7d912008-11-24 03:54:41 +00004837 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004838 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroffa5c0db82008-12-11 21:05:33 +00004839 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004840 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004841 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
John McCall97513962010-01-15 18:39:57 +00004842 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4843 CastExpr::CK_Unknown, Arg);
Steve Narofff4b992a2008-10-28 20:29:00 +00004844 } else {
Chris Lattner86d7d912008-11-24 03:54:41 +00004845 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004846 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004847 }
Mike Stump11289f42009-09-09 15:08:12 +00004848 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004849 }
4850 // Output all "by ref" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004851 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004852 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004853 ValueDecl *ND = (*I);
4854 std::string Name(ND->getNameAsString());
4855 std::string RecName;
4856 RewriteByRefString(RecName, Name, ND);
4857 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4858 + sizeof("struct"));
4859 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
4860 SourceLocation(), II);
4861 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4862 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4863
Chris Lattner86d7d912008-11-24 03:54:41 +00004864 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004865 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4866 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004867 Context->getPointerType(Exp->getType()),
Steve Naroffe2514232008-10-29 21:23:59 +00004868 SourceLocation());
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004869 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CastExpr::CK_Unknown, Exp);
Mike Stump11289f42009-09-09 15:08:12 +00004870 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004871 }
4872 }
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00004873 if (ImportedBlockDecls.size()) {
4874 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4875 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff30484702009-12-06 21:14:13 +00004876 unsigned IntSize =
4877 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00004878 Expr *FlagExp = new (Context) IntegerLiteral(llvm::APInt(IntSize, flag),
4879 Context->IntTy, SourceLocation());
4880 InitExprs.push_back(FlagExp);
Steve Naroff30484702009-12-06 21:14:13 +00004881 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004882 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4883 FType, SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00004884 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004885 Context->getPointerType(NewRep->getType()),
Steve Narofff4b992a2008-10-28 20:29:00 +00004886 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00004887 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CastExpr::CK_Unknown,
4888 NewRep);
Steve Narofff4b992a2008-10-28 20:29:00 +00004889 BlockDeclRefs.clear();
4890 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004891 BlockByRefDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00004892 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004893 BlockByCopyDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00004894 ImportedBlockDecls.clear();
4895 return NewRep;
4896}
4897
4898//===----------------------------------------------------------------------===//
4899// Function Body / Expression rewriting
4900//===----------------------------------------------------------------------===//
4901
Steve Naroff4588d0f2008-12-04 16:24:46 +00004902// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4903// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4904// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4905// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4906// Since the rewriter isn't capable of rewriting rewritten code, it's important
4907// we get this right.
4908void RewriteObjC::CollectPropertySetters(Stmt *S) {
4909 // Perform a bottom up traversal of all children.
4910 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4911 CI != E; ++CI)
4912 if (*CI)
4913 CollectPropertySetters(*CI);
4914
4915 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4916 if (BinOp->isAssignmentOp()) {
4917 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4918 PropSetters[PRE] = BinOp;
4919 }
4920 }
4921}
4922
Steve Narofff4b992a2008-10-28 20:29:00 +00004923Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump11289f42009-09-09 15:08:12 +00004924 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004925 isa<DoStmt>(S) || isa<ForStmt>(S))
4926 Stmts.push_back(S);
4927 else if (isa<ObjCForCollectionStmt>(S)) {
4928 Stmts.push_back(S);
Chris Lattnerb71980f2010-01-09 21:45:57 +00004929 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofff4b992a2008-10-28 20:29:00 +00004930 }
Mike Stump11289f42009-09-09 15:08:12 +00004931
Steve Narofff4b992a2008-10-28 20:29:00 +00004932 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004933
Steve Narofff4b992a2008-10-28 20:29:00 +00004934 // Perform a bottom up rewrite of all children.
4935 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4936 CI != E; ++CI)
4937 if (*CI) {
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00004938 Stmt *newStmt;
4939 Stmt *S = (*CI);
4940 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4941 Expr *OldBase = IvarRefExpr->getBase();
4942 bool replaced = false;
4943 newStmt = RewriteObjCNestedIvarRefExpr(S, replaced);
4944 if (replaced) {
4945 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
4946 ReplaceStmt(OldBase, IRE->getBase());
4947 else
4948 ReplaceStmt(S, newStmt);
4949 }
4950 }
4951 else
4952 newStmt = RewriteFunctionBodyOrGlobalInitializer(S);
Mike Stump11289f42009-09-09 15:08:12 +00004953 if (newStmt)
Steve Narofff4b992a2008-10-28 20:29:00 +00004954 *CI = newStmt;
4955 }
Mike Stump11289f42009-09-09 15:08:12 +00004956
Steve Narofff4b992a2008-10-28 20:29:00 +00004957 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4958 // Rewrite the block body in place.
4959 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Mike Stump11289f42009-09-09 15:08:12 +00004960
Steve Narofff4b992a2008-10-28 20:29:00 +00004961 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenekdb2ef372010-01-07 18:00:35 +00004962 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroffd8907b72008-10-29 18:15:37 +00004963 RewrittenBlockExprs[BE] = Str;
Mike Stump11289f42009-09-09 15:08:12 +00004964
Steve Narofff4b992a2008-10-28 20:29:00 +00004965 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4966 //blockTranscribed->dump();
Steve Naroffd8907b72008-10-29 18:15:37 +00004967 ReplaceStmt(S, blockTranscribed);
Steve Narofff4b992a2008-10-28 20:29:00 +00004968 return blockTranscribed;
4969 }
4970 // Handle specific things.
4971 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4972 return RewriteAtEncode(AtEncode);
Mike Stump11289f42009-09-09 15:08:12 +00004973
Steve Naroff4588d0f2008-12-04 16:24:46 +00004974 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4975 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4976 if (BinOp) {
4977 // Because the rewriter doesn't allow us to rewrite rewritten code,
4978 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroff08628db2008-12-09 12:56:34 +00004979 DisableReplaceStmt = true;
4980 // Save the source range. Even if we disable the replacement, the
4981 // rewritten node will have been inserted into the tree. If the synthesized
4982 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump11289f42009-09-09 15:08:12 +00004983 // self.errorHandler = handler ? handler :
Steve Naroff08628db2008-12-09 12:56:34 +00004984 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4985 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroff4588d0f2008-12-04 16:24:46 +00004986 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroff08628db2008-12-09 12:56:34 +00004987 DisableReplaceStmt = false;
Steve Naroff22216db2008-12-04 23:50:32 +00004988 //
4989 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4990 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4991 // to see the original expression). Consider this example:
4992 //
4993 // Foo *obj1, *obj2;
4994 //
4995 // obj1.i = [obj2 rrrr];
4996 //
4997 // 'BinOp' for the previous expression looks like:
4998 //
4999 // (BinaryOperator 0x231ccf0 'int' '='
5000 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
5001 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
5002 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
5003 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
5004 //
5005 // 'newStmt' represents the rewritten message expression. For example:
5006 //
5007 // (CallExpr 0x231d300 'id':'struct objc_object *'
5008 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
5009 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
5010 // (CStyleCastExpr 0x231d220 'void *'
5011 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
5012 //
5013 // Note that 'newStmt' is passed to RewritePropertySetter so that it
5014 // can be used as the setter argument. ReplaceStmt() will still 'see'
5015 // the original RHS (since we haven't altered BinOp).
5016 //
Mike Stump11289f42009-09-09 15:08:12 +00005017 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff22216db2008-12-04 23:50:32 +00005018 // node. As a result, we now leak the original AST nodes.
5019 //
Steve Naroff08628db2008-12-09 12:56:34 +00005020 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroff4588d0f2008-12-04 16:24:46 +00005021 } else {
5022 return RewritePropertyGetter(PropRefExpr);
Steve Narofff326f402008-12-03 00:56:33 +00005023 }
5024 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005025 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5026 return RewriteAtSelector(AtSelector);
Mike Stump11289f42009-09-09 15:08:12 +00005027
Steve Narofff4b992a2008-10-28 20:29:00 +00005028 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5029 return RewriteObjCStringLiteral(AtString);
Mike Stump11289f42009-09-09 15:08:12 +00005030
Steve Narofff4b992a2008-10-28 20:29:00 +00005031 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00005032#if 0
Steve Narofff4b992a2008-10-28 20:29:00 +00005033 // Before we rewrite it, put the original message expression in a comment.
5034 SourceLocation startLoc = MessExpr->getLocStart();
5035 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00005036
Steve Narofff4b992a2008-10-28 20:29:00 +00005037 const char *startBuf = SM->getCharacterData(startLoc);
5038 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump11289f42009-09-09 15:08:12 +00005039
Steve Narofff4b992a2008-10-28 20:29:00 +00005040 std::string messString;
5041 messString += "// ";
5042 messString.append(startBuf, endBuf-startBuf+1);
5043 messString += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00005044
5045 // FIXME: Missing definition of
Steve Narofff4b992a2008-10-28 20:29:00 +00005046 // InsertText(clang::SourceLocation, char const*, unsigned int).
5047 // InsertText(startLoc, messString.c_str(), messString.size());
5048 // Tried this, but it didn't work either...
5049 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff4588d0f2008-12-04 16:24:46 +00005050#endif
Steve Narofff4b992a2008-10-28 20:29:00 +00005051 return RewriteMessageExpr(MessExpr);
5052 }
Mike Stump11289f42009-09-09 15:08:12 +00005053
Steve Narofff4b992a2008-10-28 20:29:00 +00005054 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5055 return RewriteObjCTryStmt(StmtTry);
5056
5057 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5058 return RewriteObjCSynchronizedStmt(StmtTry);
5059
5060 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5061 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump11289f42009-09-09 15:08:12 +00005062
Steve Narofff4b992a2008-10-28 20:29:00 +00005063 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5064 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump11289f42009-09-09 15:08:12 +00005065
5066 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofff4b992a2008-10-28 20:29:00 +00005067 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump11289f42009-09-09 15:08:12 +00005068 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofff4b992a2008-10-28 20:29:00 +00005069 OrigStmtRange.getEnd());
5070 if (BreakStmt *StmtBreakStmt =
5071 dyn_cast<BreakStmt>(S))
5072 return RewriteBreakStmt(StmtBreakStmt);
5073 if (ContinueStmt *StmtContinueStmt =
5074 dyn_cast<ContinueStmt>(S))
5075 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump11289f42009-09-09 15:08:12 +00005076
5077 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofff4b992a2008-10-28 20:29:00 +00005078 // and cast exprs.
5079 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5080 // FIXME: What we're doing here is modifying the type-specifier that
5081 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump11289f42009-09-09 15:08:12 +00005082 // a separate type-specifier that we can rewrite.
Steve Naroffe70a52a2009-12-05 15:55:59 +00005083 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5084 // the context of an ObjCForCollectionStmt. For example:
5085 // NSArray *someArray;
5086 // for (id <FooProtocol> index in someArray) ;
5087 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5088 // and it depends on the original text locations/positions.
Benjamin Krameracc5fa12009-12-05 22:16:51 +00005089 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroffe70a52a2009-12-05 15:55:59 +00005090 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump11289f42009-09-09 15:08:12 +00005091
Steve Narofff4b992a2008-10-28 20:29:00 +00005092 // Blocks rewrite rules.
5093 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5094 DI != DE; ++DI) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +00005095 Decl *SD = *DI;
Steve Narofff4b992a2008-10-28 20:29:00 +00005096 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005097 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005098 RewriteBlockPointerDecl(ND);
Mike Stump11289f42009-09-09 15:08:12 +00005099 else if (ND->getType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005100 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00005101 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005102 if (VD->hasAttr<BlocksAttr>()) {
5103 static unsigned uniqueByrefDeclCount = 0;
5104 assert(!BlockByRefDeclNo.count(ND) &&
5105 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5106 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005107 RewriteByRefVar(VD);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005108 }
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00005109 else
5110 RewriteTypeOfDecl(VD);
5111 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005112 }
5113 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005114 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005115 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005116 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005117 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5118 }
5119 }
5120 }
Mike Stump11289f42009-09-09 15:08:12 +00005121
Steve Narofff4b992a2008-10-28 20:29:00 +00005122 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5123 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump11289f42009-09-09 15:08:12 +00005124
5125 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00005126 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5127 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump11289f42009-09-09 15:08:12 +00005128 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5129 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005130 && "Statement stack mismatch");
5131 Stmts.pop_back();
5132 }
5133 // Handle blocks rewriting.
5134 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5135 if (BDRE->isByRef())
Steve Naroffd9803712009-04-29 16:37:50 +00005136 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofff4b992a2008-10-28 20:29:00 +00005137 }
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005138 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5139 ValueDecl *VD = DRE->getDecl();
5140 if (VD->hasAttr<BlocksAttr>())
5141 return RewriteBlockDeclRefExpr(DRE);
5142 }
5143
Steve Narofff4b992a2008-10-28 20:29:00 +00005144 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff350b6652008-10-30 10:07:53 +00005145 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00005146 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00005147 ReplaceStmt(S, BlockCall);
5148 return BlockCall;
5149 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005150 }
Steve Naroffc989a7b2008-11-03 23:29:32 +00005151 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005152 RewriteCastExpr(CE);
5153 }
5154#if 0
5155 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek5a201952009-02-07 01:47:29 +00005156 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00005157 // Get the new text.
5158 std::string SStr;
5159 llvm::raw_string_ostream Buf(SStr);
Eli Friedman0905f142009-05-30 05:19:26 +00005160 Replacement->printPretty(Buf, *Context);
Steve Narofff4b992a2008-10-28 20:29:00 +00005161 const std::string &Str = Buf.str();
5162
5163 printf("CAST = %s\n", &Str[0]);
5164 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5165 delete S;
5166 return Replacement;
5167 }
5168#endif
5169 // Return this stmt unmodified.
5170 return S;
5171}
5172
Steve Naroffe70a52a2009-12-05 15:55:59 +00005173void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5174 for (RecordDecl::field_iterator i = RD->field_begin(),
5175 e = RD->field_end(); i != e; ++i) {
5176 FieldDecl *FD = *i;
5177 if (isTopLevelBlockPointerType(FD->getType()))
5178 RewriteBlockPointerDecl(FD);
5179 if (FD->getType()->isObjCQualifiedIdType() ||
5180 FD->getType()->isObjCQualifiedInterfaceType())
5181 RewriteObjCQualifiedInterfaceTypes(FD);
5182 }
5183}
5184
Steve Narofff4b992a2008-10-28 20:29:00 +00005185/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5186/// main file of the input.
5187void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5188 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffb1368882008-12-17 00:20:22 +00005189 if (FD->isOverloadedOperator())
5190 return;
Mike Stump11289f42009-09-09 15:08:12 +00005191
Steve Narofff4b992a2008-10-28 20:29:00 +00005192 // Since function prototypes don't have ParmDecl's, we check the function
5193 // prototype. This enables us to rewrite function declarations and
5194 // definitions using the same code.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005195 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005196
Sebastian Redla7b98a72009-04-26 20:35:05 +00005197 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005198 if (CompoundStmt *Body = FD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005199 CurFunctionDef = FD;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005200 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005201 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005202 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005203 Body =
5204 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5205 FD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005206 CurrentBody = 0;
5207 if (PropParentMap) {
5208 delete PropParentMap;
5209 PropParentMap = 0;
5210 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005211 // This synthesizes and inserts the block "impl" struct, invoke function,
5212 // and any copy/dispose helper functions.
5213 InsertBlockLiteralsWithinFunction(FD);
5214 CurFunctionDef = 0;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005215 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005216 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005217 return;
5218 }
5219 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005220 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005221 CurMethodDef = MD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005222 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005223 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005224 Body =
5225 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5226 MD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005227 CurrentBody = 0;
5228 if (PropParentMap) {
5229 delete PropParentMap;
5230 PropParentMap = 0;
5231 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005232 InsertBlockLiteralsWithinMethod(MD);
5233 CurMethodDef = 0;
5234 }
5235 }
5236 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5237 ClassImplementation.push_back(CI);
5238 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5239 CategoryImplementation.push_back(CI);
5240 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5241 RewriteForwardClassDecl(CD);
5242 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5243 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroffa5c0db82008-12-11 21:05:33 +00005244 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005245 RewriteBlockPointerDecl(VD);
Steve Naroffd8907b72008-10-29 18:15:37 +00005246 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005247 CheckFunctionPointerDecl(VD->getType(), VD);
5248 if (VD->getInit()) {
Steve Naroffc989a7b2008-11-03 23:29:32 +00005249 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005250 RewriteCastExpr(CE);
5251 }
5252 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00005253 } else if (VD->getType()->isRecordType()) {
5254 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5255 if (RD->isDefinition())
5256 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005257 }
Steve Naroffd8907b72008-10-29 18:15:37 +00005258 if (VD->getInit()) {
5259 GlobalVarDecl = VD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005260 CollectPropertySetters(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005261 CurrentBody = VD->getInit();
Steve Naroffd8907b72008-10-29 18:15:37 +00005262 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005263 CurrentBody = 0;
5264 if (PropParentMap) {
5265 delete PropParentMap;
5266 PropParentMap = 0;
5267 }
Mike Stump11289f42009-09-09 15:08:12 +00005268 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner86d7d912008-11-24 03:54:41 +00005269 VD->getNameAsCString());
Steve Naroffd8907b72008-10-29 18:15:37 +00005270 GlobalVarDecl = 0;
5271
5272 // This is needed for blocks.
Steve Naroffc989a7b2008-11-03 23:29:32 +00005273 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroffd8907b72008-10-29 18:15:37 +00005274 RewriteCastExpr(CE);
5275 }
5276 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005277 return;
5278 }
5279 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005280 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005281 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005282 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005283 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Steve Naroffe70a52a2009-12-05 15:55:59 +00005284 else if (TD->getUnderlyingType()->isRecordType()) {
5285 RecordDecl *RD = TD->getUnderlyingType()->getAs<RecordType>()->getDecl();
5286 if (RD->isDefinition())
5287 RewriteRecordBody(RD);
5288 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005289 return;
5290 }
5291 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroffe70a52a2009-12-05 15:55:59 +00005292 if (RD->isDefinition())
5293 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005294 return;
5295 }
5296 // Nothing yet.
5297}
5298
Chris Lattnercf169832009-03-28 04:11:33 +00005299void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005300 if (Diags.hasErrorOccurred())
5301 return;
Mike Stump11289f42009-09-09 15:08:12 +00005302
Steve Narofff4b992a2008-10-28 20:29:00 +00005303 RewriteInclude();
Mike Stump11289f42009-09-09 15:08:12 +00005304
Steve Naroffd9803712009-04-29 16:37:50 +00005305 // Here's a great place to add any extra declarations that may be needed.
5306 // Write out meta data for each @protocol(<expr>).
Mike Stump11289f42009-09-09 15:08:12 +00005307 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00005308 E = ProtocolExprDecls.end(); I != E; ++I)
5309 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5310
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005311 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005312 if (ClassImplementation.size() || CategoryImplementation.size())
5313 RewriteImplementations();
Steve Naroffd9803712009-04-29 16:37:50 +00005314
Steve Narofff4b992a2008-10-28 20:29:00 +00005315 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5316 // we are done.
Mike Stump11289f42009-09-09 15:08:12 +00005317 if (const RewriteBuffer *RewriteBuf =
Steve Narofff4b992a2008-10-28 20:29:00 +00005318 Rewrite.getRewriteBufferFor(MainFileID)) {
5319 //printf("Changed:\n");
5320 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5321 } else {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005322 llvm::errs() << "No changes\n";
Steve Narofff4b992a2008-10-28 20:29:00 +00005323 }
Steve Narofff8cfd162008-11-13 20:07:04 +00005324
Steve Naroffd9803712009-04-29 16:37:50 +00005325 if (ClassImplementation.size() || CategoryImplementation.size() ||
5326 ProtocolExprDecls.size()) {
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005327 // Rewrite Objective-c meta data*
5328 std::string ResultStr;
5329 SynthesizeMetaDataIntoBuffer(ResultStr);
5330 // Emit metadata.
5331 *OutFile << ResultStr;
5332 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005333 OutFile->flush();
5334}
5335