blob: 521abf489b9067cf8e970bae83d4ebdb39f43a7a [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,
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +0000304 Expr **args, unsigned nargs,
305 SourceLocation StartLoc=SourceLocation(),
306 SourceLocation EndLoc=SourceLocation());
307 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
308 SourceLocation StartLoc=SourceLocation(),
309 SourceLocation EndLoc=SourceLocation());
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +0000310 Stmt *RewriteBreakStmt(BreakStmt *S);
311 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian965a8962008-01-08 22:06:28 +0000312 void SynthCountByEnumWithState(std::string &buf);
Mike Stump11289f42009-09-09 15:08:12 +0000313
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000314 void SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +0000315 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000316 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +0000317 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000318 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000319 void SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +0000320 void SynthGetMetaClassFunctionDecl();
Fariborz Jahanian31e18502007-12-04 21:47:40 +0000321 void SynthSelGetUidFunctionDecl();
Steve Naroff17978c42008-03-11 17:37:02 +0000322 void SynthSuperContructorFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000323
Chris Lattner3c799d72007-10-24 17:06:59 +0000324 // Metadata emission.
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000325 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000326 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000327
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000328 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000329 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000330
Douglas Gregor29bd76f2009-04-23 01:02:12 +0000331 template<typename MethodIterator>
332 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
333 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +0000334 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +0000335 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +0000336 const char *ClassName,
337 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000338
Steve Naroffd9803712009-04-29 16:37:50 +0000339 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
340 const char *prefix,
341 const char *ClassName,
342 std::string &Result);
343 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Mike Stump11289f42009-09-09 15:08:12 +0000344 const char *prefix,
Steve Naroffd9803712009-04-29 16:37:50 +0000345 const char *ClassName,
346 std::string &Result);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000347 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000348 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000349 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
350 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000351 std::string &Result);
Steve Narofff8cfd162008-11-13 20:07:04 +0000352 void RewriteImplementations();
353 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000354
Steve Naroff677ab3a2008-10-27 17:20:55 +0000355 // Block rewriting.
Mike Stump11289f42009-09-09 15:08:12 +0000356 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000357 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump11289f42009-09-09 15:08:12 +0000358
Steve Naroff677ab3a2008-10-27 17:20:55 +0000359 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
360 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump11289f42009-09-09 15:08:12 +0000361
362 // Block specific rewrite rules.
Steve Naroff677ab3a2008-10-27 17:20:55 +0000363 void RewriteBlockCall(CallExpr *Exp);
364 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000365 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahaniane3891582010-01-05 18:04:40 +0000366 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +0000367 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000368 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump11289f42009-09-09 15:08:12 +0000369
370 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Steve Naroff677ab3a2008-10-27 17:20:55 +0000371 const char *funcName, std::string Tag);
Mike Stump11289f42009-09-09 15:08:12 +0000372 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Steve Naroff677ab3a2008-10-27 17:20:55 +0000373 const char *funcName, std::string Tag);
Steve Naroff30484702009-12-06 21:14:13 +0000374 std::string SynthesizeBlockImpl(BlockExpr *CE,
375 std::string Tag, std::string Desc);
376 std::string SynthesizeBlockDescriptor(std::string DescTag,
377 std::string ImplTag,
378 int i, const char *funcName,
379 unsigned hasCopy);
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +0000380 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000381 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000382 const char *FunName);
Steve Naroffe70a52a2009-12-05 15:55:59 +0000383 void RewriteRecordBody(RecordDecl *RD);
Mike Stump11289f42009-09-09 15:08:12 +0000384
Steve Naroff677ab3a2008-10-27 17:20:55 +0000385 void CollectBlockDeclRefInfo(BlockExpr *Exp);
386 void GetBlockCallExprs(Stmt *S);
387 void GetBlockDeclRefExprs(Stmt *S);
Mike Stump11289f42009-09-09 15:08:12 +0000388
Steve Naroff677ab3a2008-10-27 17:20:55 +0000389 // We avoid calling Type::isBlockPointerType(), since it operates on the
390 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek5a201952009-02-07 01:47:29 +0000391 bool isTopLevelBlockPointerType(QualType T) {
392 return isa<BlockPointerType>(T);
393 }
Mike Stump11289f42009-09-09 15:08:12 +0000394
Steve Naroff677ab3a2008-10-27 17:20:55 +0000395 // FIXME: This predicate seems like it would be useful to add to ASTContext.
396 bool isObjCType(QualType T) {
397 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
398 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000399
Steve Naroff677ab3a2008-10-27 17:20:55 +0000400 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000401
Steve Naroff677ab3a2008-10-27 17:20:55 +0000402 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
403 OCT == Context->getCanonicalType(Context->getObjCClassType()))
404 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000405
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000406 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +0000407 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Narofffb4330f2009-06-17 22:40:22 +0000408 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff677ab3a2008-10-27 17:20:55 +0000409 return true;
410 }
411 return false;
412 }
413 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek5a201952009-02-07 01:47:29 +0000414 void GetExtentOfArgList(const char *Name, const char *&LParen,
415 const char *&RParen);
Steve Naroffc989a7b2008-11-03 23:29:32 +0000416 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump11289f42009-09-09 15:08:12 +0000417
Steve Narofff4b992a2008-10-28 20:29:00 +0000418 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroffd8907b72008-10-29 18:15:37 +0000419 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Mike Stump11289f42009-09-09 15:08:12 +0000420
Steve Naroffd9803712009-04-29 16:37:50 +0000421 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump11289f42009-09-09 15:08:12 +0000422 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroffd9803712009-04-29 16:37:50 +0000423 if (From[i] == '"')
424 To += "\\\"";
425 else
426 To += From[i];
427 }
428 }
Chris Lattnere99c8322007-10-11 00:43:27 +0000429 };
John McCall97513962010-01-15 18:39:57 +0000430
431 // Helper function: create a CStyleCastExpr with trivial type source info.
432 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
433 CastExpr::CastKind Kind, Expr *E) {
434 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
435 return new (Ctx) CStyleCastExpr(Ty, Kind, E, TInfo,
436 SourceLocation(), SourceLocation());
437 }
Chris Lattnere99c8322007-10-11 00:43:27 +0000438}
439
Mike Stump11289f42009-09-09 15:08:12 +0000440void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
441 NamedDecl *D) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000442 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000443 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +0000444 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +0000445 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +0000446 // All the args are checked/rewritten. Don't call twice!
447 RewriteBlockPointerDecl(D);
448 break;
449 }
450 }
451}
452
453void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000454 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +0000455 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000456 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000457}
458
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000459static bool IsHeaderFile(const std::string &Filename) {
460 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump11289f42009-09-09 15:08:12 +0000461
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000462 if (DotPos == std::string::npos) {
463 // no file extension
Mike Stump11289f42009-09-09 15:08:12 +0000464 return false;
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000465 }
Mike Stump11289f42009-09-09 15:08:12 +0000466
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000467 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
468 // C header: .h
469 // C++ header: .hh or .H;
470 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump11289f42009-09-09 15:08:12 +0000471}
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000472
Eli Friedman94cf21e2009-05-18 22:20:00 +0000473RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000474 Diagnostic &D, const LangOptions &LOpts,
475 bool silenceMacroWarn)
476 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
477 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Narofff9e7c902008-03-28 22:26:09 +0000478 IsHeader = IsHeaderFile(inFile);
Mike Stump11289f42009-09-09 15:08:12 +0000479 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Narofff9e7c902008-03-28 22:26:09 +0000480 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump11289f42009-09-09 15:08:12 +0000481 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek5a201952009-02-07 01:47:29 +0000482 "rewriter doesn't support user-specified control flow semantics "
483 "for @try/@finally (code may not execute properly)");
Steve Narofff9e7c902008-03-28 22:26:09 +0000484}
485
Eli Friedmana63ab2d2009-05-18 22:29:17 +0000486ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
487 llvm::raw_ostream* OS,
Mike Stump11289f42009-09-09 15:08:12 +0000488 Diagnostic &Diags,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000489 const LangOptions &LOpts,
490 bool SilenceRewriteMacroWarning) {
491 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere9c810c2007-11-30 22:25:36 +0000492}
Chris Lattnere99c8322007-10-11 00:43:27 +0000493
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000494void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner187f6262008-01-31 19:38:44 +0000495 Context = &context;
496 SM = &Context->getSourceManager();
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +0000497 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner187f6262008-01-31 19:38:44 +0000498 MsgSendFunctionDecl = 0;
499 MsgSendSuperFunctionDecl = 0;
500 MsgSendStretFunctionDecl = 0;
501 MsgSendSuperStretFunctionDecl = 0;
502 MsgSendFpretFunctionDecl = 0;
503 GetClassFunctionDecl = 0;
504 GetMetaClassFunctionDecl = 0;
505 SelGetUidFunctionDecl = 0;
506 CFStringFunctionDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000507 ConstantStringClassReference = 0;
508 NSStringRecord = 0;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000509 CurMethodDef = 0;
510 CurFunctionDef = 0;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000511 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000512 GlobalVarDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000513 SuperStructDecl = 0;
Steve Naroffd9803712009-04-29 16:37:50 +0000514 ProtocolTypeDecl = 0;
Steve Naroff60a9ef62008-03-27 22:59:54 +0000515 ConstantStringDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000516 BcLabelCount = 0;
Steve Naroff17978c42008-03-11 17:37:02 +0000517 SuperContructorFunctionDecl = 0;
Steve Naroffce8e8862008-03-15 00:55:56 +0000518 NumObjCStringLiterals = 0;
Steve Narofff1ab6002008-12-08 20:01:41 +0000519 PropParentMap = 0;
520 CurrentBody = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000521 DisableReplaceStmt = false;
Fariborz Jahanianbc6811c2010-01-07 22:51:18 +0000522 objc_impl_method = false;
Mike Stump11289f42009-09-09 15:08:12 +0000523
Chris Lattner187f6262008-01-31 19:38:44 +0000524 // Get the ID and start/end of the main file.
525 MainFileID = SM->getMainFileID();
526 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
527 MainFileStart = MainBuf->getBufferStart();
528 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000529
Chris Lattner184e65d2009-04-14 23:22:57 +0000530 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump11289f42009-09-09 15:08:12 +0000531
Chris Lattner187f6262008-01-31 19:38:44 +0000532 // declaring objc_selector outside the parameter list removes a silly
533 // scope related warning...
Steve Naroff00a31762008-03-27 22:29:16 +0000534 if (IsHeader)
Steve Narofffcc6fd52009-02-03 20:39:18 +0000535 Preamble = "#pragma once\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000536 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff6ab6dc72008-12-23 20:11:22 +0000537 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroff00a31762008-03-27 22:29:16 +0000538 Preamble += "struct objc_object *superClass; ";
Steve Naroff17978c42008-03-11 17:37:02 +0000539 if (LangOpts.Microsoft) {
540 // Add a constructor for creating temporary objects.
Ted Kremenek5a201952009-02-07 01:47:29 +0000541 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
542 ": ";
Steve Naroff00a31762008-03-27 22:29:16 +0000543 Preamble += "object(o), superClass(s) {} ";
Steve Naroff17978c42008-03-11 17:37:02 +0000544 }
Steve Naroff00a31762008-03-27 22:29:16 +0000545 Preamble += "};\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000546 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
547 Preamble += "typedef struct objc_object Protocol;\n";
548 Preamble += "#define _REWRITER_typedef_Protocol\n";
549 Preamble += "#endif\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000550 if (LangOpts.Microsoft) {
551 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
552 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
553 } else
554 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
555 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
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";
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 struct objc_object *objc_msgSend_stret";
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_msgSendSuper_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000562 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000563 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroff00a31762008-03-27 22:29:16 +0000564 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000565 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000566 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000567 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000568 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000569 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
570 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
571 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
572 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
573 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroffd30f8c52008-05-09 21:17:56 +0000574 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff8dd15252008-07-16 18:58:11 +0000575 // @synchronized hooks.
Steve Narofff122ff02008-12-08 17:30:33 +0000576 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
577 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
578 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000579 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
580 Preamble += "struct __objcFastEnumerationState {\n\t";
581 Preamble += "unsigned long state;\n\t";
Steve Naroff4dbab8a2008-04-04 22:58:22 +0000582 Preamble += "void **itemsPtr;\n\t";
Steve Naroff00a31762008-03-27 22:29:16 +0000583 Preamble += "unsigned long *mutationsPtr;\n\t";
584 Preamble += "unsigned long extra[5];\n};\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000585 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000586 Preamble += "#define __FASTENUMERATIONSTATE\n";
587 Preamble += "#endif\n";
588 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
589 Preamble += "struct __NSConstantStringImpl {\n";
590 Preamble += " int *isa;\n";
591 Preamble += " int flags;\n";
592 Preamble += " char *str;\n";
593 Preamble += " long length;\n";
594 Preamble += "};\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000595 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
596 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
597 Preamble += "#else\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000598 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000599 Preamble += "#endif\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000600 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
601 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000602 // Blocks preamble.
603 Preamble += "#ifndef BLOCK_IMPL\n";
604 Preamble += "#define BLOCK_IMPL\n";
605 Preamble += "struct __block_impl {\n";
606 Preamble += " void *isa;\n";
607 Preamble += " int Flags;\n";
Steve Naroff30484702009-12-06 21:14:13 +0000608 Preamble += " int Reserved;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000609 Preamble += " void *FuncPtr;\n";
610 Preamble += "};\n";
Steve Naroff61d879e2008-12-16 15:50:30 +0000611 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroff287a2bf2009-12-06 01:52:22 +0000612 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000613 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_assign(void *, const void *, const int);\n";
614 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
615 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
616 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
617 Preamble += "#else\n";
Steve Naroff7bf01ea2010-01-05 18:09:31 +0000618 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
619 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000620 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
621 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
622 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000623 Preamble += "#endif\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000624 if (LangOpts.Microsoft) {
Steve Narofff122ff02008-12-08 17:30:33 +0000625 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
626 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000627 Preamble += "#define __attribute__(X)\n";
Fariborz Jahanianf0462ff2010-01-15 22:29:39 +0000628 Preamble += "#define __weak\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000629 }
Fariborz Jahanian7fac6552010-01-05 19:21:35 +0000630 else {
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000631 Preamble += "#define __block\n";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +0000632 Preamble += "#define __weak\n";
633 }
Chris Lattner187f6262008-01-31 19:38:44 +0000634}
635
636
Chris Lattner3c799d72007-10-24 17:06:59 +0000637//===----------------------------------------------------------------------===//
638// Top Level Driver Code
639//===----------------------------------------------------------------------===//
640
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000641void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremenek31e7f0f2010-02-05 21:28:51 +0000642 if (Diags.hasErrorOccurred())
643 return;
644
Chris Lattner0bd1c972007-10-16 21:07:07 +0000645 // Two cases: either the decl could be in the main file, or it could be in a
646 // #included file. If the former, rewrite it now. If the later, check to see
647 // if we rewrote the #include/#import.
648 SourceLocation Loc = D->getLocation();
Chris Lattner8a425862009-01-16 07:36:28 +0000649 Loc = SM->getInstantiationLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000650
Chris Lattner0bd1c972007-10-16 21:07:07 +0000651 // If this is for a builtin, ignore it.
652 if (Loc.isInvalid()) return;
653
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000654 // Look for built-in declarations that we need to refer during the rewrite.
655 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000656 RewriteFunctionDecl(FD);
Steve Naroff08899ff2008-04-15 22:42:06 +0000657 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000658 // declared in <Foundation/NSString.h>
Chris Lattner86d7d912008-11-24 03:54:41 +0000659 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000660 ConstantStringClassReference = FVD;
661 return;
662 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000663 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff161a92b2007-10-26 20:53:56 +0000664 RewriteInterfaceDecl(MD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000665 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000666 RewriteCategoryDecl(CD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000667 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff921385f2007-10-30 16:42:30 +0000668 RewriteProtocolDecl(PD);
Mike Stump11289f42009-09-09 15:08:12 +0000669 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000670 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000671 RewriteForwardProtocolDecl(FP);
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000672 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
673 // Recurse into linkage specifications
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000674 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
675 DIEnd = LSD->decls_end();
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000676 DI != DIEnd; ++DI)
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000677 HandleTopLevelSingleDecl(*DI);
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000678 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000679 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekd61ed3b2008-04-14 21:24:13 +0000680 if (SM->isFromMainFile(Loc))
Chris Lattner0bd1c972007-10-16 21:07:07 +0000681 return HandleDeclInMainFile(D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000682}
683
Chris Lattner3c799d72007-10-24 17:06:59 +0000684//===----------------------------------------------------------------------===//
685// Syntactic (non-AST) Rewriting Code
686//===----------------------------------------------------------------------===//
687
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000688void RewriteObjC::RewriteInclude() {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000689 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000690 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
691 const char *MainBufStart = MainBuf.first;
692 const char *MainBufEnd = MainBuf.second;
693 size_t ImportLen = strlen("import");
Mike Stump11289f42009-09-09 15:08:12 +0000694
Fariborz Jahanian137d6932008-01-19 01:03:17 +0000695 // Loop over the whole file, looking for includes.
Fariborz Jahanian80258362008-01-19 00:30:35 +0000696 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
697 if (*BufPtr == '#') {
698 if (++BufPtr == MainBufEnd)
699 return;
700 while (*BufPtr == ' ' || *BufPtr == '\t')
701 if (++BufPtr == MainBufEnd)
702 return;
703 if (!strncmp(BufPtr, "import", ImportLen)) {
704 // replace import with include
Mike Stump11289f42009-09-09 15:08:12 +0000705 SourceLocation ImportLoc =
Fariborz Jahanian80258362008-01-19 00:30:35 +0000706 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000707 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian80258362008-01-19 00:30:35 +0000708 BufPtr += ImportLen;
709 }
710 }
711 }
Chris Lattner0bd1c972007-10-16 21:07:07 +0000712}
713
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000714void RewriteObjC::RewriteTabs() {
Chris Lattner3c799d72007-10-24 17:06:59 +0000715 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
716 const char *MainBufStart = MainBuf.first;
717 const char *MainBufEnd = MainBuf.second;
Mike Stump11289f42009-09-09 15:08:12 +0000718
Chris Lattner3c799d72007-10-24 17:06:59 +0000719 // Loop over the whole file, looking for tabs.
720 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
721 if (*BufPtr != '\t')
722 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000723
Chris Lattner3c799d72007-10-24 17:06:59 +0000724 // Okay, we found a tab. This tab will turn into at least one character,
725 // but it depends on which 'virtual column' it is in. Compute that now.
726 unsigned VCol = 0;
727 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
728 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
729 ++VCol;
Mike Stump11289f42009-09-09 15:08:12 +0000730
Chris Lattner3c799d72007-10-24 17:06:59 +0000731 // Okay, now that we know the virtual column, we know how many spaces to
732 // insert. We assume 8-character tab-stops.
733 unsigned Spaces = 8-(VCol & 7);
Mike Stump11289f42009-09-09 15:08:12 +0000734
Chris Lattner3c799d72007-10-24 17:06:59 +0000735 // Get the location of the tab.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000736 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
737 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Mike Stump11289f42009-09-09 15:08:12 +0000738
Chris Lattner3c799d72007-10-24 17:06:59 +0000739 // Rewrite the single tab character into a sequence of spaces.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000740 ReplaceText(TabLoc, 1, llvm::StringRef(" ", Spaces));
Chris Lattner3c799d72007-10-24 17:06:59 +0000741 }
Chris Lattner16a0de42007-10-11 18:38:32 +0000742}
743
Steve Naroff9af94912008-12-02 15:48:25 +0000744static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
745 ObjCIvarDecl *OID) {
746 std::string S;
747 S = "((struct ";
748 S += ClassDecl->getIdentifier()->getName();
749 S += "_IMPL *)self)->";
Daniel Dunbar70e7ead2009-10-18 20:26:27 +0000750 S += OID->getName();
Steve Naroff9af94912008-12-02 15:48:25 +0000751 return S;
752}
753
Steve Naroffc038b3a2008-12-02 17:36:43 +0000754void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
755 ObjCImplementationDecl *IMD,
756 ObjCCategoryImplDecl *CID) {
Steve Naroffe1908e32008-12-01 20:33:01 +0000757 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000758 InsertText(startLoc, "// ");
Steve Naroff9af94912008-12-02 15:48:25 +0000759 const char *startBuf = SM->getCharacterData(startLoc);
760 assert((*startBuf == '@') && "bogus @synthesize location");
761 const char *semiBuf = strchr(startBuf, ';');
762 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek5a201952009-02-07 01:47:29 +0000763 SourceLocation onePastSemiLoc =
764 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroff9af94912008-12-02 15:48:25 +0000765
766 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
767 return; // FIXME: is this correct?
Mike Stump11289f42009-09-09 15:08:12 +0000768
Steve Naroff9af94912008-12-02 15:48:25 +0000769 // Generate the 'getter' function.
Steve Naroff9af94912008-12-02 15:48:25 +0000770 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroff9af94912008-12-02 15:48:25 +0000771 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroff9af94912008-12-02 15:48:25 +0000772 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000773
Steve Naroff003d00e2008-12-02 16:05:55 +0000774 if (!OID)
775 return;
Mike Stump11289f42009-09-09 15:08:12 +0000776
Steve Naroff003d00e2008-12-02 16:05:55 +0000777 std::string Getr;
778 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
779 Getr += "{ ";
780 // Synthesize an explicit cast to gain access to the ivar.
Mike Stump11289f42009-09-09 15:08:12 +0000781 // FIXME: deal with code generation implications for various property
782 // attributes (copy, retain, nonatomic).
Steve Naroff06297042008-12-02 17:54:50 +0000783 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroff003d00e2008-12-02 16:05:55 +0000784 Getr += "return " + getIvarAccessString(ClassDecl, OID);
785 Getr += "; }";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000786 InsertText(onePastSemiLoc, Getr);
Steve Naroff9af94912008-12-02 15:48:25 +0000787 if (PD->isReadOnly())
788 return;
Mike Stump11289f42009-09-09 15:08:12 +0000789
Steve Naroff9af94912008-12-02 15:48:25 +0000790 // Generate the 'setter' function.
791 std::string Setr;
792 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroff9af94912008-12-02 15:48:25 +0000793 Setr += "{ ";
Steve Naroff003d00e2008-12-02 16:05:55 +0000794 // Synthesize an explicit cast to initialize the ivar.
Mike Stump11289f42009-09-09 15:08:12 +0000795 // FIXME: deal with code generation implications for various property
796 // attributes (copy, retain, nonatomic).
Steve Narofff326f402008-12-03 00:56:33 +0000797 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroff003d00e2008-12-02 16:05:55 +0000798 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000799 Setr += PD->getNameAsCString();
Steve Naroff003d00e2008-12-02 16:05:55 +0000800 Setr += "; }";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000801 InsertText(onePastSemiLoc, Setr);
Steve Naroffe1908e32008-12-01 20:33:01 +0000802}
Chris Lattner16a0de42007-10-11 18:38:32 +0000803
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000804void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattner3c799d72007-10-24 17:06:59 +0000805 // Get the start location and compute the semi location.
806 SourceLocation startLoc = ClassDecl->getLocation();
807 const char *startBuf = SM->getCharacterData(startLoc);
808 const char *semiPtr = strchr(startBuf, ';');
Mike Stump11289f42009-09-09 15:08:12 +0000809
Chris Lattner3c799d72007-10-24 17:06:59 +0000810 // Translate to typedef's that forward reference structs with the same name
811 // as the class. As a convenience, we include the original declaration
812 // as a comment.
813 std::string typedefString;
Fariborz Jahanian1c2cb6d2010-01-11 22:48:40 +0000814 typedefString += "// @class ";
815 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
816 I != E; ++I) {
817 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
818 typedefString += ForwardDecl->getNameAsString();
819 if (I+1 != E)
820 typedefString += ", ";
821 else
822 typedefString += ";\n";
823 }
824
Chris Lattner9ee23b72009-02-20 18:04:31 +0000825 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
826 I != E; ++I) {
Ted Kremenek9b124e12009-11-18 00:28:11 +0000827 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff1b232132007-11-09 12:50:28 +0000828 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000829 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000830 typedefString += "\n";
831 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000832 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000833 typedefString += "\n";
Steve Naroff98eb8d12007-11-05 14:36:37 +0000834 typedefString += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000835 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000836 typedefString += ";\n#endif\n";
Steve Naroff574440f2007-10-24 22:48:43 +0000837 }
Mike Stump11289f42009-09-09 15:08:12 +0000838
Steve Naroff574440f2007-10-24 22:48:43 +0000839 // Replace the @class with typedefs corresponding to the classes.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000840 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
Chris Lattner3c799d72007-10-24 17:06:59 +0000841}
842
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000843void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000844 // When method is a synthesized one, such as a getter/setter there is
845 // nothing to rewrite.
846 if (Method->isSynthesized())
847 return;
Steve Naroff3ce37a62007-12-14 23:37:57 +0000848 SourceLocation LocStart = Method->getLocStart();
849 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000850
Chris Lattner88ea93e2009-02-04 01:06:56 +0000851 if (SM->getInstantiationLineNumber(LocEnd) >
852 SM->getInstantiationLineNumber(LocStart)) {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000853 InsertText(LocStart, "#if 0\n");
854 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff3ce37a62007-12-14 23:37:57 +0000855 } else {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000856 InsertText(LocStart, "// ");
Steve Naroff5448cf62007-10-30 13:30:57 +0000857 }
858}
859
Mike Stump11289f42009-09-09 15:08:12 +0000860void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000861 SourceLocation Loc = prop->getAtLoc();
Mike Stump11289f42009-09-09 15:08:12 +0000862
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000863 ReplaceText(Loc, 0, "// ");
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000864 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahaniane8a30162007-11-07 00:09:37 +0000865}
866
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000867void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000868 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000869
Steve Naroff5448cf62007-10-30 13:30:57 +0000870 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000871 ReplaceText(LocStart, 0, "// ");
Mike Stump11289f42009-09-09 15:08:12 +0000872
Fariborz Jahanian68ebe632010-02-10 01:15:09 +0000873 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
874 E = CatDecl->prop_end(); I != E; ++I)
875 RewriteProperty(*I);
876
Mike Stump11289f42009-09-09 15:08:12 +0000877 for (ObjCCategoryDecl::instmeth_iterator
878 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000879 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000880 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +0000881 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000882 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000883 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000884 RewriteMethodDeclaration(*I);
885
Steve Naroff5448cf62007-10-30 13:30:57 +0000886 // Lastly, comment out the @end.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000887 ReplaceText(CatDecl->getAtEndRange().getBegin(), 0, "// ");
Steve Naroff5448cf62007-10-30 13:30:57 +0000888}
889
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000890void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000891 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Mike Stump11289f42009-09-09 15:08:12 +0000892
Steve Narofff921385f2007-10-30 16:42:30 +0000893 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000894
Steve Narofff921385f2007-10-30 16:42:30 +0000895 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000896 ReplaceText(LocStart, 0, "// ");
Mike Stump11289f42009-09-09 15:08:12 +0000897
898 for (ObjCProtocolDecl::instmeth_iterator
899 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000900 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000901 RewriteMethodDeclaration(*I);
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000902 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000903 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000904 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000905 RewriteMethodDeclaration(*I);
906
Steve Narofff921385f2007-10-30 16:42:30 +0000907 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +0000908 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000909 ReplaceText(LocEnd, 0, "// ");
Steve Naroffa509f042007-11-14 15:03:57 +0000910
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000911 // Must comment out @optional/@required
912 const char *startBuf = SM->getCharacterData(LocStart);
913 const char *endBuf = SM->getCharacterData(LocEnd);
914 for (const char *p = startBuf; p < endBuf; p++) {
915 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Steve Naroffa509f042007-11-14 15:03:57 +0000916 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000917 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump11289f42009-09-09 15:08:12 +0000918
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000919 }
920 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Steve Naroffa509f042007-11-14 15:03:57 +0000921 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000922 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump11289f42009-09-09 15:08:12 +0000923
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000924 }
925 }
Steve Narofff921385f2007-10-30 16:42:30 +0000926}
927
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000928void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000929 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffc17b0562007-11-14 03:37:28 +0000930 if (LocStart.isInvalid())
931 assert(false && "Invalid SourceLocation");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000932 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000933 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000934}
935
Mike Stump11289f42009-09-09 15:08:12 +0000936void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000937 std::string &ResultStr) {
Steve Naroff295570a2008-10-30 12:09:33 +0000938 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroffb067bbd2008-07-16 14:40:40 +0000939 const FunctionType *FPRetType = 0;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000940 ResultStr += "\nstatic ";
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000941 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +0000942 ResultStr += "id";
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000943 else if (OMD->getResultType()->isFunctionPointerType() ||
944 OMD->getResultType()->isBlockPointerType()) {
Steve Naroffb067bbd2008-07-16 14:40:40 +0000945 // needs special handling, since pointer-to-functions have special
946 // syntax (where a decaration models use).
947 QualType retType = OMD->getResultType();
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000948 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000949 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000950 PointeeTy = PT->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000951 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000952 PointeeTy = BPT->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +0000953 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000954 ResultStr += FPRetType->getResultType().getAsString();
955 ResultStr += "(*";
Steve Naroffb067bbd2008-07-16 14:40:40 +0000956 }
957 } else
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +0000958 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian7262fca2008-01-10 01:39:52 +0000959 ResultStr += " ";
Mike Stump11289f42009-09-09 15:08:12 +0000960
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000961 // Unique method name
Fariborz Jahanian56338352007-11-13 21:02:00 +0000962 std::string NameStr;
Mike Stump11289f42009-09-09 15:08:12 +0000963
Douglas Gregorffca3a22009-01-09 17:18:27 +0000964 if (OMD->isInstanceMethod())
Fariborz Jahanian56338352007-11-13 21:02:00 +0000965 NameStr += "_I_";
966 else
967 NameStr += "_C_";
Mike Stump11289f42009-09-09 15:08:12 +0000968
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000969 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +0000970 NameStr += "_";
Mike Stump11289f42009-09-09 15:08:12 +0000971
972 if (ObjCCategoryImplDecl *CID =
Steve Naroff11b387f2009-01-08 19:41:02 +0000973 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000974 NameStr += CID->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +0000975 NameStr += "_";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000976 }
Mike Stump11289f42009-09-09 15:08:12 +0000977 // Append selector names, replacing ':' with '_'
Chris Lattnere4b95692008-11-24 03:33:13 +0000978 {
979 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000980 int len = selString.size();
981 for (int i = 0; i < len; i++)
982 if (selString[i] == ':')
983 selString[i] = '_';
Fariborz Jahanian56338352007-11-13 21:02:00 +0000984 NameStr += selString;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000985 }
Fariborz Jahanian56338352007-11-13 21:02:00 +0000986 // Remember this name for metadata emission
987 MethodInternalNames[OMD] = NameStr;
988 ResultStr += NameStr;
Mike Stump11289f42009-09-09 15:08:12 +0000989
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000990 // Rewrite arguments
991 ResultStr += "(";
Mike Stump11289f42009-09-09 15:08:12 +0000992
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000993 // invisible arguments
Douglas Gregorffca3a22009-01-09 17:18:27 +0000994 if (OMD->isInstanceMethod()) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000995 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000996 selfTy = Context->getPointerType(selfTy);
Steve Naroffdc5b6b22008-03-12 00:25:36 +0000997 if (!LangOpts.Microsoft) {
998 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
999 ResultStr += "struct ";
1000 }
1001 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001002 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00001003 ResultStr += " *";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001004 }
1005 else
Steve Naroffd9803712009-04-29 16:37:50 +00001006 ResultStr += Context->getObjCClassType().getAsString();
Mike Stump11289f42009-09-09 15:08:12 +00001007
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001008 ResultStr += " self, ";
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001009 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001010 ResultStr += " _cmd";
Mike Stump11289f42009-09-09 15:08:12 +00001011
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001012 // Method arguments.
Chris Lattnera4997152009-02-20 18:43:26 +00001013 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1014 E = OMD->param_end(); PI != E; ++PI) {
1015 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001016 ResultStr += ", ";
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001017 if (PDecl->getType()->isObjCQualifiedIdType()) {
1018 ResultStr += "id ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001019 ResultStr += PDecl->getNameAsString();
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001020 } else {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001021 std::string Name = PDecl->getNameAsString();
Steve Naroffa5c0db82008-12-11 21:05:33 +00001022 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroff44df6a22008-10-30 14:45:29 +00001023 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001024 const BlockPointerType *BPT = PDecl->getType()->getAs<BlockPointerType>();
Douglas Gregor7de59662009-05-29 20:38:28 +00001025 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name,
1026 Context->PrintingPolicy);
Steve Naroff44df6a22008-10-30 14:45:29 +00001027 } else
Douglas Gregor7de59662009-05-29 20:38:28 +00001028 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001029 ResultStr += Name;
1030 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001031 }
Fariborz Jahanianeab81cd2008-01-21 20:14:23 +00001032 if (OMD->isVariadic())
1033 ResultStr += ", ...";
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001034 ResultStr += ") ";
Mike Stump11289f42009-09-09 15:08:12 +00001035
Steve Naroffb067bbd2008-07-16 14:40:40 +00001036 if (FPRetType) {
1037 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump11289f42009-09-09 15:08:12 +00001038
Steve Naroffb067bbd2008-07-16 14:40:40 +00001039 // Now, emit the argument types (if any).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001040 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001041 ResultStr += "(";
1042 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1043 if (i) ResultStr += ", ";
1044 std::string ParamStr = FT->getArgType(i).getAsString();
1045 ResultStr += ParamStr;
1046 }
1047 if (FT->isVariadic()) {
1048 if (FT->getNumArgs()) ResultStr += ", ";
1049 ResultStr += "...";
1050 }
1051 ResultStr += ")";
1052 } else {
1053 ResultStr += "()";
1054 }
1055 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001056}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001057void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001058 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1059 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump11289f42009-09-09 15:08:12 +00001060
Fariborz Jahanian02d964b2010-02-15 21:11:41 +00001061 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump11289f42009-09-09 15:08:12 +00001062
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001063 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001064 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1065 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001066 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001067 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001068 ObjCMethodDecl *OMD = *I;
1069 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001070 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001071 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redla7b98a72009-04-26 20:35:05 +00001072
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001073 const char *startBuf = SM->getCharacterData(LocStart);
1074 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001075 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001076 }
Mike Stump11289f42009-09-09 15:08:12 +00001077
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001078 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001079 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1080 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001081 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001082 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001083 ObjCMethodDecl *OMD = *I;
1084 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001085 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001086 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +00001087
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001088 const char *startBuf = SM->getCharacterData(LocStart);
1089 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001090 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001091 }
Steve Naroffe1908e32008-12-01 20:33:01 +00001092 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001093 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001094 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001095 I != E; ++I) {
Steve Naroffc038b3a2008-12-02 17:36:43 +00001096 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffe1908e32008-12-01 20:33:01 +00001097 }
1098
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001099 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001100}
1101
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001102void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffc5484042007-10-30 02:23:23 +00001103 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001104 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff2f55b982007-11-01 03:35:41 +00001105 // we haven't seen a forward decl - generate a typedef.
Steve Naroff03f27672007-11-14 23:02:56 +00001106 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001107 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001108 ResultStr += "\n";
1109 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001110 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001111 ResultStr += "\n";
Steve Naroffa1e115e2008-03-10 23:16:54 +00001112 ResultStr += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001113 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001114 ResultStr += ";\n#endif\n";
Steve Naroff2f55b982007-11-01 03:35:41 +00001115 // Mark this typedef as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001116 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff2f55b982007-11-01 03:35:41 +00001117 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001118 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump11289f42009-09-09 15:08:12 +00001119
1120 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001121 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff0c0f5ba2009-01-11 01:06:09 +00001122 RewriteProperty(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001123 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001124 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001125 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001126 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001127 for (ObjCInterfaceDecl::classmeth_iterator
1128 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001129 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001130 RewriteMethodDeclaration(*I);
1131
Steve Naroff4cd61ac2007-10-30 03:43:13 +00001132 // Lastly, comment out the @end.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001133 ReplaceText(ClassDecl->getAtEndRange().getBegin(), 0, "// ");
Steve Naroff161a92b2007-10-26 20:53:56 +00001134}
1135
Steve Naroff08628db2008-12-09 12:56:34 +00001136Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1137 SourceRange SrcRange) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00001138 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1139 // This allows us to reuse all the fun and games in SynthMessageExpr().
1140 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1141 ObjCMessageExpr *MsgExpr;
1142 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1143 llvm::SmallVector<Expr *, 1> ExprVec;
1144 ExprVec.push_back(newStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001145
Steve Naroff1042ff32008-12-08 16:43:47 +00001146 Stmt *Receiver = PropRefExpr->getBase();
1147 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1148 if (PRE && PropGetters[PRE]) {
1149 // This allows us to handle chain/nested property getters.
1150 Receiver = PropGetters[PRE];
1151 }
Ted Kremenek2c809302010-02-11 22:41:21 +00001152 MsgExpr = new (Context) ObjCMessageExpr(*Context, dyn_cast<Expr>(Receiver),
Mike Stump11289f42009-09-09 15:08:12 +00001153 PDecl->getSetterName(), PDecl->getType(),
1154 PDecl->getSetterMethodDecl(),
1155 SourceLocation(), SourceLocation(),
Steve Naroff4588d0f2008-12-04 16:24:46 +00001156 &ExprVec[0], 1);
1157 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001158
Steve Naroff4588d0f2008-12-04 16:24:46 +00001159 // Now do the actual rewrite.
Steve Naroff08628db2008-12-09 12:56:34 +00001160 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffdf705772008-12-10 14:53:27 +00001161 //delete BinOp;
Ted Kremenek5a201952009-02-07 01:47:29 +00001162 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1163 // to things that stay around.
1164 Context->Deallocate(MsgExpr);
Steve Naroff4588d0f2008-12-04 16:24:46 +00001165 return ReplacingStmt;
Steve Narofff326f402008-12-03 00:56:33 +00001166}
1167
Steve Naroff4588d0f2008-12-04 16:24:46 +00001168Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Narofff326f402008-12-03 00:56:33 +00001169 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1170 // This allows us to reuse all the fun and games in SynthMessageExpr().
1171 ObjCMessageExpr *MsgExpr;
1172 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
Mike Stump11289f42009-09-09 15:08:12 +00001173
Steve Naroff1042ff32008-12-08 16:43:47 +00001174 Stmt *Receiver = PropRefExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00001175
Steve Naroff1042ff32008-12-08 16:43:47 +00001176 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1177 if (PRE && PropGetters[PRE]) {
1178 // This allows us to handle chain/nested property getters.
1179 Receiver = PropGetters[PRE];
1180 }
Ted Kremenek2c809302010-02-11 22:41:21 +00001181 MsgExpr = new (Context) ObjCMessageExpr(*Context, dyn_cast<Expr>(Receiver),
Mike Stump11289f42009-09-09 15:08:12 +00001182 PDecl->getGetterName(), PDecl->getType(),
1183 PDecl->getGetterMethodDecl(),
1184 SourceLocation(), SourceLocation(),
Steve Narofff326f402008-12-03 00:56:33 +00001185 0, 0);
1186
Steve Naroff22216db2008-12-04 23:50:32 +00001187 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001188
1189 if (!PropParentMap)
1190 PropParentMap = new ParentMap(CurrentBody);
1191
1192 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1193 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1194 // We stash away the ReplacingStmt since actually doing the
1195 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1196 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek5a201952009-02-07 01:47:29 +00001197 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1198 // to things that stay around.
1199 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001200 return PropRefExpr; // return the original...
1201 } else {
1202 ReplaceStmt(PropRefExpr, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001203 // delete PropRefExpr; elsewhere...
Ted Kremenek5a201952009-02-07 01:47:29 +00001204 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1205 // to things that stay around.
1206 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001207 return ReplacingStmt;
1208 }
Steve Narofff326f402008-12-03 00:56:33 +00001209}
1210
Mike Stump11289f42009-09-09 15:08:12 +00001211Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001212 SourceLocation OrigStart,
1213 bool &replaced) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001214 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001215 const Expr *BaseExpr = IV->getBase();
Steve Naroff677ab3a2008-10-27 17:20:55 +00001216 if (CurMethodDef) {
Fariborz Jahanianf9e8c2b2010-01-26 18:28:51 +00001217 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001218 ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001219 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianf0ed69c2010-01-26 20:37:44 +00001220 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Naroffb1c02372008-05-08 17:52:16 +00001221 // lookup which class implements the instance variable.
1222 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001223 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001224 clsDeclared);
Steve Naroffb1c02372008-05-08 17:52:16 +00001225 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001226
Steve Naroffb1c02372008-05-08 17:52:16 +00001227 // Synthesize an explicit cast to gain access to the ivar.
1228 std::string RecName = clsDeclared->getIdentifier()->getName();
1229 RecName += "_IMPL";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001230 IdentifierInfo *II = &Context->Idents.get(RecName);
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001231 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001232 SourceLocation(), II);
Steve Naroffb1c02372008-05-08 17:52:16 +00001233 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1234 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall97513962010-01-15 18:39:57 +00001235 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1236 CastExpr::CK_Unknown,
1237 IV->getBase());
Steve Naroffb1c02372008-05-08 17:52:16 +00001238 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001239 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1240 IV->getBase()->getLocEnd(),
1241 castExpr);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001242 replaced = true;
Mike Stump11289f42009-09-09 15:08:12 +00001243 if (IV->isFreeIvar() &&
Steve Naroff677ab3a2008-10-27 17:20:55 +00001244 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001245 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1246 IV->getLocation(),
1247 D->getType());
Steve Naroff22216db2008-12-04 23:50:32 +00001248 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb1c02372008-05-08 17:52:16 +00001249 return ME;
Steve Naroff05caa482007-11-15 11:33:00 +00001250 }
Fariborz Jahanian81310812010-01-28 01:41:20 +00001251 // Get the new text
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001252 // Cannot delete IV->getBase(), since PE points to it.
1253 // Replace the old base with the cast. This is important when doing
1254 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001255 IV->setBase(PE);
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001256 return IV;
Steve Naroff05caa482007-11-15 11:33:00 +00001257 }
Steve Naroff24840f62008-04-18 21:55:08 +00001258 } else { // we are outside a method.
Steve Naroff29ce4e52008-05-06 23:20:07 +00001259 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump11289f42009-09-09 15:08:12 +00001260
Steve Naroff29ce4e52008-05-06 23:20:07 +00001261 // Explicit ivar refs need to have a cast inserted.
1262 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian12e2e862010-01-12 17:31:23 +00001263 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Fariborz Jahanian9146e442010-01-11 17:50:35 +00001264 ObjCInterfaceType *iFaceDecl =
1265 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001266 // lookup which class implements the instance variable.
1267 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001268 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001269 clsDeclared);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001270 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001271
Steve Naroff29ce4e52008-05-06 23:20:07 +00001272 // Synthesize an explicit cast to gain access to the ivar.
1273 std::string RecName = clsDeclared->getIdentifier()->getName();
1274 RecName += "_IMPL";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001275 IdentifierInfo *II = &Context->Idents.get(RecName);
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001276 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001277 SourceLocation(), II);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001278 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1279 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall97513962010-01-15 18:39:57 +00001280 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1281 CastExpr::CK_Unknown,
1282 IV->getBase());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001283 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001284 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner34873d22008-05-28 16:38:23 +00001285 IV->getBase()->getLocEnd(), castExpr);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001286 replaced = true;
Steve Naroff29ce4e52008-05-06 23:20:07 +00001287 // Cannot delete IV->getBase(), since PE points to it.
1288 // Replace the old base with the cast. This is important when doing
1289 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001290 IV->setBase(PE);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001291 return IV;
1292 }
Steve Naroff05caa482007-11-15 11:33:00 +00001293 }
Steve Naroff24840f62008-04-18 21:55:08 +00001294 return IV;
Steve Narofff60782b2007-11-15 02:58:25 +00001295}
1296
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001297Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
1298 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1299 CI != E; ++CI) {
1300 if (*CI) {
1301 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1302 if (newStmt)
1303 *CI = newStmt;
1304 }
1305 }
1306 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1307 SourceRange OrigStmtRange = S->getSourceRange();
1308 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1309 replaced);
1310 return newStmt;
Fariborz Jahanian31433382010-02-05 17:48:10 +00001311 }
1312 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1313 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1314 return newStmt;
1315 }
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001316 return S;
1317}
1318
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001319/// SynthCountByEnumWithState - To print:
1320/// ((unsigned int (*)
1321/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001322/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001323/// sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001324/// "countByEnumeratingWithState:objects:count:"),
1325/// &enumState,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001326/// (id *)items, (unsigned int)16)
1327///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001328void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001329 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1330 "id *, unsigned int))(void *)objc_msgSend)";
1331 buf += "\n\t\t";
1332 buf += "((id)l_collection,\n\t\t";
1333 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1334 buf += "\n\t\t";
1335 buf += "&enumState, "
1336 "(id *)items, (unsigned int)16)";
1337}
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001338
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001339/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1340/// statement to exit to its outer synthesized loop.
1341///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001342Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001343 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1344 return S;
1345 // replace break with goto __break_label
1346 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001347
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001348 SourceLocation startLoc = S->getLocStart();
1349 buf = "goto __break_label_";
1350 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001351 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001352
1353 return 0;
1354}
1355
1356/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1357/// statement to continue with its inner synthesized loop.
1358///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001359Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001360 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1361 return S;
1362 // replace continue with goto __continue_label
1363 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001364
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001365 SourceLocation startLoc = S->getLocStart();
1366 buf = "goto __continue_label_";
1367 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001368 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump11289f42009-09-09 15:08:12 +00001369
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001370 return 0;
1371}
1372
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001373/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001374/// It rewrites:
1375/// for ( type elem in collection) { stmts; }
Mike Stump11289f42009-09-09 15:08:12 +00001376
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001377/// Into:
1378/// {
Mike Stump11289f42009-09-09 15:08:12 +00001379/// type elem;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001380/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001381/// id items[16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001382/// id l_collection = (id)collection;
Mike Stump11289f42009-09-09 15:08:12 +00001383/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001384/// objects:items count:16];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001385/// if (limit) {
1386/// unsigned long startMutations = *enumState.mutationsPtr;
1387/// do {
1388/// unsigned long counter = 0;
1389/// do {
Mike Stump11289f42009-09-09 15:08:12 +00001390/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001391/// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001392/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001393/// stmts;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001394/// __continue_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001395/// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001396/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001397/// objects:items count:16]);
1398/// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001399/// __break_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001400/// }
1401/// else
1402/// elem = nil;
1403/// }
1404///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001405Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattnera779d692008-01-31 05:10:40 +00001406 SourceLocation OrigEnd) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001407 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001408 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001409 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump11289f42009-09-09 15:08:12 +00001410 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001411 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001412
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001413 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001414 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001415 const char *elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001416 std::string elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001417 std::string buf;
1418 buf = "\n{\n\t";
1419 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1420 // type elem;
Chris Lattner529efc72009-03-28 06:33:19 +00001421 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek292b3842008-10-06 22:16:13 +00001422 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001423 if (ElementType->isObjCQualifiedIdType() ||
1424 ElementType->isObjCQualifiedInterfaceType())
1425 // Simply use 'id' for all qualified types.
1426 elementTypeAsString = "id";
1427 else
1428 elementTypeAsString = ElementType.getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001429 buf += elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001430 buf += " ";
Chris Lattner86d7d912008-11-24 03:54:41 +00001431 elementName = D->getNameAsCString();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001432 buf += elementName;
1433 buf += ";\n\t";
1434 }
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001435 else {
1436 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner86d7d912008-11-24 03:54:41 +00001437 elementName = DR->getDecl()->getNameAsCString();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001438 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1439 if (VD->getType()->isObjCQualifiedIdType() ||
1440 VD->getType()->isObjCQualifiedInterfaceType())
1441 // Simply use 'id' for all qualified types.
1442 elementTypeAsString = "id";
1443 else
1444 elementTypeAsString = VD->getType().getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001445 }
Mike Stump11289f42009-09-09 15:08:12 +00001446
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001447 // struct __objcFastEnumerationState enumState = { 0 };
1448 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1449 // id items[16];
1450 buf += "id items[16];\n\t";
1451 // id l_collection = (id)
1452 buf += "id l_collection = (id)";
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001453 // Find start location of 'collection' the hard way!
1454 const char *startCollectionBuf = startBuf;
1455 startCollectionBuf += 3; // skip 'for'
1456 startCollectionBuf = strchr(startCollectionBuf, '(');
1457 startCollectionBuf++; // skip '('
1458 // find 'in' and skip it.
1459 while (*startCollectionBuf != ' ' ||
1460 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1461 (*(startCollectionBuf+3) != ' ' &&
1462 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1463 startCollectionBuf++;
1464 startCollectionBuf += 3;
Mike Stump11289f42009-09-09 15:08:12 +00001465
1466 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001467 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001468 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001469 SourceLocation rightParenLoc = S->getRParenLoc();
1470 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1471 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001472 buf = ";\n\t";
Mike Stump11289f42009-09-09 15:08:12 +00001473
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001474 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1475 // objects:items count:16];
1476 // which is synthesized into:
Mike Stump11289f42009-09-09 15:08:12 +00001477 // unsigned int limit =
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001478 // ((unsigned int (*)
1479 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001480 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001481 // sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001482 // "countByEnumeratingWithState:objects:count:"),
1483 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001484 // (id *)items, (unsigned int)16);
1485 buf += "unsigned long limit =\n\t\t";
1486 SynthCountByEnumWithState(buf);
1487 buf += ";\n\t";
1488 /// if (limit) {
1489 /// unsigned long startMutations = *enumState.mutationsPtr;
1490 /// do {
1491 /// unsigned long counter = 0;
1492 /// do {
Mike Stump11289f42009-09-09 15:08:12 +00001493 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001494 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001495 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001496 buf += "if (limit) {\n\t";
1497 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1498 buf += "do {\n\t\t";
1499 buf += "unsigned long counter = 0;\n\t\t";
1500 buf += "do {\n\t\t\t";
1501 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1502 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1503 buf += elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001504 buf += " = (";
1505 buf += elementTypeAsString;
1506 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001507 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001508 ReplaceText(lparenLoc, 1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001509
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001510 /// __continue_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001511 /// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001512 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001513 /// objects:items count:16]);
1514 /// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001515 /// __break_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001516 /// }
1517 /// else
1518 /// elem = nil;
1519 /// }
Mike Stump11289f42009-09-09 15:08:12 +00001520 ///
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001521 buf = ";\n\t";
1522 buf += "__continue_label_";
1523 buf += utostr(ObjCBcLabelNo.back());
1524 buf += ": ;";
1525 buf += "\n\t\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001526 buf += "} while (counter < limit);\n\t";
1527 buf += "} while (limit = ";
1528 SynthCountByEnumWithState(buf);
1529 buf += ");\n\t";
1530 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001531 buf += " = ((";
1532 buf += elementTypeAsString;
1533 buf += ")0);\n\t";
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001534 buf += "__break_label_";
1535 buf += utostr(ObjCBcLabelNo.back());
1536 buf += ": ;\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001537 buf += "}\n\t";
1538 buf += "else\n\t\t";
1539 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001540 buf += " = ((";
1541 buf += elementTypeAsString;
1542 buf += ")0);\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001543 buf += "}\n";
Mike Stump11289f42009-09-09 15:08:12 +00001544
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001545 // Insert all these *after* the statement body.
Sebastian Redla7b98a72009-04-26 20:35:05 +00001546 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Narofff0ff8792008-07-21 18:26:02 +00001547 if (isa<CompoundStmt>(S->getBody())) {
1548 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001549 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001550 } else {
1551 /* Need to treat single statements specially. For example:
1552 *
1553 * for (A *a in b) if (stuff()) break;
1554 * for (A *a in b) xxxyy;
1555 *
1556 * The following code simply scans ahead to the semi to find the actual end.
1557 */
1558 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1559 const char *semiBuf = strchr(stmtBuf, ';');
1560 assert(semiBuf && "Can't find ';'");
1561 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001562 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001563 }
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001564 Stmts.pop_back();
1565 ObjCBcLabelNo.pop_back();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001566 return 0;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001567}
1568
Mike Stump11289f42009-09-09 15:08:12 +00001569/// RewriteObjCSynchronizedStmt -
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001570/// This routine rewrites @synchronized(expr) stmt;
1571/// into:
1572/// objc_sync_enter(expr);
1573/// @try stmt @finally { objc_sync_exit(expr); }
1574///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001575Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001576 // Get the start location and compute the semi location.
1577 SourceLocation startLoc = S->getLocStart();
1578 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001579
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001580 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump11289f42009-09-09 15:08:12 +00001581
1582 std::string buf;
Steve Naroffb2fc0522008-08-21 13:03:03 +00001583 buf = "objc_sync_enter((id)";
1584 const char *lparenBuf = startBuf;
1585 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001586 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001587 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1588 // the sync expression is typically a message expression that's already
Steve Naroffad7013b2008-08-19 13:04:19 +00001589 // been rewritten! (which implies the SourceLocation's are invalid).
1590 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001591 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffad7013b2008-08-19 13:04:19 +00001592 while (*endBuf != ')') endBuf--;
1593 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001594 buf = ");\n";
1595 // declare a new scope with two variables, _stack and _rethrow.
1596 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1597 buf += "int buf[18/*32-bit i386*/];\n";
1598 buf += "char *pointers[4];} _stack;\n";
1599 buf += "id volatile _rethrow = 0;\n";
1600 buf += "objc_exception_try_enter(&_stack);\n";
1601 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001602 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001603 startLoc = S->getSynchBody()->getLocEnd();
1604 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001605
Steve Naroffad7013b2008-08-19 13:04:19 +00001606 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001607 SourceLocation lastCurlyLoc = startLoc;
1608 buf = "}\nelse {\n";
1609 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroffd9803712009-04-29 16:37:50 +00001610 buf += "}\n";
1611 buf += "{ /* implicit finally clause */\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001612 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffec60b432009-12-05 21:43:12 +00001613
1614 std::string syncBuf;
1615 syncBuf += " objc_sync_exit(";
John McCall97513962010-01-15 18:39:57 +00001616 Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1617 CastExpr::CK_Unknown,
1618 S->getSynchExpr());
Ted Kremenek2d470fc2008-09-13 05:16:45 +00001619 std::string syncExprBufS;
1620 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00001621 syncExpr->printPretty(syncExprBuf, *Context, 0,
1622 PrintingPolicy(LangOpts));
Steve Naroffec60b432009-12-05 21:43:12 +00001623 syncBuf += syncExprBuf.str();
1624 syncBuf += ");";
1625
1626 buf += syncBuf;
1627 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001628 buf += "}\n";
1629 buf += "}";
Mike Stump11289f42009-09-09 15:08:12 +00001630
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001631 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00001632
1633 bool hasReturns = false;
1634 HasReturnStmts(S->getSynchBody(), hasReturns);
1635 if (hasReturns)
1636 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1637
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001638 return 0;
1639}
1640
Steve Naroffec60b432009-12-05 21:43:12 +00001641void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1642{
Steve Naroff6d6da252008-12-05 17:03:39 +00001643 // Perform a bottom up traversal of all children.
1644 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1645 CI != E; ++CI)
1646 if (*CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001647 WarnAboutReturnGotoStmts(*CI);
Steve Naroff6d6da252008-12-05 17:03:39 +00001648
Steve Naroffec60b432009-12-05 21:43:12 +00001649 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump11289f42009-09-09 15:08:12 +00001650 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff6d6da252008-12-05 17:03:39 +00001651 TryFinallyContainsReturnDiag);
1652 }
1653 return;
1654}
1655
Steve Naroffec60b432009-12-05 21:43:12 +00001656void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1657{
1658 // Perform a bottom up traversal of all children.
1659 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1660 CI != E; ++CI)
1661 if (*CI)
1662 HasReturnStmts(*CI, hasReturns);
1663
1664 if (isa<ReturnStmt>(S))
1665 hasReturns = true;
1666 return;
1667}
1668
1669void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1670 // Perform a bottom up traversal of all children.
1671 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1672 CI != E; ++CI)
1673 if (*CI) {
1674 RewriteTryReturnStmts(*CI);
1675 }
1676 if (isa<ReturnStmt>(S)) {
1677 SourceLocation startLoc = S->getLocStart();
1678 const char *startBuf = SM->getCharacterData(startLoc);
1679
1680 const char *semiBuf = strchr(startBuf, ';');
1681 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1682 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1683
1684 std::string buf;
1685 buf = "{ objc_exception_try_exit(&_stack); return";
1686
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001687 ReplaceText(startLoc, 6, buf);
1688 InsertText(onePastSemiLoc, "}");
Steve Naroffec60b432009-12-05 21:43:12 +00001689 }
1690 return;
1691}
1692
1693void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1694 // Perform a bottom up traversal of all children.
1695 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1696 CI != E; ++CI)
1697 if (*CI) {
1698 RewriteSyncReturnStmts(*CI, syncExitBuf);
1699 }
1700 if (isa<ReturnStmt>(S)) {
1701 SourceLocation startLoc = S->getLocStart();
1702 const char *startBuf = SM->getCharacterData(startLoc);
1703
1704 const char *semiBuf = strchr(startBuf, ';');
1705 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1706 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1707
1708 std::string buf;
1709 buf = "{ objc_exception_try_exit(&_stack);";
1710 buf += syncExitBuf;
1711 buf += " return";
1712
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001713 ReplaceText(startLoc, 6, buf);
1714 InsertText(onePastSemiLoc, "}");
Steve Naroffec60b432009-12-05 21:43:12 +00001715 }
1716 return;
1717}
1718
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001719Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001720 // Get the start location and compute the semi location.
1721 SourceLocation startLoc = S->getLocStart();
1722 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001723
Steve Naroffbf478ec2007-11-07 04:08:17 +00001724 assert((*startBuf == '@') && "bogus @try location");
1725
1726 std::string buf;
1727 // declare a new scope with two variables, _stack and _rethrow.
1728 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1729 buf += "int buf[18/*32-bit i386*/];\n";
1730 buf += "char *pointers[4];} _stack;\n";
1731 buf += "id volatile _rethrow = 0;\n";
1732 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff16018582007-11-07 18:43:40 +00001733 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffbf478ec2007-11-07 04:08:17 +00001734
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001735 ReplaceText(startLoc, 4, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001736
Steve Naroffbf478ec2007-11-07 04:08:17 +00001737 startLoc = S->getTryBody()->getLocEnd();
1738 startBuf = SM->getCharacterData(startLoc);
1739
1740 assert((*startBuf == '}') && "bogus @try block");
Mike Stump11289f42009-09-09 15:08:12 +00001741
Steve Naroffbf478ec2007-11-07 04:08:17 +00001742 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffce2dca12008-07-16 15:31:30 +00001743 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1744 if (catchList) {
1745 startLoc = startLoc.getFileLocWithOffset(1);
1746 buf = " /* @catch begin */ else {\n";
1747 buf += " id _caught = objc_exception_extract(&_stack);\n";
1748 buf += " objc_exception_try_enter (&_stack);\n";
1749 buf += " if (_setjmp(_stack.buf))\n";
1750 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1751 buf += " else { /* @catch continue */";
Mike Stump11289f42009-09-09 15:08:12 +00001752
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001753 InsertText(startLoc, buf);
Steve Narofffac18fe2008-09-09 19:59:12 +00001754 } else { /* no catch list */
1755 buf = "}\nelse {\n";
1756 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1757 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001758 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffce2dca12008-07-16 15:31:30 +00001759 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001760 bool sawIdTypedCatch = false;
1761 Stmt *lastCatchBody = 0;
Steve Naroffbf478ec2007-11-07 04:08:17 +00001762 while (catchList) {
Steve Naroff371b8fb2009-03-03 19:52:17 +00001763 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001764
Mike Stump11289f42009-09-09 15:08:12 +00001765 if (catchList == S->getCatchStmts())
Steve Naroffbf478ec2007-11-07 04:08:17 +00001766 buf = "if ("; // we are generating code for the first catch clause
1767 else
1768 buf = "else if (";
1769 startLoc = catchList->getLocStart();
1770 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001771
Steve Naroffbf478ec2007-11-07 04:08:17 +00001772 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump11289f42009-09-09 15:08:12 +00001773
Steve Naroffbf478ec2007-11-07 04:08:17 +00001774 const char *lParenLoc = strchr(startBuf, '(');
1775
Steve Naroffe6b7ffd2008-02-01 22:08:12 +00001776 if (catchList->hasEllipsis()) {
Steve Naroffedb5bc62008-02-01 20:02:07 +00001777 // Now rewrite the body...
1778 lastCatchBody = catchList->getCatchBody();
Steve Naroffedb5bc62008-02-01 20:02:07 +00001779 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1780 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001781 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1782 "bogus @catch paren location");
Steve Naroffedb5bc62008-02-01 20:02:07 +00001783 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001784
Steve Naroffedb5bc62008-02-01 20:02:07 +00001785 buf += "1) { id _tmp = _caught;";
Daniel Dunbardec484a2009-08-19 19:10:30 +00001786 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff371b8fb2009-03-03 19:52:17 +00001787 } else if (catchDecl) {
1788 QualType t = catchDecl->getType();
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001789 if (t == Context->getObjCIdType()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001790 buf += "1) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001791 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroffbf478ec2007-11-07 04:08:17 +00001792 sawIdTypedCatch = true;
Fariborz Jahanian59516092010-01-12 01:22:23 +00001793 } else if (t->isObjCObjectPointerType()) {
1794 QualType InterfaceTy = t->getPointeeType();
1795 const ObjCInterfaceType *cls = // Should be a pointer to a class.
1796 InterfaceTy->getAs<ObjCInterfaceType>();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001797 if (cls) {
Steve Naroff16018582007-11-07 18:43:40 +00001798 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001799 buf += cls->getDecl()->getNameAsString();
Steve Naroff16018582007-11-07 18:43:40 +00001800 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001801 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroffbf478ec2007-11-07 04:08:17 +00001802 }
1803 }
1804 // Now rewrite the body...
1805 lastCatchBody = catchList->getCatchBody();
1806 SourceLocation rParenLoc = catchList->getRParenLoc();
1807 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1808 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1809 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1810 assert((*rParenBuf == ')') && "bogus @catch paren location");
1811 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001812
Mike Stump11289f42009-09-09 15:08:12 +00001813 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroffbf478ec2007-11-07 04:08:17 +00001814 // declares the @catch parameter).
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001815 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff371b8fb2009-03-03 19:52:17 +00001816 } else {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001817 assert(false && "@catch rewrite bug");
Steve Naroffa733c7f2007-11-07 15:32:26 +00001818 }
Steve Naroffedb5bc62008-02-01 20:02:07 +00001819 // make sure all the catch bodies get rewritten!
Steve Naroffbf478ec2007-11-07 04:08:17 +00001820 catchList = catchList->getNextCatchStmt();
1821 }
1822 // Complete the catch list...
1823 if (lastCatchBody) {
1824 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001825 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1826 "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001827
Steve Naroff4adbe312008-09-11 15:29:03 +00001828 // Insert the last (implicit) else clause *before* the right curly brace.
1829 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1830 buf = "} /* last catch end */\n";
1831 buf += "else {\n";
1832 buf += " _rethrow = _caught;\n";
1833 buf += " objc_exception_try_exit(&_stack);\n";
1834 buf += "} } /* @catch end */\n";
1835 if (!S->getFinallyStmt())
1836 buf += "}\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001837 InsertText(bodyLoc, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001838
Steve Naroffbf478ec2007-11-07 04:08:17 +00001839 // Set lastCurlyLoc
1840 lastCurlyLoc = lastCatchBody->getLocEnd();
1841 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001842 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001843 startLoc = finalStmt->getLocStart();
1844 startBuf = SM->getCharacterData(startLoc);
1845 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump11289f42009-09-09 15:08:12 +00001846
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001847 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump11289f42009-09-09 15:08:12 +00001848
Steve Naroffbf478ec2007-11-07 04:08:17 +00001849 Stmt *body = finalStmt->getFinallyBody();
1850 SourceLocation startLoc = body->getLocStart();
1851 SourceLocation endLoc = body->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001852 assert(*SM->getCharacterData(startLoc) == '{' &&
1853 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001854 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001855 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001856
Steve Naroffbf478ec2007-11-07 04:08:17 +00001857 startLoc = startLoc.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001858 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Steve Naroffbf478ec2007-11-07 04:08:17 +00001859 endLoc = endLoc.getFileLocWithOffset(-1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001860 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump11289f42009-09-09 15:08:12 +00001861
Steve Naroffbf478ec2007-11-07 04:08:17 +00001862 // Set lastCurlyLoc
1863 lastCurlyLoc = body->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00001864
Steve Naroff6d6da252008-12-05 17:03:39 +00001865 // Now check for any return/continue/go statements within the @try.
Steve Naroffec60b432009-12-05 21:43:12 +00001866 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff4adbe312008-09-11 15:29:03 +00001867 } else { /* no finally clause - make sure we synthesize an implicit one */
1868 buf = "{ /* implicit finally clause */\n";
1869 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1870 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1871 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001872 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00001873
1874 // Now check for any return/continue/go statements within the @try.
1875 // The implicit finally clause won't called if the @try contains any
1876 // jump statements.
1877 bool hasReturns = false;
1878 HasReturnStmts(S->getTryBody(), hasReturns);
1879 if (hasReturns)
1880 RewriteTryReturnStmts(S->getTryBody());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001881 }
1882 // Now emit the final closing curly brace...
1883 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001884 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001885 return 0;
1886}
1887
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001888Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001889 return 0;
1890}
1891
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001892Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001893 return 0;
1894}
1895
Mike Stump11289f42009-09-09 15:08:12 +00001896// This can't be done with ReplaceStmt(S, ThrowExpr), since
1897// the throw expression is typically a message expression that's already
Steve Naroffa733c7f2007-11-07 15:32:26 +00001898// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001899Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroffa733c7f2007-11-07 15:32:26 +00001900 // Get the start location and compute the semi location.
1901 SourceLocation startLoc = S->getLocStart();
1902 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001903
Steve Naroffa733c7f2007-11-07 15:32:26 +00001904 assert((*startBuf == '@') && "bogus @throw location");
1905
1906 std::string buf;
1907 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffc7d2df22008-01-19 00:42:38 +00001908 if (S->getThrowExpr())
1909 buf = "objc_exception_throw(";
1910 else // add an implicit argument
1911 buf = "objc_exception_throw(_caught";
Mike Stump11289f42009-09-09 15:08:12 +00001912
Steve Naroff29788342008-07-25 15:41:30 +00001913 // handle "@ throw" correctly.
1914 const char *wBuf = strchr(startBuf, 'w');
1915 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001916 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001917
Steve Naroffa733c7f2007-11-07 15:32:26 +00001918 const char *semiBuf = strchr(startBuf, ';');
1919 assert((*semiBuf == ';') && "@throw: can't find ';'");
1920 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001921 ReplaceText(semiLoc, 1, ");");
Steve Naroffa733c7f2007-11-07 15:32:26 +00001922 return 0;
1923}
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001924
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001925Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerc6d91c02007-10-17 22:35:30 +00001926 // Create a new string expression.
1927 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlssond8499822007-10-29 05:01:08 +00001928 std::string StrEncoding;
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00001929 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00001930 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
1931 StrEncoding.length(), false,StrType,
1932 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00001933 ReplaceStmt(Exp, Replacement);
Mike Stump11289f42009-09-09 15:08:12 +00001934
Chris Lattner4431a1b2007-11-30 22:53:43 +00001935 // Replace this subexpr in the parent.
Steve Naroff22216db2008-12-04 23:50:32 +00001936 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattner69534692007-10-24 16:57:36 +00001937 return Replacement;
Chris Lattnera7c19fe2007-10-16 22:36:42 +00001938}
1939
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001940Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff2654e182008-12-22 22:16:07 +00001941 if (!SelGetUidFunctionDecl)
1942 SynthSelGetUidFunctionDecl();
Steve Naroffe4f9b232007-11-05 14:50:49 +00001943 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1944 // Create a call to sel_registerName("selName").
1945 llvm::SmallVector<Expr*, 8> SelExprs;
1946 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00001947 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00001948 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00001949 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00001950 false, argType, SourceLocation()));
Steve Naroffe4f9b232007-11-05 14:50:49 +00001951 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1952 &SelExprs[0], SelExprs.size());
Chris Lattner2e0d2602008-01-31 19:37:57 +00001953 ReplaceStmt(Exp, SelExp);
Steve Naroff22216db2008-12-04 23:50:32 +00001954 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffe4f9b232007-11-05 14:50:49 +00001955 return SelExp;
1956}
1957
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001958CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00001959 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
1960 SourceLocation EndLoc) {
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001961 // Get the type, we will need to reference it in a couple spots.
Steve Naroff574440f2007-10-24 22:48:43 +00001962 QualType msgSendType = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001963
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001964 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek5a201952009-02-07 01:47:29 +00001965 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001966
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001967 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattner3c799d72007-10-24 17:06:59 +00001968 QualType pToFunc = Context->getPointerType(msgSendType);
Mike Stump11289f42009-09-09 15:08:12 +00001969 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc,
Anders Carlssona2615922009-07-31 00:48:10 +00001970 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00001971 DRE,
Douglas Gregora11693b2008-11-12 17:17:38 +00001972 /*isLvalue=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001973
John McCall9dd450b2009-09-21 23:43:11 +00001974 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00001975
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00001976 CallExpr *Exp =
1977 new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
1978 EndLoc);
1979 return Exp;
Steve Naroff574440f2007-10-24 22:48:43 +00001980}
1981
Steve Naroff50d42052007-11-01 13:24:47 +00001982static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1983 const char *&startRef, const char *&endRef) {
1984 while (startBuf < endBuf) {
1985 if (*startBuf == '<')
1986 startRef = startBuf; // mark the start.
1987 if (*startBuf == '>') {
Steve Naroff1b232132007-11-09 12:50:28 +00001988 if (startRef && *startRef == '<') {
1989 endRef = startBuf; // mark the end.
1990 return true;
1991 }
1992 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00001993 }
1994 startBuf++;
1995 }
1996 return false;
1997}
1998
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001999static void scanToNextArgument(const char *&argRef) {
2000 int angle = 0;
2001 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2002 if (*argRef == '<')
2003 angle++;
2004 else if (*argRef == '>')
2005 angle--;
2006 argRef++;
2007 }
2008 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2009}
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002010
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002011bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian80c54b02010-02-03 21:29:28 +00002012 if (T->isObjCQualifiedIdType())
2013 return true;
Fariborz Jahanian06769f92010-02-02 18:35:07 +00002014 if (const PointerType *PT = T->getAs<PointerType>()) {
2015 if (PT->getPointeeType()->isObjCQualifiedIdType())
2016 return true;
2017 }
2018 if (T->isObjCObjectPointerType()) {
2019 T = T->getPointeeType();
2020 return T->isObjCQualifiedInterfaceType();
2021 }
2022 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002023}
2024
Steve Naroff873bd842008-07-29 18:15:38 +00002025void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2026 QualType Type = E->getType();
2027 if (needToScanForQualifiers(Type)) {
Steve Naroffdbfc6932008-11-19 21:15:47 +00002028 SourceLocation Loc, EndLoc;
Mike Stump11289f42009-09-09 15:08:12 +00002029
Steve Naroffdbfc6932008-11-19 21:15:47 +00002030 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2031 Loc = ECE->getLParenLoc();
2032 EndLoc = ECE->getRParenLoc();
2033 } else {
2034 Loc = E->getLocStart();
2035 EndLoc = E->getLocEnd();
2036 }
2037 // This will defend against trying to rewrite synthesized expressions.
2038 if (Loc.isInvalid() || EndLoc.isInvalid())
2039 return;
2040
Steve Naroff873bd842008-07-29 18:15:38 +00002041 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffdbfc6932008-11-19 21:15:47 +00002042 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff873bd842008-07-29 18:15:38 +00002043 const char *startRef = 0, *endRef = 0;
2044 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2045 // Get the locations of the startRef, endRef.
2046 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2047 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2048 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002049 InsertText(LessLoc, "/*");
2050 InsertText(GreaterLoc, "*/");
Steve Naroff873bd842008-07-29 18:15:38 +00002051 }
2052 }
2053}
2054
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002055void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002056 SourceLocation Loc;
2057 QualType Type;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002058 const FunctionProtoType *proto = 0;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002059 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2060 Loc = VD->getLocation();
2061 Type = VD->getType();
2062 }
2063 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2064 Loc = FD->getLocation();
2065 // Check for ObjC 'id' and class types that have been adorned with protocol
2066 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall9dd450b2009-09-21 23:43:11 +00002067 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002068 assert(funcType && "missing function type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002069 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002070 if (!proto)
2071 return;
2072 Type = proto->getResultType();
2073 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00002074 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2075 Loc = FD->getLocation();
2076 Type = FD->getType();
2077 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002078 else
2079 return;
Mike Stump11289f42009-09-09 15:08:12 +00002080
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002081 if (needToScanForQualifiers(Type)) {
Steve Naroff50d42052007-11-01 13:24:47 +00002082 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002083
Steve Naroff50d42052007-11-01 13:24:47 +00002084 const char *endBuf = SM->getCharacterData(Loc);
2085 const char *startBuf = endBuf;
Steve Naroff930e0992008-05-31 05:02:17 +00002086 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroff50d42052007-11-01 13:24:47 +00002087 startBuf--; // scan backward (from the decl location) for return type.
2088 const char *startRef = 0, *endRef = 0;
2089 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2090 // Get the locations of the startRef, endRef.
2091 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2092 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2093 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002094 InsertText(LessLoc, "/*");
2095 InsertText(GreaterLoc, "*/");
Steve Naroff37e011c2007-10-31 04:38:33 +00002096 }
2097 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002098 if (!proto)
2099 return; // most likely, was a variable
Steve Naroff50d42052007-11-01 13:24:47 +00002100 // Now check arguments.
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002101 const char *startBuf = SM->getCharacterData(Loc);
2102 const char *startFuncBuf = startBuf;
Steve Naroff50d42052007-11-01 13:24:47 +00002103 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2104 if (needToScanForQualifiers(proto->getArgType(i))) {
2105 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002106
Steve Naroff50d42052007-11-01 13:24:47 +00002107 const char *endBuf = startBuf;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002108 // scan forward (from the decl location) for argument types.
2109 scanToNextArgument(endBuf);
Steve Naroff50d42052007-11-01 13:24:47 +00002110 const char *startRef = 0, *endRef = 0;
2111 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2112 // Get the locations of the startRef, endRef.
Mike Stump11289f42009-09-09 15:08:12 +00002113 SourceLocation LessLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002114 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump11289f42009-09-09 15:08:12 +00002115 SourceLocation GreaterLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002116 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002117 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002118 InsertText(LessLoc, "/*");
2119 InsertText(GreaterLoc, "*/");
Steve Naroff50d42052007-11-01 13:24:47 +00002120 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002121 startBuf = ++endBuf;
2122 }
2123 else {
Steve Naroffc884aa82008-08-06 15:58:23 +00002124 // If the function name is derived from a macro expansion, then the
2125 // argument buffer will not follow the name. Need to speak with Chris.
2126 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002127 startBuf++; // scan forward (from the decl location) for argument types.
2128 startBuf++;
2129 }
Steve Naroff50d42052007-11-01 13:24:47 +00002130 }
Steve Naroff37e011c2007-10-31 04:38:33 +00002131}
2132
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002133void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2134 QualType QT = ND->getType();
2135 const Type* TypePtr = QT->getAs<Type>();
2136 if (!isa<TypeOfExprType>(TypePtr))
2137 return;
2138 while (isa<TypeOfExprType>(TypePtr)) {
2139 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2140 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2141 TypePtr = QT->getAs<Type>();
2142 }
2143 // FIXME. This will not work for multiple declarators; as in:
2144 // __typeof__(a) b,c,d;
2145 std::string TypeAsString(QT.getAsString());
2146 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2147 const char *startBuf = SM->getCharacterData(DeclLoc);
2148 if (ND->getInit()) {
2149 std::string Name(ND->getNameAsString());
2150 TypeAsString += " " + Name + " = ";
2151 Expr *E = ND->getInit();
2152 SourceLocation startLoc;
2153 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2154 startLoc = ECE->getLParenLoc();
2155 else
2156 startLoc = E->getLocStart();
2157 startLoc = SM->getInstantiationLoc(startLoc);
2158 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002159 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002160 }
2161 else {
2162 SourceLocation X = ND->getLocEnd();
2163 X = SM->getInstantiationLoc(X);
2164 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002165 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002166 }
2167}
2168
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002169// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002170void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002171 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2172 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002173 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002174 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002175 &ArgTys[0], ArgTys.size(),
2176 false /*isVariadic*/, 0,
2177 false, false, 0, 0, false,
2178 CC_Default);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002179 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002180 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002181 SelGetUidIdent, getFuncType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002182 FunctionDecl::Extern, false);
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002183}
2184
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002185void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002186 // declared in <objc/objc.h>
Douglas Gregor1e21c192009-01-09 01:47:02 +00002187 if (FD->getIdentifier() &&
2188 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002189 SelGetUidFunctionDecl = FD;
Steve Naroff37e011c2007-10-31 04:38:33 +00002190 return;
2191 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002192 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002193}
2194
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002195static void RewriteBlockPointerType(std::string& Str, QualType Type) {
2196 std::string TypeString(Type.getAsString());
2197 const char *argPtr = TypeString.c_str();
2198 if (!strchr(argPtr, '^')) {
2199 Str += TypeString;
2200 return;
2201 }
2202 while (*argPtr) {
2203 Str += (*argPtr == '^' ? '*' : *argPtr);
2204 argPtr++;
2205 }
2206}
2207
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002208// FIXME. Consolidate this routine with RewriteBlockPointerType.
2209static void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD) {
2210 QualType Type = VD->getType();
2211 std::string TypeString(Type.getAsString());
2212 const char *argPtr = TypeString.c_str();
2213 int paren = 0;
2214 while (*argPtr) {
2215 switch (*argPtr) {
2216 case '(':
2217 Str += *argPtr;
2218 paren++;
2219 break;
2220 case ')':
2221 Str += *argPtr;
2222 paren--;
2223 break;
2224 case '^':
2225 Str += '*';
2226 if (paren == 1)
2227 Str += VD->getNameAsString();
2228 break;
2229 default:
2230 Str += *argPtr;
2231 break;
2232 }
2233 argPtr++;
2234 }
2235}
2236
2237
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002238void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2239 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2240 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2241 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2242 if (!proto)
2243 return;
2244 QualType Type = proto->getResultType();
2245 std::string FdStr = Type.getAsString();
2246 FdStr += " ";
2247 FdStr += FD->getNameAsCString();
2248 FdStr += "(";
2249 unsigned numArgs = proto->getNumArgs();
2250 for (unsigned i = 0; i < numArgs; i++) {
2251 QualType ArgType = proto->getArgType(i);
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002252 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002253 if (i+1 < numArgs)
2254 FdStr += ", ";
2255 }
2256 FdStr += ");\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002257 InsertText(FunLocStart, FdStr);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002258 CurFunctionDeclToDeclareForBlock = 0;
2259}
2260
Steve Naroff17978c42008-03-11 17:37:02 +00002261// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002262void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroff17978c42008-03-11 17:37:02 +00002263 if (SuperContructorFunctionDecl)
2264 return;
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002265 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroff17978c42008-03-11 17:37:02 +00002266 llvm::SmallVector<QualType, 16> ArgTys;
2267 QualType argT = Context->getObjCIdType();
2268 assert(!argT.isNull() && "Can't find 'id' type");
2269 ArgTys.push_back(argT);
2270 ArgTys.push_back(argT);
2271 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2272 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002273 false, 0,
2274 false, false, 0, 0, false,
2275 CC_Default);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002276 SuperContructorFunctionDecl = 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 Naroff17978c42008-03-11 17:37:02 +00002280}
2281
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002282// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002283void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002284 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2285 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002286 QualType argT = Context->getObjCIdType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +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();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +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(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002293 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002294 true /*isVariadic*/, 0,
2295 false, false, 0, 0, false,
2296 CC_Default);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002297 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002298 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002299 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002300 FunctionDecl::Extern, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002301}
2302
Steve Naroff7fa2f042007-11-15 10:28:18 +00002303// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002304void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002305 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
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"));
Steve Naroff7fa2f042007-11-15 10:28:18 +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();
Steve Naroff7fa2f042007-11-15 10:28:18 +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(),
Steve Naroff7fa2f042007-11-15 10:28:18 +00002317 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002318 true /*isVariadic*/, 0,
2319 false, false, 0, 0, false,
2320 CC_Default);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002321 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002322 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002323 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002324 FunctionDecl::Extern, false);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002325}
2326
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002327// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002328void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002329 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2330 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002331 QualType argT = Context->getObjCIdType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002332 assert(!argT.isNull() && "Can't find 'id' type");
2333 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002334 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002335 assert(!argT.isNull() && "Can't find 'SEL' type");
2336 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002337 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002338 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002339 true /*isVariadic*/, 0,
2340 false, false, 0, 0, false,
2341 CC_Default);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002342 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002343 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002344 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002345 FunctionDecl::Extern, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002346}
2347
Mike Stump11289f42009-09-09 15:08:12 +00002348// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002349// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002350void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump11289f42009-09-09 15:08:12 +00002351 IdentifierInfo *msgSendIdent =
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002352 &Context->Idents.get("objc_msgSendSuper_stret");
2353 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002354 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002355 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002356 &Context->Idents.get("objc_super"));
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002357 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2358 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2359 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002360 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002361 assert(!argT.isNull() && "Can't find 'SEL' type");
2362 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002363 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002364 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002365 true /*isVariadic*/, 0,
2366 false, false, 0, 0, false,
2367 CC_Default);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002368 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002369 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002370 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002371 FunctionDecl::Extern, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002372}
2373
Steve Naroff2e4e3852008-05-08 22:02:18 +00002374// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002375void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002376 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2377 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002378 QualType argT = Context->getObjCIdType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002379 assert(!argT.isNull() && "Can't find 'id' type");
2380 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002381 argT = Context->getObjCSelType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002382 assert(!argT.isNull() && "Can't find 'SEL' type");
2383 ArgTys.push_back(argT);
Steve Naroff2e4e3852008-05-08 22:02:18 +00002384 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002385 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002386 true /*isVariadic*/, 0,
2387 false, false, 0, 0, false,
2388 CC_Default);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002389 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002390 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002391 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002392 FunctionDecl::Extern, false);
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002393}
2394
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002395// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002396void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002397 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2398 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002399 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002400 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002401 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002402 false /*isVariadic*/, 0,
2403 false, false, 0, 0, false,
2404 CC_Default);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002405 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002406 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002407 getClassIdent, getClassType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002408 FunctionDecl::Extern, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002409}
2410
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002411// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002412void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002413 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2414 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002415 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002416 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002417 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002418 false /*isVariadic*/, 0,
2419 false, false, 0, 0, false,
2420 CC_Default);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002421 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002422 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002423 getClassIdent, getClassType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002424 FunctionDecl::Extern, false);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002425}
2426
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002427Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffce8e8862008-03-15 00:55:56 +00002428 QualType strType = getConstantStringStructType();
2429
2430 std::string S = "__NSConstantStringImpl_";
Steve Naroffa6141f02008-05-31 03:35:42 +00002431
2432 std::string tmpName = InFileName;
2433 unsigned i;
2434 for (i=0; i < tmpName.length(); i++) {
2435 char c = tmpName.at(i);
2436 // replace any non alphanumeric characters with '_'.
2437 if (!isalpha(c) && (c < '0' || c > '9'))
2438 tmpName[i] = '_';
2439 }
2440 S += tmpName;
2441 S += "_";
Steve Naroffce8e8862008-03-15 00:55:56 +00002442 S += utostr(NumObjCStringLiterals++);
2443
Steve Naroff00a31762008-03-27 22:29:16 +00002444 Preamble += "static __NSConstantStringImpl " + S;
2445 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2446 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffce8e8862008-03-15 00:55:56 +00002447 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek2d470fc2008-09-13 05:16:45 +00002448 std::string prettyBufS;
2449 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00002450 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2451 PrintingPolicy(LangOpts));
Steve Naroff00a31762008-03-27 22:29:16 +00002452 Preamble += prettyBuf.str();
2453 Preamble += ",";
Steve Naroff94ed6dc2009-12-06 01:48:44 +00002454 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002455
2456 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002457 &Context->Idents.get(S), strType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002458 VarDecl::Static);
Ted Kremenek5a201952009-02-07 01:47:29 +00002459 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2460 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002461 Context->getPointerType(DRE->getType()),
Steve Naroffce8e8862008-03-15 00:55:56 +00002462 SourceLocation());
Steve Naroff265a6b92007-11-08 14:30:50 +00002463 // cast to NSConstantString *
John McCall97513962010-01-15 18:39:57 +00002464 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2465 CastExpr::CK_Unknown, Unop);
Chris Lattner2e0d2602008-01-31 19:37:57 +00002466 ReplaceStmt(Exp, cast);
Steve Naroff22216db2008-12-04 23:50:32 +00002467 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff265a6b92007-11-08 14:30:50 +00002468 return cast;
Steve Naroffa397efd2007-11-03 11:27:19 +00002469}
2470
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002471ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002472 // check if we are sending a message to 'super'
Douglas Gregorffca3a22009-01-09 17:18:27 +00002473 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002474
Douglas Gregor8ea1f532008-11-04 14:56:14 +00002475 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
Mike Stump11289f42009-09-09 15:08:12 +00002476 const ObjCObjectPointerType *OPT =
John McCall9dd450b2009-09-21 23:43:11 +00002477 Super->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00002478 assert(OPT);
2479 const ObjCInterfaceType *IT = OPT->getInterfaceType();
Chris Lattnera9b3cae2008-06-21 18:04:54 +00002480 return IT->getDecl();
2481 }
2482 return 0;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002483}
2484
2485// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002486QualType RewriteObjC::getSuperStructType() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002487 if (!SuperStructDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002488 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002489 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002490 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002491 QualType FieldTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002492
Steve Naroff7fa2f042007-11-15 10:28:18 +00002493 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002494 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002495 // struct objc_class *super;
Mike Stump11289f42009-09-09 15:08:12 +00002496 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor91f84212008-12-11 16:49:14 +00002497
Steve Naroff7fa2f042007-11-15 10:28:18 +00002498 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002499 for (unsigned i = 0; i < 2; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002500 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2501 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002502 FieldTypes[i], 0,
2503 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002504 /*Mutable=*/false));
Douglas Gregor91f84212008-12-11 16:49:14 +00002505 }
Mike Stump11289f42009-09-09 15:08:12 +00002506
Douglas Gregord5058122010-02-11 01:19:42 +00002507 SuperStructDecl->completeDefinition();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002508 }
2509 return Context->getTagDeclType(SuperStructDecl);
2510}
2511
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002512QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffce8e8862008-03-15 00:55:56 +00002513 if (!ConstantStringDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002514 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002515 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002516 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffce8e8862008-03-15 00:55:56 +00002517 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002518
Steve Naroffce8e8862008-03-15 00:55:56 +00002519 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002520 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffce8e8862008-03-15 00:55:56 +00002521 // int flags;
Mike Stump11289f42009-09-09 15:08:12 +00002522 FieldTypes[1] = Context->IntTy;
Steve Naroffce8e8862008-03-15 00:55:56 +00002523 // char *str;
Mike Stump11289f42009-09-09 15:08:12 +00002524 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffce8e8862008-03-15 00:55:56 +00002525 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002526 FieldTypes[3] = Context->LongTy;
Douglas Gregor91f84212008-12-11 16:49:14 +00002527
Steve Naroffce8e8862008-03-15 00:55:56 +00002528 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002529 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002530 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2531 ConstantStringDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002532 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002533 FieldTypes[i], 0,
Douglas Gregor91f84212008-12-11 16:49:14 +00002534 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002535 /*Mutable=*/true));
Douglas Gregor91f84212008-12-11 16:49:14 +00002536 }
2537
Douglas Gregord5058122010-02-11 01:19:42 +00002538 ConstantStringDecl->completeDefinition();
Steve Naroffce8e8862008-03-15 00:55:56 +00002539 }
2540 return Context->getTagDeclType(ConstantStringDecl);
2541}
2542
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002543Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2544 SourceLocation StartLoc,
2545 SourceLocation EndLoc) {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002546 if (!SelGetUidFunctionDecl)
2547 SynthSelGetUidFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002548 if (!MsgSendFunctionDecl)
2549 SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002550 if (!MsgSendSuperFunctionDecl)
2551 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002552 if (!MsgSendStretFunctionDecl)
2553 SynthMsgSendStretFunctionDecl();
2554 if (!MsgSendSuperStretFunctionDecl)
2555 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002556 if (!MsgSendFpretFunctionDecl)
2557 SynthMsgSendFpretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002558 if (!GetClassFunctionDecl)
2559 SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002560 if (!GetMetaClassFunctionDecl)
2561 SynthGetMetaClassFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002562
Steve Naroff7fa2f042007-11-15 10:28:18 +00002563 // default to objc_msgSend().
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002564 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2565 // May need to use objc_msgSend_stret() as well.
2566 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroffd9803712009-04-29 16:37:50 +00002567 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2568 QualType resultType = mDecl->getResultType();
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002569 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002570 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002571 else if (resultType->isRealFloatingType())
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002572 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002573 }
Mike Stump11289f42009-09-09 15:08:12 +00002574
Steve Naroff574440f2007-10-24 22:48:43 +00002575 // Synthesize a call to objc_msgSend().
2576 llvm::SmallVector<Expr*, 8> MsgExprs;
2577 IdentifierInfo *clsName = Exp->getClassName();
Mike Stump11289f42009-09-09 15:08:12 +00002578
Steve Naroff574440f2007-10-24 22:48:43 +00002579 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2580 if (clsName) { // class message.
Steve Naroff6c79f972008-07-24 19:44:33 +00002581 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2582 // the 'super' idiom within a class method.
Daniel Dunbar07d07852009-10-18 21:17:35 +00002583 if (clsName->getName() == "super") {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002584 MsgSendFlavor = MsgSendSuperFunctionDecl;
2585 if (MsgSendStretFlavor)
2586 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2587 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002588
2589 ObjCInterfaceDecl *SuperDecl =
Steve Naroff677ab3a2008-10-27 17:20:55 +00002590 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002591
2592 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002593
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002594 // set the receiver to self, the first argument to all methods.
Steve Naroffd9803712009-04-29 16:37:50 +00002595 InitExprs.push_back(
John McCall97513962010-01-15 18:39:57 +00002596 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2597 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002598 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroffd9803712009-04-29 16:37:50 +00002599 Context->getObjCIdType(),
John McCall97513962010-01-15 18:39:57 +00002600 SourceLocation()))
2601 ); // set the 'receiver'.
Steve Naroffd9803712009-04-29 16:37:50 +00002602
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002603 llvm::SmallVector<Expr*, 8> ClsExprs;
2604 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002605 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002606 SuperDecl->getIdentifier()->getNameStart(),
2607 SuperDecl->getIdentifier()->getLength(),
2608 false, argType, SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002609 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002610 &ClsExprs[0],
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002611 ClsExprs.size(),
2612 StartLoc,
2613 EndLoc);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002614 // To turn off a warning, type-cast to 'id'
Douglas Gregore200adc2008-10-27 19:41:14 +00002615 InitExprs.push_back( // set 'super class', using objc_getClass().
John McCall97513962010-01-15 18:39:57 +00002616 NoTypeInfoCStyleCastExpr(Context,
2617 Context->getObjCIdType(),
2618 CastExpr::CK_Unknown, Cls));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002619 // struct objc_super
2620 QualType superType = getSuperStructType();
Steve Naroff0b844f02008-03-11 18:14:26 +00002621 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002622
Steve Naroff0b844f02008-03-11 18:14:26 +00002623 if (LangOpts.Microsoft) {
2624 SynthSuperContructorFunctionDecl();
2625 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002626 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff0b844f02008-03-11 18:14:26 +00002627 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002628 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002629 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002630 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002631 // The code for super is a little tricky to prevent collision with
2632 // the structure definition in the header. The rewriter has it's own
2633 // internal definition (__rw_objc_super) that is uses. This is why
2634 // we need the cast below. For example:
2635 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2636 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002637 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002638 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002639 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00002640 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2641 Context->getPointerType(superType),
2642 CastExpr::CK_Unknown, SuperRep);
Mike Stump11289f42009-09-09 15:08:12 +00002643 } else {
Steve Naroff0b844f02008-03-11 18:14:26 +00002644 // (struct objc_super) { <exprs from above> }
Ted Kremenek013041e2010-02-19 01:50:18 +00002645 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2646 &InitExprs[0], InitExprs.size(),
2647 SourceLocation());
John McCalle15bbff2010-01-18 19:35:47 +00002648 TypeSourceInfo *superTInfo
2649 = Context->getTrivialTypeSourceInfo(superType);
John McCall5d7aa7f2010-01-19 22:33:45 +00002650 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2651 superType, ILE, false);
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002652 // struct objc_super *
Ted Kremenek5a201952009-02-07 01:47:29 +00002653 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002654 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002655 SourceLocation());
Steve Naroff0b844f02008-03-11 18:14:26 +00002656 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002657 MsgExprs.push_back(SuperRep);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002658 } else {
2659 llvm::SmallVector<Expr*, 8> ClsExprs;
2660 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002661 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002662 clsName->getNameStart(),
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002663 clsName->getLength(),
2664 false, argType,
2665 SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002666 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002667 &ClsExprs[0],
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002668 ClsExprs.size(),
2669 StartLoc, EndLoc);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002670 MsgExprs.push_back(Cls);
2671 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002672 } else { // instance message.
2673 Expr *recExpr = Exp->getReceiver();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002674
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002675 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002676 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002677 if (MsgSendStretFlavor)
2678 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002679 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002680
Steve Naroff7fa2f042007-11-15 10:28:18 +00002681 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002682
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002683 InitExprs.push_back(
John McCall97513962010-01-15 18:39:57 +00002684 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2685 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002686 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff97adf602008-07-16 22:35:27 +00002687 Context->getObjCIdType(),
John McCall97513962010-01-15 18:39:57 +00002688 SourceLocation()))
2689 ); // set the 'receiver'.
Mike Stump11289f42009-09-09 15:08:12 +00002690
Steve Naroff7fa2f042007-11-15 10:28:18 +00002691 llvm::SmallVector<Expr*, 8> ClsExprs;
2692 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002693 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002694 SuperDecl->getIdentifier()->getNameStart(),
2695 SuperDecl->getIdentifier()->getLength(),
2696 false, argType, SourceLocation()));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002697 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002698 &ClsExprs[0],
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002699 ClsExprs.size(),
2700 StartLoc, EndLoc);
Fariborz Jahaniand5db92b2007-12-05 17:29:46 +00002701 // To turn off a warning, type-cast to 'id'
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002702 InitExprs.push_back(
Douglas Gregore200adc2008-10-27 19:41:14 +00002703 // set 'super class', using objc_getClass().
John McCall97513962010-01-15 18:39:57 +00002704 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2705 CastExpr::CK_Unknown, Cls));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002706 // struct objc_super
2707 QualType superType = getSuperStructType();
Steve Naroff17978c42008-03-11 17:37:02 +00002708 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002709
Steve Naroff17978c42008-03-11 17:37:02 +00002710 if (LangOpts.Microsoft) {
2711 SynthSuperContructorFunctionDecl();
2712 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002713 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff17978c42008-03-11 17:37:02 +00002714 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002715 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002716 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002717 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002718 // The code for super is a little tricky to prevent collision with
2719 // the structure definition in the header. The rewriter has it's own
2720 // internal definition (__rw_objc_super) that is uses. This is why
2721 // we need the cast below. For example:
2722 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2723 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002724 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002725 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002726 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00002727 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2728 Context->getPointerType(superType),
2729 CastExpr::CK_Unknown, SuperRep);
Steve Naroff17978c42008-03-11 17:37:02 +00002730 } else {
2731 // (struct objc_super) { <exprs from above> }
Ted Kremenek013041e2010-02-19 01:50:18 +00002732 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2733 &InitExprs[0], InitExprs.size(),
2734 SourceLocation());
John McCalle15bbff2010-01-18 19:35:47 +00002735 TypeSourceInfo *superTInfo
2736 = Context->getTrivialTypeSourceInfo(superType);
John McCall5d7aa7f2010-01-19 22:33:45 +00002737 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2738 superType, ILE, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002739 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002740 MsgExprs.push_back(SuperRep);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002741 } else {
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002742 // Remove all type-casts because it may contain objc-style types; e.g.
2743 // Foo<Proto> *.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002744 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002745 recExpr = CE->getSubExpr();
John McCall97513962010-01-15 18:39:57 +00002746 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2747 CastExpr::CK_Unknown, recExpr);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002748 MsgExprs.push_back(recExpr);
2749 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002750 }
Steve Naroffa397efd2007-11-03 11:27:19 +00002751 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff574440f2007-10-24 22:48:43 +00002752 llvm::SmallVector<Expr*, 8> SelExprs;
2753 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002754 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002755 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002756 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00002757 false, argType, SourceLocation()));
Steve Naroff574440f2007-10-24 22:48:43 +00002758 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002759 &SelExprs[0], SelExprs.size(),
2760 StartLoc,
2761 EndLoc);
Steve Naroff574440f2007-10-24 22:48:43 +00002762 MsgExprs.push_back(SelExp);
Mike Stump11289f42009-09-09 15:08:12 +00002763
Steve Naroff574440f2007-10-24 22:48:43 +00002764 // Now push any user supplied arguments.
2765 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroffe7f18192007-11-14 23:54:14 +00002766 Expr *userExpr = Exp->getArg(i);
Steve Narofff60782b2007-11-15 02:58:25 +00002767 // Make all implicit casts explicit...ICE comes in handy:-)
2768 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2769 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregore200adc2008-10-27 19:41:14 +00002770 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002771 ? Context->getObjCIdType()
Douglas Gregore200adc2008-10-27 19:41:14 +00002772 : ICE->getType();
John McCall97513962010-01-15 18:39:57 +00002773 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CastExpr::CK_Unknown,
2774 userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002775 }
2776 // Make id<P...> cast into an 'id' cast.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002777 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002778 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregorf19b2312008-10-28 15:36:24 +00002779 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002780 userExpr = CE->getSubExpr();
John McCall97513962010-01-15 18:39:57 +00002781 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2782 CastExpr::CK_Unknown, userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002783 }
Mike Stump11289f42009-09-09 15:08:12 +00002784 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002785 MsgExprs.push_back(userExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00002786 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2787 // out the argument in the original expression (since we aren't deleting
2788 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2789 //Exp->setArg(i, 0);
Steve Naroff574440f2007-10-24 22:48:43 +00002790 }
Steve Narofff36987c2007-11-04 22:37:50 +00002791 // Generate the funky cast.
2792 CastExpr *cast;
2793 llvm::SmallVector<QualType, 8> ArgTypes;
2794 QualType returnType;
Mike Stump11289f42009-09-09 15:08:12 +00002795
Steve Narofff36987c2007-11-04 22:37:50 +00002796 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff44864e42007-11-15 10:43:57 +00002797 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2798 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2799 else
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002800 ArgTypes.push_back(Context->getObjCIdType());
2801 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattnera4997152009-02-20 18:43:26 +00002802 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Narofff36987c2007-11-04 22:37:50 +00002803 // Push any user argument types.
Chris Lattnera4997152009-02-20 18:43:26 +00002804 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2805 E = OMD->param_end(); PI != E; ++PI) {
2806 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump11289f42009-09-09 15:08:12 +00002807 ? Context->getObjCIdType()
Chris Lattnera4997152009-02-20 18:43:26 +00002808 : (*PI)->getType();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002809 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00002810 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002811 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002812 t = Context->getPointerType(BPT->getPointeeType());
2813 }
Steve Naroff98eb8d12007-11-05 14:36:37 +00002814 ArgTypes.push_back(t);
2815 }
Chris Lattnera4997152009-02-20 18:43:26 +00002816 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2817 ? Context->getObjCIdType() : OMD->getResultType();
Fariborz Jahanianf89eb2b2010-02-24 01:25:40 +00002818 if (isTopLevelBlockPointerType(returnType)) {
2819 const BlockPointerType *BPT = returnType->getAs<BlockPointerType>();
2820 returnType = Context->getPointerType(BPT->getPointeeType());
2821 }
Steve Narofff36987c2007-11-04 22:37:50 +00002822 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002823 returnType = Context->getObjCIdType();
Steve Narofff36987c2007-11-04 22:37:50 +00002824 }
2825 // Get the type, we will need to reference it in a couple spots.
Steve Naroff7fa2f042007-11-15 10:28:18 +00002826 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002827
Steve Narofff36987c2007-11-04 22:37:50 +00002828 // Create a reference to the objc_msgSend() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002829 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002830 SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002831
Mike Stump11289f42009-09-09 15:08:12 +00002832 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Narofff36987c2007-11-04 22:37:50 +00002833 // If we don't do this cast, we get the following bizarre warning/note:
2834 // xx.m:13: warning: function called through a non-compatible type
2835 // xx.m:13: note: if this code is reached, the program will abort
John McCall97513962010-01-15 18:39:57 +00002836 cast = NoTypeInfoCStyleCastExpr(Context,
2837 Context->getPointerType(Context->VoidTy),
2838 CastExpr::CK_Unknown, DRE);
Mike Stump11289f42009-09-09 15:08:12 +00002839
Steve Narofff36987c2007-11-04 22:37:50 +00002840 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002841 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002842 &ArgTypes[0], ArgTypes.size(),
Steve Naroff327f0f42008-03-18 02:02:04 +00002843 // If we don't have a method decl, force a variadic cast.
Douglas Gregor36c569f2010-02-21 22:15:06 +00002844 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0,
2845 false, false, 0, 0, false,
2846 CC_Default);
Steve Narofff36987c2007-11-04 22:37:50 +00002847 castType = Context->getPointerType(castType);
John McCall97513962010-01-15 18:39:57 +00002848 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
2849 cast);
Steve Narofff36987c2007-11-04 22:37:50 +00002850
2851 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002852 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump11289f42009-09-09 15:08:12 +00002853
John McCall9dd450b2009-09-21 23:43:11 +00002854 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002855 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002856 MsgExprs.size(),
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002857 FT->getResultType(), EndLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002858 Stmt *ReplacingStmt = CE;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002859 if (MsgSendStretFlavor) {
2860 // We have the method which returns a struct/union. Must also generate
2861 // call to objc_msgSend_stret and hang both varieties on a conditional
2862 // expression which dictate which one to envoke depending on size of
2863 // method's return type.
Mike Stump11289f42009-09-09 15:08:12 +00002864
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002865 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002866 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002867 SourceLocation());
2868 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall97513962010-01-15 18:39:57 +00002869 cast = NoTypeInfoCStyleCastExpr(Context,
2870 Context->getPointerType(Context->VoidTy),
2871 CastExpr::CK_Unknown, STDRE);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002872 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002873 castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002874 &ArgTypes[0], ArgTypes.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002875 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0,
2876 false, false, 0, 0, false,
2877 CC_Default);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002878 castType = Context->getPointerType(castType);
John McCall97513962010-01-15 18:39:57 +00002879 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
2880 cast);
Mike Stump11289f42009-09-09 15:08:12 +00002881
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002882 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00002883 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00002884
John McCall9dd450b2009-09-21 23:43:11 +00002885 FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002886 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002887 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002888 FT->getResultType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002889
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002890 // Build sizeof(returnType)
Mike Stump11289f42009-09-09 15:08:12 +00002891 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCallbcd03502009-12-07 02:54:59 +00002892 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl6f282892008-11-11 17:56:53 +00002893 Context->getSizeType(),
2894 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002895 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2896 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2897 // For X86 it is more complicated and some kind of target specific routine
2898 // is needed to decide what to do.
Mike Stump11289f42009-09-09 15:08:12 +00002899 unsigned IntSize =
Chris Lattner37e05872008-03-05 18:54:05 +00002900 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Mike Stump11289f42009-09-09 15:08:12 +00002901 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002902 Context->IntTy,
2903 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002904 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
2905 BinaryOperator::LE,
2906 Context->IntTy,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002907 SourceLocation());
2908 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump11289f42009-09-09 15:08:12 +00002909 ConditionalOperator *CondExpr =
Douglas Gregor7e112b02009-08-26 14:37:04 +00002910 new (Context) ConditionalOperator(lessThanExpr,
2911 SourceLocation(), CE,
2912 SourceLocation(), STCE, returnType);
Ted Kremenek5a201952009-02-07 01:47:29 +00002913 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002914 }
Mike Stump11289f42009-09-09 15:08:12 +00002915 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002916 return ReplacingStmt;
2917}
2918
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002919Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002920 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
2921 Exp->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002922
Steve Naroff574440f2007-10-24 22:48:43 +00002923 // Now do the actual rewrite.
Chris Lattner2e0d2602008-01-31 19:37:57 +00002924 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00002925
2926 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002927 return ReplacingStmt;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002928}
2929
Steve Naroffd9803712009-04-29 16:37:50 +00002930// typedef struct objc_object Protocol;
2931QualType RewriteObjC::getProtocolType() {
2932 if (!ProtocolTypeDecl) {
John McCallbcd03502009-12-07 02:54:59 +00002933 TypeSourceInfo *TInfo
2934 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroffd9803712009-04-29 16:37:50 +00002935 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002936 SourceLocation(),
Steve Naroffd9803712009-04-29 16:37:50 +00002937 &Context->Idents.get("Protocol"),
John McCallbcd03502009-12-07 02:54:59 +00002938 TInfo);
Steve Naroffd9803712009-04-29 16:37:50 +00002939 }
2940 return Context->getTypeDeclType(ProtocolTypeDecl);
2941}
2942
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00002943/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroffd9803712009-04-29 16:37:50 +00002944/// a synthesized/forward data reference (to the protocol's metadata).
2945/// The forward references (and metadata) are generated in
2946/// RewriteObjC::HandleTranslationUnit().
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002947Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroffd9803712009-04-29 16:37:50 +00002948 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
2949 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump11289f42009-09-09 15:08:12 +00002950 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregored6c7442009-11-23 11:41:28 +00002951 ID, getProtocolType(), 0, VarDecl::Extern);
Steve Naroffd9803712009-04-29 16:37:50 +00002952 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
2953 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
2954 Context->getPointerType(DRE->getType()),
2955 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00002956 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
2957 CastExpr::CK_Unknown,
2958 DerefExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00002959 ReplaceStmt(Exp, castExpr);
2960 ProtocolExprDecls.insert(Exp->getProtocol());
Mike Stump11289f42009-09-09 15:08:12 +00002961 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00002962 return castExpr;
Mike Stump11289f42009-09-09 15:08:12 +00002963
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00002964}
2965
Mike Stump11289f42009-09-09 15:08:12 +00002966bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002967 const char *endBuf) {
2968 while (startBuf < endBuf) {
2969 if (*startBuf == '#') {
2970 // Skip whitespace.
2971 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2972 ;
2973 if (!strncmp(startBuf, "if", strlen("if")) ||
2974 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2975 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2976 !strncmp(startBuf, "define", strlen("define")) ||
2977 !strncmp(startBuf, "undef", strlen("undef")) ||
2978 !strncmp(startBuf, "else", strlen("else")) ||
2979 !strncmp(startBuf, "elif", strlen("elif")) ||
2980 !strncmp(startBuf, "endif", strlen("endif")) ||
2981 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2982 !strncmp(startBuf, "include", strlen("include")) ||
2983 !strncmp(startBuf, "import", strlen("import")) ||
2984 !strncmp(startBuf, "include_next", strlen("include_next")))
2985 return true;
2986 }
2987 startBuf++;
2988 }
2989 return false;
2990}
2991
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002992/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002993/// an objective-c class with ivars.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002994void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002995 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002996 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Mike Stump11289f42009-09-09 15:08:12 +00002997 assert(CDecl->getNameAsCString() &&
Douglas Gregor77324f32008-11-17 14:58:09 +00002998 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00002999 // Do not synthesize more than once.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003000 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00003001 return;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003002 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003003 int NumIvars = CDecl->ivar_size();
Steve Naroffdde78982007-11-14 19:25:57 +00003004 SourceLocation LocStart = CDecl->getLocStart();
3005 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00003006
Steve Naroffdde78982007-11-14 19:25:57 +00003007 const char *startBuf = SM->getCharacterData(LocStart);
3008 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00003009
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003010 // If no ivars and no root or if its root, directly or indirectly,
3011 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003012 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3013 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner184e65d2009-04-14 23:22:57 +00003014 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003015 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003016 return;
3017 }
Mike Stump11289f42009-09-09 15:08:12 +00003018
3019 // FIXME: This has potential of causing problem. If
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003020 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003021 Result += "\nstruct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003022 Result += CDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00003023 if (LangOpts.Microsoft)
3024 Result += "_IMPL";
Steve Naroffdc5b6b22008-03-12 00:25:36 +00003025
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003026 if (NumIvars > 0) {
Steve Naroffdde78982007-11-14 19:25:57 +00003027 const char *cursor = strchr(startBuf, '{');
Mike Stump11289f42009-09-09 15:08:12 +00003028 assert((cursor && endBuf)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003029 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003030 // If the buffer contains preprocessor directives, we do more fine-grained
3031 // rewrites. This is intended to fix code that looks like (which occurs in
3032 // NSURL.h, for example):
3033 //
3034 // #ifdef XYZ
3035 // @interface Foo : NSObject
3036 // #else
3037 // @interface FooBar : NSObject
3038 // #endif
3039 // {
3040 // int i;
3041 // }
3042 // @end
3043 //
3044 // This clause is segregated to avoid breaking the common case.
3045 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump11289f42009-09-09 15:08:12 +00003046 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003047 CDecl->getClassLoc();
3048 const char *endHeader = SM->getCharacterData(L);
Chris Lattner184e65d2009-04-14 23:22:57 +00003049 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003050
Chris Lattnerf5b77512009-02-20 18:18:36 +00003051 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003052 // advance to the end of the referenced protocols.
3053 while (endHeader < cursor && *endHeader != '>') endHeader++;
3054 endHeader++;
3055 }
3056 // rewrite the original header
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003057 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003058 } else {
3059 // rewrite the original header *without* disturbing the '{'
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003060 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003061 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003062 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroffdde78982007-11-14 19:25:57 +00003063 Result = "\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003064 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003065 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003066 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003067 Result += "_IVARS;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003068
Steve Naroffdde78982007-11-14 19:25:57 +00003069 // insert the super class structure definition.
Chris Lattner1780a852008-01-31 19:42:41 +00003070 SourceLocation OnePastCurly =
3071 LocStart.getFileLocWithOffset(cursor-startBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003072 InsertText(OnePastCurly, Result);
Steve Naroffdde78982007-11-14 19:25:57 +00003073 }
3074 cursor++; // past '{'
Mike Stump11289f42009-09-09 15:08:12 +00003075
Steve Naroffdde78982007-11-14 19:25:57 +00003076 // Now comment out any visibility specifiers.
3077 while (cursor < endBuf) {
3078 if (*cursor == '@') {
3079 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner174a8252007-11-14 22:57:51 +00003080 // Skip whitespace.
3081 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3082 /*scan*/;
3083
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003084 // FIXME: presence of @public, etc. inside comment results in
3085 // this transformation as well, which is still correct c-code.
Steve Naroffdde78982007-11-14 19:25:57 +00003086 if (!strncmp(cursor, "public", strlen("public")) ||
3087 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffaf91b9a2008-04-04 22:34:24 +00003088 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003089 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003090 InsertText(atLoc, "// ");
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003091 }
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003092 // FIXME: If there are cases where '<' is used in ivar declaration part
3093 // of user code, then scan the ivar list and use needToScanForQualifiers
3094 // for type checking.
3095 else if (*cursor == '<') {
3096 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003097 InsertText(atLoc, "/* ");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003098 cursor = strchr(cursor, '>');
3099 cursor++;
3100 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003101 InsertText(atLoc, " */");
Steve Naroff295570a2008-10-30 12:09:33 +00003102 } else if (*cursor == '^') { // rewrite block specifier.
3103 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003104 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003105 }
Steve Naroffdde78982007-11-14 19:25:57 +00003106 cursor++;
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003107 }
Steve Naroffdde78982007-11-14 19:25:57 +00003108 // Don't forget to add a ';'!!
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003109 InsertText(LocEnd.getFileLocWithOffset(1), ";");
Steve Naroffdde78982007-11-14 19:25:57 +00003110 } else { // we don't have any instance variables - insert super struct.
Chris Lattner184e65d2009-04-14 23:22:57 +00003111 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroffdde78982007-11-14 19:25:57 +00003112 Result += " {\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003113 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003114 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003115 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003116 Result += "_IVARS;\n};\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003117 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003118 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003119 // Mark this struct as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003120 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff13e74872008-05-06 18:26:51 +00003121 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003122}
3123
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003124// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003125/// class methods.
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003126template<typename MethodIterator>
3127void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3128 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +00003129 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003130 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +00003131 const char *ClassName,
3132 std::string &Result) {
Chris Lattner31bc07e2007-12-12 07:46:12 +00003133 if (MethodBegin == MethodEnd) return;
Mike Stump11289f42009-09-09 15:08:12 +00003134
Chris Lattner31bc07e2007-12-12 07:46:12 +00003135 if (!objc_impl_method) {
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003136 /* struct _objc_method {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003137 SEL _cmd;
3138 char *method_types;
3139 void *_imp;
3140 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003141 */
Chris Lattner211f8b82007-10-25 17:07:24 +00003142 Result += "\nstruct _objc_method {\n";
3143 Result += "\tSEL _cmd;\n";
3144 Result += "\tchar *method_types;\n";
3145 Result += "\tvoid *_imp;\n";
3146 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003147
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003148 objc_impl_method = true;
Fariborz Jahanian74a1cfa2007-10-19 00:36:46 +00003149 }
Mike Stump11289f42009-09-09 15:08:12 +00003150
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003151 // Build _objc_method_list for class's methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003152
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003153 /* struct {
3154 struct _objc_method_list *next_method;
3155 int method_count;
3156 struct _objc_method method_list[];
3157 }
3158 */
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003159 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003160 Result += "\nstatic struct {\n";
3161 Result += "\tstruct _objc_method_list *next_method;\n";
3162 Result += "\tint method_count;\n";
3163 Result += "\tstruct _objc_method method_list[";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003164 Result += utostr(NumMethods);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003165 Result += "];\n} _OBJC_";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003166 Result += prefix;
3167 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3168 Result += "_METHODS_";
3169 Result += ClassName;
Steve Naroffb327e492008-03-12 17:18:30 +00003170 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003171 Result += IsInstanceMethod ? "inst" : "cls";
3172 Result += "_meth\")))= ";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003173 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003174
Chris Lattner31bc07e2007-12-12 07:46:12 +00003175 Result += "\t,{{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003176 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattner31bc07e2007-12-12 07:46:12 +00003177 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003178 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattner31bc07e2007-12-12 07:46:12 +00003179 Result += "\", \"";
3180 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003181 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003182 Result += MethodInternalNames[*MethodBegin];
3183 Result += "}\n";
3184 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3185 Result += "\t ,{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003186 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003187 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003188 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003189 Result += "\", \"";
3190 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003191 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003192 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanian56338352007-11-13 21:02:00 +00003193 Result += "}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003194 }
Chris Lattner31bc07e2007-12-12 07:46:12 +00003195 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003196}
3197
Steve Naroffd9803712009-04-29 16:37:50 +00003198/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner390d39a2008-07-21 21:32:27 +00003199void RewriteObjC::
Steve Naroffd9803712009-04-29 16:37:50 +00003200RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
3201 const char *ClassName, std::string &Result) {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003202 static bool objc_protocol_methods = false;
Steve Naroffd9803712009-04-29 16:37:50 +00003203
3204 // Output struct protocol_methods holder of method selector and type.
3205 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3206 /* struct protocol_methods {
3207 SEL _cmd;
3208 char *method_types;
3209 }
3210 */
3211 Result += "\nstruct _protocol_methods {\n";
3212 Result += "\tstruct objc_selector *_cmd;\n";
3213 Result += "\tchar *method_types;\n";
3214 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003215
Steve Naroffd9803712009-04-29 16:37:50 +00003216 objc_protocol_methods = true;
3217 }
3218 // Do not synthesize the protocol more than once.
3219 if (ObjCSynthesizedProtocols.count(PDecl))
3220 return;
Mike Stump11289f42009-09-09 15:08:12 +00003221
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003222 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3223 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3224 PDecl->instmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003225 /* struct _objc_protocol_method_list {
3226 int protocol_method_count;
3227 struct protocol_methods protocols[];
3228 }
Steve Naroff251084d2008-03-12 01:06:30 +00003229 */
Steve Naroffd9803712009-04-29 16:37:50 +00003230 Result += "\nstatic struct {\n";
3231 Result += "\tint protocol_method_count;\n";
3232 Result += "\tstruct _protocol_methods protocol_methods[";
3233 Result += utostr(NumMethods);
3234 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3235 Result += PDecl->getNameAsString();
3236 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3237 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003238
Steve Naroffd9803712009-04-29 16:37:50 +00003239 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003240 for (ObjCProtocolDecl::instmeth_iterator
3241 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003242 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003243 if (I == PDecl->instmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003244 Result += "\t ,{{(struct objc_selector *)\"";
3245 else
3246 Result += "\t ,{(struct objc_selector *)\"";
3247 Result += (*I)->getSelector().getAsString().c_str();
3248 std::string MethodTypeString;
3249 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3250 Result += "\", \"";
3251 Result += MethodTypeString;
3252 Result += "\"}\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003253 }
Steve Naroffd9803712009-04-29 16:37:50 +00003254 Result += "\t }\n};\n";
3255 }
Mike Stump11289f42009-09-09 15:08:12 +00003256
Steve Naroffd9803712009-04-29 16:37:50 +00003257 // Output class methods declared in this protocol.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003258 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3259 PDecl->classmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003260 if (NumMethods > 0) {
3261 /* struct _objc_protocol_method_list {
3262 int protocol_method_count;
3263 struct protocol_methods protocols[];
3264 }
3265 */
3266 Result += "\nstatic struct {\n";
3267 Result += "\tint protocol_method_count;\n";
3268 Result += "\tstruct _protocol_methods protocol_methods[";
3269 Result += utostr(NumMethods);
3270 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3271 Result += PDecl->getNameAsString();
3272 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3273 "{\n\t";
3274 Result += utostr(NumMethods);
3275 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003276
Steve Naroffd9803712009-04-29 16:37:50 +00003277 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003278 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003279 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003280 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003281 if (I == PDecl->classmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003282 Result += "\t ,{{(struct objc_selector *)\"";
3283 else
3284 Result += "\t ,{(struct objc_selector *)\"";
3285 Result += (*I)->getSelector().getAsString().c_str();
3286 std::string MethodTypeString;
3287 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3288 Result += "\", \"";
3289 Result += MethodTypeString;
3290 Result += "\"}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003291 }
Steve Naroffd9803712009-04-29 16:37:50 +00003292 Result += "\t }\n};\n";
3293 }
3294
3295 // Output:
3296 /* struct _objc_protocol {
3297 // Objective-C 1.0 extensions
3298 struct _objc_protocol_extension *isa;
3299 char *protocol_name;
3300 struct _objc_protocol **protocol_list;
3301 struct _objc_protocol_method_list *instance_methods;
3302 struct _objc_protocol_method_list *class_methods;
Mike Stump11289f42009-09-09 15:08:12 +00003303 };
Steve Naroffd9803712009-04-29 16:37:50 +00003304 */
3305 static bool objc_protocol = false;
3306 if (!objc_protocol) {
3307 Result += "\nstruct _objc_protocol {\n";
3308 Result += "\tstruct _objc_protocol_extension *isa;\n";
3309 Result += "\tchar *protocol_name;\n";
3310 Result += "\tstruct _objc_protocol **protocol_list;\n";
3311 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3312 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003313 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003314
Steve Naroffd9803712009-04-29 16:37:50 +00003315 objc_protocol = true;
Chris Lattner388f6e92008-07-21 21:33:21 +00003316 }
Mike Stump11289f42009-09-09 15:08:12 +00003317
Steve Naroffd9803712009-04-29 16:37:50 +00003318 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3319 Result += PDecl->getNameAsString();
3320 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3321 "{\n\t0, \"";
3322 Result += PDecl->getNameAsString();
3323 Result += "\", 0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003324 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003325 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3326 Result += PDecl->getNameAsString();
3327 Result += ", ";
3328 }
3329 else
3330 Result += "0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003331 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003332 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3333 Result += PDecl->getNameAsString();
3334 Result += "\n";
3335 }
3336 else
3337 Result += "0\n";
3338 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003339
Steve Naroffd9803712009-04-29 16:37:50 +00003340 // Mark this protocol as having been generated.
3341 if (!ObjCSynthesizedProtocols.insert(PDecl))
3342 assert(false && "protocol already synthesized");
3343
3344}
3345
3346void RewriteObjC::
3347RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3348 const char *prefix, const char *ClassName,
3349 std::string &Result) {
3350 if (Protocols.empty()) return;
Mike Stump11289f42009-09-09 15:08:12 +00003351
Steve Naroffd9803712009-04-29 16:37:50 +00003352 for (unsigned i = 0; i != Protocols.size(); i++)
3353 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3354
Chris Lattner388f6e92008-07-21 21:33:21 +00003355 // Output the top lovel protocol meta-data for the class.
3356 /* struct _objc_protocol_list {
3357 struct _objc_protocol_list *next;
3358 int protocol_count;
3359 struct _objc_protocol *class_protocols[];
3360 }
3361 */
3362 Result += "\nstatic struct {\n";
3363 Result += "\tstruct _objc_protocol_list *next;\n";
3364 Result += "\tint protocol_count;\n";
3365 Result += "\tstruct _objc_protocol *class_protocols[";
3366 Result += utostr(Protocols.size());
3367 Result += "];\n} _OBJC_";
3368 Result += prefix;
3369 Result += "_PROTOCOLS_";
3370 Result += ClassName;
3371 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3372 "{\n\t0, ";
3373 Result += utostr(Protocols.size());
3374 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003375
Chris Lattner388f6e92008-07-21 21:33:21 +00003376 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003377 Result += Protocols[0]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003378 Result += " \n";
Mike Stump11289f42009-09-09 15:08:12 +00003379
Chris Lattner388f6e92008-07-21 21:33:21 +00003380 for (unsigned i = 1; i != Protocols.size(); i++) {
3381 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003382 Result += Protocols[i]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003383 Result += "\n";
3384 }
3385 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003386}
3387
Steve Naroffd9803712009-04-29 16:37:50 +00003388
Mike Stump11289f42009-09-09 15:08:12 +00003389/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003390/// implementation.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003391void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003392 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003393 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003394 // Find category declaration for this implementation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003395 ObjCCategoryDecl *CDecl;
Mike Stump11289f42009-09-09 15:08:12 +00003396 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003397 CDecl = CDecl->getNextClassCategory())
3398 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3399 break;
Mike Stump11289f42009-09-09 15:08:12 +00003400
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003401 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003402 FullCategoryName += '_';
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003403 FullCategoryName += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003404
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003405 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003406 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003407 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003408
3409 // If any of our property implementations have associated getters or
3410 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003411 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3412 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003413 Prop != PropEnd; ++Prop) {
3414 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3415 continue;
3416 if (!(*Prop)->getPropertyIvarDecl())
3417 continue;
3418 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3419 if (!PD)
3420 continue;
3421 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3422 InstanceMethods.push_back(Getter);
3423 if (PD->isReadOnly())
3424 continue;
3425 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3426 InstanceMethods.push_back(Setter);
3427 }
3428 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003429 true, "CATEGORY_", FullCategoryName.c_str(),
3430 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003431
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003432 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003433 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003434 false, "CATEGORY_", FullCategoryName.c_str(),
3435 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003436
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003437 // Protocols referenced in class declaration?
Fariborz Jahanian989e0392007-11-13 22:09:49 +00003438 // Null CDecl is case of a category implementation with no category interface
3439 if (CDecl)
Steve Naroffd9803712009-04-29 16:37:50 +00003440 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3441 FullCategoryName.c_str(), Result);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003442 /* struct _objc_category {
3443 char *category_name;
3444 char *class_name;
3445 struct _objc_method_list *instance_methods;
3446 struct _objc_method_list *class_methods;
3447 struct _objc_protocol_list *protocols;
3448 // Objective-C 1.0 extensions
3449 uint32_t size; // sizeof (struct _objc_category)
Mike Stump11289f42009-09-09 15:08:12 +00003450 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003451 // @property decl.
Mike Stump11289f42009-09-09 15:08:12 +00003452 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003453 */
Mike Stump11289f42009-09-09 15:08:12 +00003454
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003455 static bool objc_category = false;
3456 if (!objc_category) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003457 Result += "\nstruct _objc_category {\n";
3458 Result += "\tchar *category_name;\n";
3459 Result += "\tchar *class_name;\n";
3460 Result += "\tstruct _objc_method_list *instance_methods;\n";
3461 Result += "\tstruct _objc_method_list *class_methods;\n";
3462 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003463 Result += "\tunsigned int size;\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003464 Result += "\tstruct _objc_property_list *instance_properties;\n";
3465 Result += "};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003466 objc_category = true;
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003467 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003468 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3469 Result += FullCategoryName;
Steve Naroffb327e492008-03-12 17:18:30 +00003470 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003471 Result += IDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003472 Result += "\"\n\t, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003473 Result += ClassDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003474 Result += "\"\n";
Mike Stump11289f42009-09-09 15:08:12 +00003475
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003476 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003477 Result += "\t, (struct _objc_method_list *)"
3478 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3479 Result += FullCategoryName;
3480 Result += "\n";
3481 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003482 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003483 Result += "\t, 0\n";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003484 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003485 Result += "\t, (struct _objc_method_list *)"
3486 "&_OBJC_CATEGORY_CLASS_METHODS_";
3487 Result += FullCategoryName;
3488 Result += "\n";
3489 }
3490 else
3491 Result += "\t, 0\n";
Mike Stump11289f42009-09-09 15:08:12 +00003492
Chris Lattnerf5b77512009-02-20 18:18:36 +00003493 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump11289f42009-09-09 15:08:12 +00003494 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003495 Result += FullCategoryName;
3496 Result += "\n";
3497 }
3498 else
3499 Result += "\t, 0\n";
3500 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003501}
3502
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003503/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3504/// ivar offset.
Mike Stump11289f42009-09-09 15:08:12 +00003505void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
3506 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003507 std::string &Result) {
Steve Naroffde7d0f62008-07-16 18:22:22 +00003508 if (ivar->isBitField()) {
3509 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3510 // place all bitfields at offset 0.
3511 Result += "0";
3512 } else {
3513 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003514 Result += IDecl->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003515 if (LangOpts.Microsoft)
3516 Result += "_IMPL";
3517 Result += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003518 Result += ivar->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003519 Result += ")";
3520 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003521}
3522
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003523//===----------------------------------------------------------------------===//
3524// Meta Data Emission
3525//===----------------------------------------------------------------------===//
3526
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003527void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003528 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003529 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00003530
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003531 // Explictly declared @interface's are already synthesized.
Steve Naroffaac654a2009-04-20 20:09:33 +00003532 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump11289f42009-09-09 15:08:12 +00003533 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003534 // produce correct synthesis as yet.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003535 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003536 }
Mike Stump11289f42009-09-09 15:08:12 +00003537
Chris Lattner30d23e82007-12-12 07:56:42 +00003538 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003539 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump11289f42009-09-09 15:08:12 +00003540 ? IDecl->ivar_size()
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003541 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003542 if (NumIvars > 0) {
3543 static bool objc_ivar = false;
3544 if (!objc_ivar) {
3545 /* struct _objc_ivar {
3546 char *ivar_name;
3547 char *ivar_type;
3548 int ivar_offset;
Mike Stump11289f42009-09-09 15:08:12 +00003549 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003550 */
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003551 Result += "\nstruct _objc_ivar {\n";
3552 Result += "\tchar *ivar_name;\n";
3553 Result += "\tchar *ivar_type;\n";
3554 Result += "\tint ivar_offset;\n";
3555 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003556
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003557 objc_ivar = true;
3558 }
3559
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003560 /* struct {
3561 int ivar_count;
3562 struct _objc_ivar ivar_list[nIvars];
Mike Stump11289f42009-09-09 15:08:12 +00003563 };
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003564 */
Mike Stump11289f42009-09-09 15:08:12 +00003565 Result += "\nstatic struct {\n";
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003566 Result += "\tint ivar_count;\n";
3567 Result += "\tstruct _objc_ivar ivar_list[";
3568 Result += utostr(NumIvars);
3569 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003570 Result += IDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003571 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003572 "{\n\t";
3573 Result += utostr(NumIvars);
3574 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003575
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003576 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor5f662052009-04-23 03:23:08 +00003577 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003578 if (!IDecl->ivar_empty()) {
Fariborz Jahanianaef66222010-02-19 00:31:17 +00003579 for (ObjCInterfaceDecl::ivar_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003580 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor5f662052009-04-23 03:23:08 +00003581 IV != IVEnd; ++IV)
3582 IVars.push_back(*IV);
Fariborz Jahanianaef66222010-02-19 00:31:17 +00003583 IVI = IDecl->ivar_begin();
3584 IVE = IDecl->ivar_end();
Chris Lattner30d23e82007-12-12 07:56:42 +00003585 } else {
3586 IVI = CDecl->ivar_begin();
3587 IVE = CDecl->ivar_end();
3588 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003589 Result += "\t,{{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003590 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003591 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003592 std::string TmpString, StrEncoding;
3593 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3594 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003595 Result += StrEncoding;
3596 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003597 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003598 Result += "}\n";
Chris Lattner30d23e82007-12-12 07:56:42 +00003599 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003600 Result += "\t ,{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003601 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003602 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003603 std::string TmpString, StrEncoding;
3604 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3605 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003606 Result += StrEncoding;
3607 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003608 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003609 Result += "}\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003610 }
Mike Stump11289f42009-09-09 15:08:12 +00003611
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003612 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003613 }
Mike Stump11289f42009-09-09 15:08:12 +00003614
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003615 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003616 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003617 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003618
3619 // If any of our property implementations have associated getters or
3620 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003621 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3622 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003623 Prop != PropEnd; ++Prop) {
3624 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3625 continue;
3626 if (!(*Prop)->getPropertyIvarDecl())
3627 continue;
3628 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3629 if (!PD)
3630 continue;
3631 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3632 InstanceMethods.push_back(Getter);
3633 if (PD->isReadOnly())
3634 continue;
3635 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3636 InstanceMethods.push_back(Setter);
3637 }
3638 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003639 true, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003640
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003641 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003642 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003643 false, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003644
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003645 // Protocols referenced in class declaration?
Steve Naroffd9803712009-04-29 16:37:50 +00003646 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3647 "CLASS", CDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003648
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003649 // Declaration of class/meta-class metadata
3650 /* struct _objc_class {
3651 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003652 const char *super_class_name;
3653 char *name;
3654 long version;
3655 long info;
3656 long instance_size;
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003657 struct _objc_ivar_list *ivars;
3658 struct _objc_method_list *methods;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003659 struct objc_cache *cache;
3660 struct objc_protocol_list *protocols;
3661 const char *ivar_layout;
3662 struct _objc_class_ext *ext;
Mike Stump11289f42009-09-09 15:08:12 +00003663 };
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003664 */
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003665 static bool objc_class = false;
3666 if (!objc_class) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003667 Result += "\nstruct _objc_class {\n";
3668 Result += "\tstruct _objc_class *isa;\n";
3669 Result += "\tconst char *super_class_name;\n";
3670 Result += "\tchar *name;\n";
3671 Result += "\tlong version;\n";
3672 Result += "\tlong info;\n";
3673 Result += "\tlong instance_size;\n";
3674 Result += "\tstruct _objc_ivar_list *ivars;\n";
3675 Result += "\tstruct _objc_method_list *methods;\n";
3676 Result += "\tstruct objc_cache *cache;\n";
3677 Result += "\tstruct _objc_protocol_list *protocols;\n";
3678 Result += "\tconst char *ivar_layout;\n";
3679 Result += "\tstruct _objc_class_ext *ext;\n";
3680 Result += "};\n";
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003681 objc_class = true;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003682 }
Mike Stump11289f42009-09-09 15:08:12 +00003683
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003684 // Meta-class metadata generation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003685 ObjCInterfaceDecl *RootClass = 0;
3686 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003687 while (SuperClass) {
3688 RootClass = SuperClass;
3689 SuperClass = SuperClass->getSuperClass();
3690 }
3691 SuperClass = CDecl->getSuperClass();
Mike Stump11289f42009-09-09 15:08:12 +00003692
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003693 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003694 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003695 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003696 "{\n\t(struct _objc_class *)\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003697 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003698 Result += "\"";
3699
3700 if (SuperClass) {
3701 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003702 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003703 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003704 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003705 Result += "\"";
3706 }
3707 else {
3708 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003709 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003710 Result += "\"";
3711 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003712 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003713 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003714 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003715 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff0b844f02008-03-11 18:14:26 +00003716 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003717 Result += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003718 Result += "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003719 }
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003720 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003721 Result += ", 0\n";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003722 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003723 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003724 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003725 Result += ",0,0\n";
3726 }
Fariborz Jahanian486f7182007-10-24 20:54:23 +00003727 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003728 Result += "\t,0,0,0,0\n";
3729 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003730
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003731 // class metadata generation.
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003732 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003733 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003734 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003735 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003736 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003737 if (SuperClass) {
3738 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003739 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003740 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003741 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003742 Result += "\"";
3743 }
3744 else {
3745 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003746 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003747 Result += "\"";
3748 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003749 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003750 Result += ", 0,1";
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003751 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003752 Result += ",0";
3753 else {
3754 // class has size. Must synthesize its size.
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00003755 Result += ",sizeof(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003756 Result += CDecl->getNameAsString();
Steve Naroff14a07462008-03-10 23:33:22 +00003757 if (LangOpts.Microsoft)
3758 Result += "_IMPL";
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003759 Result += ")";
3760 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003761 if (NumIvars > 0) {
Steve Naroff17978c42008-03-11 17:37:02 +00003762 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003763 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003764 Result += "\n\t";
3765 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003766 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003767 Result += ",0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003768 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003769 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003770 Result += CDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003771 Result += ", 0\n\t";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003772 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003773 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003774 Result += ",0,0";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003775 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003776 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003777 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003778 Result += ", 0,0\n";
3779 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003780 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003781 Result += ",0,0,0\n";
3782 Result += "};\n";
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003783}
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003784
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003785/// RewriteImplementations - This routine rewrites all method implementations
3786/// and emits meta-data.
3787
Steve Narofff8cfd162008-11-13 20:07:04 +00003788void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003789 int ClsDefCount = ClassImplementation.size();
3790 int CatDefCount = CategoryImplementation.size();
Mike Stump11289f42009-09-09 15:08:12 +00003791
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003792 // Rewrite implemented methods
3793 for (int i = 0; i < ClsDefCount; i++)
3794 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003795
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00003796 for (int i = 0; i < CatDefCount; i++)
3797 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofff8cfd162008-11-13 20:07:04 +00003798}
Mike Stump11289f42009-09-09 15:08:12 +00003799
Steve Narofff8cfd162008-11-13 20:07:04 +00003800void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3801 int ClsDefCount = ClassImplementation.size();
3802 int CatDefCount = CategoryImplementation.size();
3803
Steve Naroff30ac2222008-05-07 21:23:49 +00003804 // This is needed for determining instance variable offsets.
Fariborz Jahanian9ab63492010-01-07 18:31:42 +00003805 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003806 // For each implemented class, write out all its meta data.
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003807 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003808 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump11289f42009-09-09 15:08:12 +00003809
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003810 // For each implemented category, write out all its meta data.
3811 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003812 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroffd9803712009-04-29 16:37:50 +00003813
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003814 // Write objc_symtab metadata
3815 /*
3816 struct _objc_symtab
3817 {
3818 long sel_ref_cnt;
3819 SEL *refs;
3820 short cls_def_cnt;
3821 short cat_def_cnt;
3822 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump11289f42009-09-09 15:08:12 +00003823 };
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003824 */
Mike Stump11289f42009-09-09 15:08:12 +00003825
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003826 Result += "\nstruct _objc_symtab {\n";
3827 Result += "\tlong sel_ref_cnt;\n";
3828 Result += "\tSEL *refs;\n";
3829 Result += "\tshort cls_def_cnt;\n";
3830 Result += "\tshort cat_def_cnt;\n";
3831 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3832 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003833
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003834 Result += "static struct _objc_symtab "
Steve Naroffb327e492008-03-12 17:18:30 +00003835 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003836 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003837 + ", " + utostr(CatDefCount) + "\n";
3838 for (int i = 0; i < ClsDefCount; i++) {
3839 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003840 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003841 Result += "\n";
3842 }
Mike Stump11289f42009-09-09 15:08:12 +00003843
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003844 for (int i = 0; i < CatDefCount; i++) {
3845 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003846 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003847 Result += "_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003848 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003849 Result += "\n";
3850 }
Mike Stump11289f42009-09-09 15:08:12 +00003851
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003852 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003853
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003854 // Write objc_module metadata
Mike Stump11289f42009-09-09 15:08:12 +00003855
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003856 /*
3857 struct _objc_module {
3858 long version;
3859 long size;
3860 const char *name;
3861 struct _objc_symtab *symtab;
3862 }
3863 */
Mike Stump11289f42009-09-09 15:08:12 +00003864
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003865 Result += "\nstruct _objc_module {\n";
3866 Result += "\tlong version;\n";
3867 Result += "\tlong size;\n";
3868 Result += "\tconst char *name;\n";
3869 Result += "\tstruct _objc_symtab *symtab;\n";
3870 Result += "};\n\n";
3871 Result += "static struct _objc_module "
Steve Naroffb327e492008-03-12 17:18:30 +00003872 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003873 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003874 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003875 Result += "};\n\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003876
3877 if (LangOpts.Microsoft) {
Steve Naroffd9803712009-04-29 16:37:50 +00003878 if (ProtocolExprDecls.size()) {
3879 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
3880 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump11289f42009-09-09 15:08:12 +00003881 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00003882 E = ProtocolExprDecls.end(); I != E; ++I) {
3883 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
3884 Result += (*I)->getNameAsString();
3885 Result += " = &_OBJC_PROTOCOL_";
3886 Result += (*I)->getNameAsString();
3887 Result += ";\n";
3888 }
3889 Result += "#pragma data_seg(pop)\n\n";
3890 }
Steve Naroff945a3b12008-03-10 20:43:59 +00003891 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffcab93d52008-05-07 00:06:16 +00003892 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003893 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3894 Result += "&_OBJC_MODULES;\n";
3895 Result += "#pragma data_seg(pop)\n\n";
3896 }
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003897}
Chris Lattnera7c19fe2007-10-16 22:36:42 +00003898
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003899void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3900 const std::string &Name,
3901 ValueDecl *VD) {
3902 assert(BlockByRefDeclNo.count(VD) &&
3903 "RewriteByRefString: ByRef decl missing");
3904 ResultStr += "struct __Block_byref_" + Name +
3905 "_" + utostr(BlockByRefDeclNo[VD]) ;
3906}
3907
Steve Naroff677ab3a2008-10-27 17:20:55 +00003908std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3909 const char *funcName,
3910 std::string Tag) {
3911 const FunctionType *AFT = CE->getFunctionType();
3912 QualType RT = AFT->getResultType();
3913 std::string StructRef = "struct " + Tag;
3914 std::string S = "static " + RT.getAsString() + " __" +
3915 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00003916
Steve Naroff677ab3a2008-10-27 17:20:55 +00003917 BlockDecl *BD = CE->getBlockDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003918
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003919 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump11289f42009-09-09 15:08:12 +00003920 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Narofff26a1d42009-02-02 17:19:26 +00003921 // block (to reference imported block decl refs).
3922 S += "(" + StructRef + " *__cself)";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003923 } else if (BD->param_empty()) {
3924 S += "(" + StructRef + " *__cself)";
3925 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003926 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003927 assert(FT && "SynthesizeBlockFunc: No function proto");
3928 S += '(';
3929 // first add the implicit argument.
3930 S += StructRef + " *__cself, ";
3931 std::string ParamStr;
3932 for (BlockDecl::param_iterator AI = BD->param_begin(),
3933 E = BD->param_end(); AI != E; ++AI) {
3934 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003935 ParamStr = (*AI)->getNameAsString();
Douglas Gregor7de59662009-05-29 20:38:28 +00003936 (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003937 S += ParamStr;
3938 }
3939 if (FT->isVariadic()) {
3940 if (!BD->param_empty()) S += ", ";
3941 S += "...";
3942 }
3943 S += ')';
3944 }
3945 S += " {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003946
Steve Naroff677ab3a2008-10-27 17:20:55 +00003947 // Create local declarations to avoid rewriting all closure decl ref exprs.
3948 // First, emit a declaration for all "by ref" decls.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00003949 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003950 E = BlockByRefDecls.end(); I != E; ++I) {
3951 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003952 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003953 std::string TypeString;
3954 RewriteByRefString(TypeString, Name, (*I));
3955 TypeString += " *";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003956 Name = TypeString + Name;
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003957 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump11289f42009-09-09 15:08:12 +00003958 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003959 // Next, emit a declaration for all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00003960 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003961 E = BlockByCopyDecls.end(); I != E; ++I) {
3962 S += " ";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003963 // Handle nested closure invocation. For example:
3964 //
3965 // void (^myImportedClosure)(void);
3966 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003967 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003968 // void (^anotherClosure)(void);
3969 // anotherClosure = ^(void) {
3970 // myImportedClosure(); // import and invoke the closure
3971 // };
3972 //
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00003973 if (isTopLevelBlockPointerType((*I)->getType())) {
3974 RewriteBlockPointerTypeVariable(S, (*I));
3975 S += " = (";
3976 RewriteBlockPointerType(S, (*I)->getType());
3977 S += ")";
3978 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3979 }
3980 else {
Fariborz Jahanianb6a68c02010-02-16 17:26:03 +00003981 std::string Name = (*I)->getNameAsString();
Douglas Gregor7de59662009-05-29 20:38:28 +00003982 (*I)->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00003983 S += Name + " = __cself->" +
3984 (*I)->getNameAsString() + "; // bound by copy\n";
3985 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003986 }
3987 std::string RewrittenStr = RewrittenBlockExprs[CE];
3988 const char *cstr = RewrittenStr.c_str();
3989 while (*cstr++ != '{') ;
3990 S += cstr;
3991 S += "\n";
3992 return S;
3993}
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00003994
Steve Naroff677ab3a2008-10-27 17:20:55 +00003995std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3996 const char *funcName,
3997 std::string Tag) {
3998 std::string StructRef = "struct " + Tag;
3999 std::string S = "static void __";
Mike Stump11289f42009-09-09 15:08:12 +00004000
Steve Naroff677ab3a2008-10-27 17:20:55 +00004001 S += funcName;
4002 S += "_block_copy_" + utostr(i);
4003 S += "(" + StructRef;
4004 S += "*dst, " + StructRef;
4005 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00004006 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004007 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00004008 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004009 S += (*I)->getNameAsString();
Steve Naroff5ac4eac2008-12-11 20:51:38 +00004010 S += ", (void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004011 S += (*I)->getNameAsString();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004012 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004013 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00004014 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004015 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004016 }
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00004017 S += "}\n";
4018
Steve Naroff677ab3a2008-10-27 17:20:55 +00004019 S += "\nstatic void __";
4020 S += funcName;
4021 S += "_block_dispose_" + utostr(i);
4022 S += "(" + StructRef;
4023 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00004024 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004025 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00004026 S += "_Block_object_dispose((void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004027 S += (*I)->getNameAsString();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004028 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004029 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00004030 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004031 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004032 }
Mike Stump11289f42009-09-09 15:08:12 +00004033 S += "}\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004034 return S;
4035}
4036
Steve Naroff30484702009-12-06 21:14:13 +00004037std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4038 std::string Desc) {
Steve Naroff295570a2008-10-30 12:09:33 +00004039 std::string S = "\nstruct " + Tag;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004040 std::string Constructor = " " + Tag;
Mike Stump11289f42009-09-09 15:08:12 +00004041
Steve Naroff677ab3a2008-10-27 17:20:55 +00004042 S += " {\n struct __block_impl impl;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004043 S += " struct " + Desc;
4044 S += "* Desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00004045
Steve Naroff30484702009-12-06 21:14:13 +00004046 Constructor += "(void *fp, "; // Invoke function pointer.
4047 Constructor += "struct " + Desc; // Descriptor pointer.
4048 Constructor += " *desc";
Mike Stump11289f42009-09-09 15:08:12 +00004049
Steve Naroff677ab3a2008-10-27 17:20:55 +00004050 if (BlockDeclRefs.size()) {
4051 // Output all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004052 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004053 E = BlockByCopyDecls.end(); I != E; ++I) {
4054 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004055 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004056 std::string ArgName = "_" + FieldName;
4057 // Handle nested closure invocation. For example:
4058 //
4059 // void (^myImportedBlock)(void);
4060 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00004061 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00004062 // void (^anotherBlock)(void);
4063 // anotherBlock = ^(void) {
4064 // myImportedBlock(); // import and invoke the closure
4065 // };
4066 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00004067 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004068 S += "struct __block_impl *";
4069 Constructor += ", void *" + ArgName;
4070 } else {
Douglas Gregor7de59662009-05-29 20:38:28 +00004071 (*I)->getType().getAsStringInternal(FieldName, Context->PrintingPolicy);
4072 (*I)->getType().getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004073 Constructor += ", " + ArgName;
4074 }
4075 S += FieldName + ";\n";
4076 }
4077 // Output all "by ref" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004078 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004079 E = BlockByRefDecls.end(); I != E; ++I) {
4080 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004081 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004082 std::string ArgName = "_" + FieldName;
4083 // Handle nested closure invocation. For example:
4084 //
4085 // void (^myImportedBlock)(void);
4086 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00004087 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00004088 // void (^anotherBlock)(void);
4089 // anotherBlock = ^(void) {
4090 // myImportedBlock(); // import and invoke the closure
4091 // };
4092 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00004093 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004094 S += "struct __block_impl *";
4095 Constructor += ", void *" + ArgName;
4096 } else {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004097 std::string TypeString;
4098 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004099 TypeString += " *";
4100 FieldName = TypeString + FieldName;
4101 ArgName = TypeString + ArgName;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004102 Constructor += ", " + ArgName;
4103 }
4104 S += FieldName + "; // by ref\n";
4105 }
4106 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004107 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00004108 if (GlobalVarDecl)
4109 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4110 else
4111 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004112 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00004113
Steve Naroff30484702009-12-06 21:14:13 +00004114 Constructor += " Desc = desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00004115
Steve Naroff677ab3a2008-10-27 17:20:55 +00004116 // Initialize all "by copy" arguments.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004117 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004118 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004119 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004120 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00004121 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004122 Constructor += Name + " = (struct __block_impl *)_";
4123 else
4124 Constructor += Name + " = _";
4125 Constructor += Name + ";\n";
4126 }
4127 // Initialize all "by ref" arguments.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004128 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004129 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004130 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004131 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00004132 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004133 Constructor += Name + " = (struct __block_impl *)_";
4134 else
4135 Constructor += Name + " = _";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004136 Constructor += Name + "->__forwarding;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004137 }
4138 } else {
4139 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004140 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00004141 if (GlobalVarDecl)
4142 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4143 else
4144 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004145 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4146 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004147 }
4148 Constructor += " ";
4149 Constructor += "}\n";
4150 S += Constructor;
4151 S += "};\n";
4152 return S;
4153}
4154
Steve Naroff30484702009-12-06 21:14:13 +00004155std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4156 std::string ImplTag, int i,
4157 const char *FunName,
4158 unsigned hasCopy) {
4159 std::string S = "\nstatic struct " + DescTag;
4160
4161 S += " {\n unsigned long reserved;\n";
4162 S += " unsigned long Block_size;\n";
4163 if (hasCopy) {
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004164 S += " void (*copy)(struct ";
4165 S += ImplTag; S += "*, struct ";
4166 S += ImplTag; S += "*);\n";
4167
4168 S += " void (*dispose)(struct ";
4169 S += ImplTag; S += "*);\n";
Steve Naroff30484702009-12-06 21:14:13 +00004170 }
4171 S += "} ";
4172
4173 S += DescTag + "_DATA = { 0, sizeof(struct ";
4174 S += ImplTag + ")";
4175 if (hasCopy) {
4176 S += ", __" + std::string(FunName) + "_block_copy_" + utostr(i);
4177 S += ", __" + std::string(FunName) + "_block_dispose_" + utostr(i);
4178 }
4179 S += "};\n";
4180 return S;
4181}
4182
Steve Naroff677ab3a2008-10-27 17:20:55 +00004183void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004184 const char *FunName) {
4185 // Insert declaration for the function in which block literal is used.
Fariborz Jahanian5c26eee2010-01-15 18:14:52 +00004186 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004187 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004188 // Insert closures that were part of the function.
4189 for (unsigned i = 0; i < Blocks.size(); i++) {
4190
4191 CollectBlockDeclRefInfo(Blocks[i]);
4192
Steve Naroff30484702009-12-06 21:14:13 +00004193 std::string ImplTag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
4194 std::string DescTag = "__" + std::string(FunName) + "_block_desc_" + utostr(i);
Mike Stump11289f42009-09-09 15:08:12 +00004195
Steve Naroff30484702009-12-06 21:14:13 +00004196 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004197
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004198 InsertText(FunLocStart, CI);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004199
Steve Naroff30484702009-12-06 21:14:13 +00004200 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump11289f42009-09-09 15:08:12 +00004201
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004202 InsertText(FunLocStart, CF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004203
4204 if (ImportedBlockDecls.size()) {
Steve Naroff30484702009-12-06 21:14:13 +00004205 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004206 InsertText(FunLocStart, HF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004207 }
Steve Naroff30484702009-12-06 21:14:13 +00004208 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4209 ImportedBlockDecls.size() > 0);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004210 InsertText(FunLocStart, BD);
Mike Stump11289f42009-09-09 15:08:12 +00004211
Steve Naroff677ab3a2008-10-27 17:20:55 +00004212 BlockDeclRefs.clear();
4213 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004214 BlockByRefDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004215 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004216 BlockByCopyDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004217 BlockCallExprs.clear();
4218 ImportedBlockDecls.clear();
4219 }
4220 Blocks.clear();
4221 RewrittenBlockExprs.clear();
4222}
4223
4224void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4225 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner86d7d912008-11-24 03:54:41 +00004226 const char *FuncName = FD->getNameAsCString();
Mike Stump11289f42009-09-09 15:08:12 +00004227
Steve Naroff677ab3a2008-10-27 17:20:55 +00004228 SynthesizeBlockLiterals(FunLocStart, FuncName);
4229}
4230
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004231static void BuildUniqueMethodName(std::string &Name,
4232 ObjCMethodDecl *MD) {
4233 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4234 Name = IFace->getNameAsCString();
4235 Name += "__" + MD->getSelector().getAsString();
4236 // Convert colons to underscores.
4237 std::string::size_type loc = 0;
4238 while ((loc = Name.find(":", loc)) != std::string::npos)
4239 Name.replace(loc, 1, "_");
4240}
4241
Steve Naroff677ab3a2008-10-27 17:20:55 +00004242void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff295570a2008-10-30 12:09:33 +00004243 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4244 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianb5f99c32010-01-29 01:55:49 +00004245 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004246 std::string FuncName;
4247 BuildUniqueMethodName(FuncName, MD);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004248 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
4249}
4250
4251void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4252 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4253 CI != E; ++CI)
4254 if (*CI) {
4255 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4256 GetBlockDeclRefExprs(CBE->getBody());
4257 else
4258 GetBlockDeclRefExprs(*CI);
4259 }
4260 // Handle specific things.
4261 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
4262 // FIXME: Handle enums.
4263 if (!isa<FunctionDecl>(CDRE->getDecl()))
4264 BlockDeclRefs.push_back(CDRE);
4265 return;
4266}
4267
4268void RewriteObjC::GetBlockCallExprs(Stmt *S) {
4269 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4270 CI != E; ++CI)
4271 if (*CI) {
4272 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4273 GetBlockCallExprs(CBE->getBody());
4274 else
4275 GetBlockCallExprs(*CI);
4276 }
Mike Stump11289f42009-09-09 15:08:12 +00004277
Steve Naroff677ab3a2008-10-27 17:20:55 +00004278 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4279 if (CE->getCallee()->getType()->isBlockPointerType()) {
4280 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
4281 }
4282 }
4283 return;
4284}
4285
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004286Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004287 // Navigate to relevant type information.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004288 const BlockPointerType *CPT = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004289
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004290 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004291 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004292 } else if (const BlockDeclRefExpr *CDRE =
4293 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004294 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004295 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004296 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004297 }
4298 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4299 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4300 }
4301 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4302 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4303 else if (const ConditionalOperator *CEXPR =
4304 dyn_cast<ConditionalOperator>(BlockExp)) {
4305 Expr *LHSExp = CEXPR->getLHS();
4306 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4307 Expr *RHSExp = CEXPR->getRHS();
4308 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4309 Expr *CONDExp = CEXPR->getCond();
4310 ConditionalOperator *CondExpr =
4311 new (Context) ConditionalOperator(CONDExp,
4312 SourceLocation(), cast<Expr>(LHSStmt),
4313 SourceLocation(), cast<Expr>(RHSStmt),
4314 Exp->getType());
4315 return CondExpr;
Fariborz Jahanian6ab7ed42009-12-18 01:15:21 +00004316 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4317 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004318 } else {
4319 assert(1 && "RewriteBlockClass: Bad type");
4320 }
4321 assert(CPT && "RewriteBlockClass: Bad type");
John McCall9dd450b2009-09-21 23:43:11 +00004322 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004323 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004324 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004325 // FTP will be null for closures that don't take arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004326
Steve Naroff350b6652008-10-30 10:07:53 +00004327 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
4328 SourceLocation(),
4329 &Context->Idents.get("__block_impl"));
4330 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff677ab3a2008-10-27 17:20:55 +00004331
Steve Naroff350b6652008-10-30 10:07:53 +00004332 // Generate a funky cast.
4333 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00004334
Steve Naroff350b6652008-10-30 10:07:53 +00004335 // Push the block argument type.
4336 ArgTypes.push_back(PtrBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004337 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004338 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff350b6652008-10-30 10:07:53 +00004339 E = FTP->arg_type_end(); I && (I != E); ++I) {
4340 QualType t = *I;
4341 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00004342 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004343 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff350b6652008-10-30 10:07:53 +00004344 t = Context->getPointerType(BPT->getPointeeType());
4345 }
4346 ArgTypes.push_back(t);
4347 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004348 }
Steve Naroff350b6652008-10-30 10:07:53 +00004349 // Now do the pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00004350 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00004351 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0,
4352 false, false, 0, 0,
4353 false, CC_Default);
Mike Stump11289f42009-09-09 15:08:12 +00004354
Steve Naroff350b6652008-10-30 10:07:53 +00004355 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump11289f42009-09-09 15:08:12 +00004356
John McCall97513962010-01-15 18:39:57 +00004357 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4358 CastExpr::CK_Unknown,
4359 const_cast<Expr*>(BlockExp));
Steve Naroff350b6652008-10-30 10:07:53 +00004360 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00004361 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4362 BlkCast);
Steve Naroff350b6652008-10-30 10:07:53 +00004363 //PE->dump();
Mike Stump11289f42009-09-09 15:08:12 +00004364
Douglas Gregor91f84212008-12-11 16:49:14 +00004365 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00004366 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004367 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek5a201952009-02-07 01:47:29 +00004368 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4369 FD->getType());
Mike Stump11289f42009-09-09 15:08:12 +00004370
John McCall97513962010-01-15 18:39:57 +00004371 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4372 CastExpr::CK_Unknown, ME);
Ted Kremenek5a201952009-02-07 01:47:29 +00004373 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump11289f42009-09-09 15:08:12 +00004374
Steve Naroff350b6652008-10-30 10:07:53 +00004375 llvm::SmallVector<Expr*, 8> BlkExprs;
4376 // Add the implicit argument.
4377 BlkExprs.push_back(BlkCast);
4378 // Add the user arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004379 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004380 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00004381 BlkExprs.push_back(*I);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004382 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004383 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4384 BlkExprs.size(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004385 Exp->getType(), SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004386 return CE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004387}
4388
4389void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004390 Stmt *BlockCall = SynthesizeBlockCall(Exp, Exp->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00004391 ReplaceStmt(Exp, BlockCall);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004392}
4393
Steve Naroffd9803712009-04-29 16:37:50 +00004394// We need to return the rewritten expression to handle cases where the
4395// BlockDeclRefExpr is embedded in another expression being rewritten.
4396// For example:
4397//
4398// int main() {
4399// __block Foo *f;
4400// __block int i;
Mike Stump11289f42009-09-09 15:08:12 +00004401//
Steve Naroffd9803712009-04-29 16:37:50 +00004402// void (^myblock)() = ^() {
4403// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4404// i = 77;
4405// };
4406//}
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004407Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanian25c07fa2009-12-23 19:26:34 +00004408 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004409 // for each DeclRefExp where BYREFVAR is name of the variable.
4410 ValueDecl *VD;
4411 bool isArrow = true;
4412 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4413 VD = BDRE->getDecl();
4414 else {
4415 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4416 isArrow = false;
4417 }
4418
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004419 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4420 &Context->Idents.get("__forwarding"),
4421 Context->VoidPtrTy, 0,
4422 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004423 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4424 FD, SourceLocation(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004425 FD->getType());
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004426
4427 const char *Name = VD->getNameAsCString();
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004428 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4429 &Context->Idents.get(Name),
4430 Context->VoidPtrTy, 0,
4431 /*BitWidth=*/0, /*Mutable=*/true);
4432 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004433 DeclRefExp->getType());
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004434
4435
4436
Steve Narofff26a1d42009-02-02 17:19:26 +00004437 // Need parens to enforce precedence.
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004438 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4439 ME);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004440 ReplaceStmt(DeclRefExp, PE);
Steve Naroffd9803712009-04-29 16:37:50 +00004441 return PE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004442}
4443
Steve Naroffc989a7b2008-11-03 23:29:32 +00004444void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4445 SourceLocation LocStart = CE->getLParenLoc();
4446 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofff4b992a2008-10-28 20:29:00 +00004447
4448 // Need to avoid trying to rewrite synthesized casts.
4449 if (LocStart.isInvalid())
4450 return;
Steve Naroff3e7ced12008-11-03 11:20:24 +00004451 // Need to avoid trying to rewrite casts contained in macros.
4452 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4453 return;
Mike Stump11289f42009-09-09 15:08:12 +00004454
Steve Naroff677ab3a2008-10-27 17:20:55 +00004455 const char *startBuf = SM->getCharacterData(LocStart);
4456 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004457 QualType QT = CE->getType();
4458 const Type* TypePtr = QT->getAs<Type>();
4459 if (isa<TypeOfExprType>(TypePtr)) {
4460 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4461 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4462 std::string TypeAsString = "(";
Fariborz Jahanianf5067912010-02-18 01:20:22 +00004463 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004464 TypeAsString += ")";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004465 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004466 return;
4467 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004468 // advance the location to startArgList.
4469 const char *argPtr = startBuf;
Mike Stump11289f42009-09-09 15:08:12 +00004470
Steve Naroff677ab3a2008-10-27 17:20:55 +00004471 while (*argPtr++ && (argPtr < endBuf)) {
4472 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004473 case '^':
4474 // Replace the '^' with '*'.
4475 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004476 ReplaceText(LocStart, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00004477 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004478 }
4479 }
4480 return;
4481}
4482
4483void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4484 SourceLocation DeclLoc = FD->getLocation();
4485 unsigned parenCount = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004486
Steve Naroff677ab3a2008-10-27 17:20:55 +00004487 // We have 1 or more arguments that have closure pointers.
4488 const char *startBuf = SM->getCharacterData(DeclLoc);
4489 const char *startArgList = strchr(startBuf, '(');
Mike Stump11289f42009-09-09 15:08:12 +00004490
Steve Naroff677ab3a2008-10-27 17:20:55 +00004491 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004492
Steve Naroff677ab3a2008-10-27 17:20:55 +00004493 parenCount++;
4494 // advance the location to startArgList.
4495 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4496 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump11289f42009-09-09 15:08:12 +00004497
Steve Naroff677ab3a2008-10-27 17:20:55 +00004498 const char *argPtr = startArgList;
Mike Stump11289f42009-09-09 15:08:12 +00004499
Steve Naroff677ab3a2008-10-27 17:20:55 +00004500 while (*argPtr++ && parenCount) {
4501 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004502 case '^':
4503 // Replace the '^' with '*'.
4504 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004505 ReplaceText(DeclLoc, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00004506 break;
4507 case '(':
4508 parenCount++;
4509 break;
4510 case ')':
4511 parenCount--;
4512 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004513 }
4514 }
4515 return;
4516}
4517
4518bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004519 const FunctionProtoType *FTP;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004520 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004521 if (PT) {
John McCall9dd450b2009-09-21 23:43:11 +00004522 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004523 } else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004524 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004525 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall9dd450b2009-09-21 23:43:11 +00004526 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004527 }
4528 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004529 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004530 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +00004531 if (isTopLevelBlockPointerType(*I))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004532 return true;
4533 }
4534 return false;
4535}
4536
Ted Kremenek5a201952009-02-07 01:47:29 +00004537void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4538 const char *&RParen) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004539 const char *argPtr = strchr(Name, '(');
4540 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004541
Steve Naroff677ab3a2008-10-27 17:20:55 +00004542 LParen = argPtr; // output the start.
4543 argPtr++; // skip past the left paren.
4544 unsigned parenCount = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004545
Steve Naroff677ab3a2008-10-27 17:20:55 +00004546 while (*argPtr && parenCount) {
4547 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004548 case '(': parenCount++; break;
4549 case ')': parenCount--; break;
4550 default: break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004551 }
4552 if (parenCount) argPtr++;
4553 }
4554 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4555 RParen = argPtr; // output the end
4556}
4557
4558void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4559 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4560 RewriteBlockPointerFunctionArgs(FD);
4561 return;
Mike Stump11289f42009-09-09 15:08:12 +00004562 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004563 // Handle Variables and Typedefs.
4564 SourceLocation DeclLoc = ND->getLocation();
4565 QualType DeclT;
4566 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4567 DeclT = VD->getType();
4568 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4569 DeclT = TDD->getUnderlyingType();
4570 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4571 DeclT = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004572 else
Steve Naroff677ab3a2008-10-27 17:20:55 +00004573 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump11289f42009-09-09 15:08:12 +00004574
Steve Naroff677ab3a2008-10-27 17:20:55 +00004575 const char *startBuf = SM->getCharacterData(DeclLoc);
4576 const char *endBuf = startBuf;
4577 // scan backward (from the decl location) for the end of the previous decl.
4578 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4579 startBuf--;
Mike Stump11289f42009-09-09 15:08:12 +00004580
Steve Naroff677ab3a2008-10-27 17:20:55 +00004581 // *startBuf != '^' if we are dealing with a pointer to function that
4582 // may take block argument types (which will be handled below).
4583 if (*startBuf == '^') {
4584 // Replace the '^' with '*', computing a negative offset.
4585 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004586 ReplaceText(DeclLoc, 1, "*");
Steve Naroff677ab3a2008-10-27 17:20:55 +00004587 }
4588 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4589 // Replace the '^' with '*' for arguments.
4590 DeclLoc = ND->getLocation();
4591 startBuf = SM->getCharacterData(DeclLoc);
4592 const char *argListBegin, *argListEnd;
4593 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4594 while (argListBegin < argListEnd) {
4595 if (*argListBegin == '^') {
4596 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004597 ReplaceText(CaretLoc, 1, "*");
Steve Naroff677ab3a2008-10-27 17:20:55 +00004598 }
4599 argListBegin++;
4600 }
4601 }
4602 return;
4603}
4604
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004605
4606/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4607/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4608/// struct Block_byref_id_object *src) {
4609/// _Block_object_assign (&_dest->object, _src->object,
4610/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4611/// [|BLOCK_FIELD_IS_WEAK]) // object
4612/// _Block_object_assign(&_dest->object, _src->object,
4613/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4614/// [|BLOCK_FIELD_IS_WEAK]) // block
4615/// }
4616/// And:
4617/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4618/// _Block_object_dispose(_src->object,
4619/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4620/// [|BLOCK_FIELD_IS_WEAK]) // object
4621/// _Block_object_dispose(_src->object,
4622/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4623/// [|BLOCK_FIELD_IS_WEAK]) // block
4624/// }
4625
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004626std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4627 int flag) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004628 std::string S;
Benjamin Kramere056cea2010-01-10 19:57:50 +00004629 if (CopyDestroyCache.count(flag))
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004630 return S;
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004631 CopyDestroyCache.insert(flag);
4632 S = "static void __Block_byref_id_object_copy_";
4633 S += utostr(flag);
4634 S += "(void *dst, void *src) {\n";
4635
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004636 // offset into the object pointer is computed as:
4637 // void * + void* + int + int + void* + void *
4638 unsigned IntSize =
4639 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4640 unsigned VoidPtrSize =
4641 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4642
4643 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
4644 S += " _Block_object_assign((char*)dst + ";
4645 S += utostr(offset);
4646 S += ", *(void * *) ((char*)src + ";
4647 S += utostr(offset);
4648 S += "), ";
4649 S += utostr(flag);
4650 S += ");\n}\n";
4651
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004652 S += "static void __Block_byref_id_object_dispose_";
4653 S += utostr(flag);
4654 S += "(void *src) {\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004655 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4656 S += utostr(offset);
4657 S += "), ";
4658 S += utostr(flag);
4659 S += ");\n}\n";
4660 return S;
4661}
4662
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004663/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4664/// the declaration into:
4665/// struct __Block_byref_ND {
4666/// void *__isa; // NULL for everything except __weak pointers
4667/// struct __Block_byref_ND *__forwarding;
4668/// int32_t __flags;
4669/// int32_t __size;
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004670/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4671/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004672/// typex ND;
4673/// };
4674///
4675/// It then replaces declaration of ND variable with:
4676/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4677/// __size=sizeof(struct __Block_byref_ND),
4678/// ND=initializer-if-any};
4679///
4680///
4681void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004682 // Insert declaration for the function in which block literal is
4683 // used.
4684 if (CurFunctionDeclToDeclareForBlock)
4685 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004686 int flag = 0;
4687 int isa = 0;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004688 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4689 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian92368a12009-12-30 20:38:08 +00004690 SourceLocation X = ND->getLocEnd();
4691 X = SM->getInstantiationLoc(X);
4692 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004693 std::string Name(ND->getNameAsString());
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004694 std::string ByrefType;
4695 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004696 ByrefType += " {\n";
4697 ByrefType += " void *__isa;\n";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004698 RewriteByRefString(ByrefType, Name, ND);
4699 ByrefType += " *__forwarding;\n";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004700 ByrefType += " int __flags;\n";
4701 ByrefType += " int __size;\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004702 // Add void *__Block_byref_id_object_copy;
4703 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004704 QualType Ty = ND->getType();
4705 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4706 if (HasCopyAndDispose) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004707 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4708 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004709 }
4710
4711 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004712 ByrefType += " " + Name + ";\n";
4713 ByrefType += "};\n";
4714 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004715 SourceLocation FunLocStart;
4716 if (CurFunctionDef)
4717 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4718 else {
4719 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4720 FunLocStart = CurMethodDef->getLocStart();
4721 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004722 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004723 if (Ty.isObjCGCWeak()) {
4724 flag |= BLOCK_FIELD_IS_WEAK;
4725 isa = 1;
4726 }
4727
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004728 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004729 flag = BLOCK_BYREF_CALLER;
4730 QualType Ty = ND->getType();
4731 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4732 if (Ty->isBlockPointerType())
4733 flag |= BLOCK_FIELD_IS_BLOCK;
4734 else
4735 flag |= BLOCK_FIELD_IS_OBJECT;
4736 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004737 if (!HF.empty())
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004738 InsertText(FunLocStart, HF);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004739 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004740
4741 // struct __Block_byref_ND ND =
4742 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4743 // initializer-if-any};
4744 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanianf7945432010-01-05 18:15:57 +00004745 unsigned flags = 0;
4746 if (HasCopyAndDispose)
4747 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004748 Name = ND->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004749 ByrefType.clear();
4750 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004751 std::string ForwardingCastType("(");
4752 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004753 if (!hasInit) {
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004754 ByrefType += " " + Name + " = {(void*)";
4755 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004756 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004757 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004758 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004759 ByrefType += "sizeof(";
4760 RewriteByRefString(ByrefType, Name, ND);
4761 ByrefType += ")";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004762 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004763 ByrefType += ", __Block_byref_id_object_copy_";
4764 ByrefType += utostr(flag);
4765 ByrefType += ", __Block_byref_id_object_dispose_";
4766 ByrefType += utostr(flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004767 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004768 ByrefType += "};\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004769 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(), ByrefType);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004770 }
4771 else {
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004772 SourceLocation startLoc;
4773 Expr *E = ND->getInit();
4774 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4775 startLoc = ECE->getLParenLoc();
4776 else
4777 startLoc = E->getLocStart();
Fariborz Jahanianb8646ed2010-01-05 23:06:29 +00004778 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004779 endBuf = SM->getCharacterData(startLoc);
4780
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004781 ByrefType += " " + Name;
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004782 ByrefType += " = {(void*)";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004783 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004784 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004785 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004786 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004787 ByrefType += "sizeof(";
4788 RewriteByRefString(ByrefType, Name, ND);
4789 ByrefType += "), ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004790 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004791 ByrefType += "__Block_byref_id_object_copy_";
4792 ByrefType += utostr(flag);
4793 ByrefType += ", __Block_byref_id_object_dispose_";
4794 ByrefType += utostr(flag);
4795 ByrefType += ", ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004796 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004797 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroff13468372009-12-23 17:24:33 +00004798
4799 // Complete the newly synthesized compound expression by inserting a right
4800 // curly brace before the end of the declaration.
4801 // FIXME: This approach avoids rewriting the initializer expression. It
4802 // also assumes there is only one declarator. For example, the following
4803 // isn't currently supported by this routine (in general):
4804 //
4805 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4806 //
4807 const char *startBuf = SM->getCharacterData(startLoc);
4808 const char *semiBuf = strchr(startBuf, ';');
4809 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4810 SourceLocation semiLoc =
4811 startLoc.getFileLocWithOffset(semiBuf-startBuf);
4812
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004813 InsertText(semiLoc, "}");
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004814 }
Fariborz Jahanian81203462009-12-22 00:48:54 +00004815 return;
4816}
4817
Mike Stump11289f42009-09-09 15:08:12 +00004818void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004819 // Add initializers for any closure decl refs.
4820 GetBlockDeclRefExprs(Exp->getBody());
4821 if (BlockDeclRefs.size()) {
4822 // Unique all "by copy" declarations.
4823 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004824 if (!BlockDeclRefs[i]->isByRef()) {
4825 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4826 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4827 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4828 }
4829 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004830 // Unique all "by ref" declarations.
4831 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4832 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004833 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4834 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4835 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4836 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004837 }
4838 // Find any imported blocks...they will need special attention.
4839 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004840 if (BlockDeclRefs[i]->isByRef() ||
4841 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4842 BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroff832d8902008-11-13 17:40:07 +00004843 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004844 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4845 }
4846 }
4847}
4848
Steve Narofff4b992a2008-10-28 20:29:00 +00004849FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4850 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004851 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump11289f42009-09-09 15:08:12 +00004852 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004853 ID, FType, 0, FunctionDecl::Extern, false,
Douglas Gregor739ef0c2009-02-25 16:33:18 +00004854 false);
Steve Narofff4b992a2008-10-28 20:29:00 +00004855}
4856
Steve Naroffd8907b72008-10-29 18:15:37 +00004857Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004858 Blocks.push_back(Exp);
4859
4860 CollectBlockDeclRefInfo(Exp);
4861 std::string FuncName;
Mike Stump11289f42009-09-09 15:08:12 +00004862
Steve Narofff4b992a2008-10-28 20:29:00 +00004863 if (CurFunctionDef)
Chris Lattnere4b95692008-11-24 03:33:13 +00004864 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004865 else if (CurMethodDef)
4866 BuildUniqueMethodName(FuncName, CurMethodDef);
4867 else if (GlobalVarDecl)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004868 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump11289f42009-09-09 15:08:12 +00004869
Steve Narofff4b992a2008-10-28 20:29:00 +00004870 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump11289f42009-09-09 15:08:12 +00004871
Steve Narofff4b992a2008-10-28 20:29:00 +00004872 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4873 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump11289f42009-09-09 15:08:12 +00004874
Steve Narofff4b992a2008-10-28 20:29:00 +00004875 // Get a pointer to the function type so we can cast appropriately.
4876 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4877
4878 FunctionDecl *FD;
4879 Expr *NewRep;
Mike Stump11289f42009-09-09 15:08:12 +00004880
Steve Narofff4b992a2008-10-28 20:29:00 +00004881 // Simulate a contructor call...
4882 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004883 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004884
Steve Narofff4b992a2008-10-28 20:29:00 +00004885 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00004886
Steve Naroffe2514232008-10-29 21:23:59 +00004887 // Initialize the block function.
Steve Narofff4b992a2008-10-28 20:29:00 +00004888 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004889 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4890 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00004891 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4892 CastExpr::CK_Unknown, Arg);
Mike Stump11289f42009-09-09 15:08:12 +00004893 InitExprs.push_back(castExpr);
4894
Steve Naroff30484702009-12-06 21:14:13 +00004895 // Initialize the block descriptor.
4896 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump11289f42009-09-09 15:08:12 +00004897
Steve Naroff30484702009-12-06 21:14:13 +00004898 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
4899 &Context->Idents.get(DescData.c_str()),
4900 Context->VoidPtrTy, 0,
4901 VarDecl::Static);
4902 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
4903 new (Context) DeclRefExpr(NewVD,
4904 Context->VoidPtrTy, SourceLocation()),
4905 UnaryOperator::AddrOf,
4906 Context->getPointerType(Context->VoidPtrTy),
4907 SourceLocation());
4908 InitExprs.push_back(DescRefExpr);
4909
Steve Narofff4b992a2008-10-28 20:29:00 +00004910 // Add initializers for any closure decl refs.
4911 if (BlockDeclRefs.size()) {
Steve Naroffe2514232008-10-29 21:23:59 +00004912 Expr *Exp;
Steve Narofff4b992a2008-10-28 20:29:00 +00004913 // Output all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004914 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004915 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004916 if (isObjCType((*I)->getType())) {
Steve Naroffe2514232008-10-29 21:23:59 +00004917 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner86d7d912008-11-24 03:54:41 +00004918 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004919 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroffa5c0db82008-12-11 21:05:33 +00004920 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004921 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004922 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
John McCall97513962010-01-15 18:39:57 +00004923 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4924 CastExpr::CK_Unknown, Arg);
Steve Narofff4b992a2008-10-28 20:29:00 +00004925 } else {
Chris Lattner86d7d912008-11-24 03:54:41 +00004926 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004927 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004928 }
Mike Stump11289f42009-09-09 15:08:12 +00004929 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004930 }
4931 // Output all "by ref" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004932 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004933 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004934 ValueDecl *ND = (*I);
4935 std::string Name(ND->getNameAsString());
4936 std::string RecName;
4937 RewriteByRefString(RecName, Name, ND);
4938 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4939 + sizeof("struct"));
4940 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
4941 SourceLocation(), II);
4942 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4943 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4944
Chris Lattner86d7d912008-11-24 03:54:41 +00004945 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004946 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4947 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004948 Context->getPointerType(Exp->getType()),
Steve Naroffe2514232008-10-29 21:23:59 +00004949 SourceLocation());
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004950 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CastExpr::CK_Unknown, Exp);
Mike Stump11289f42009-09-09 15:08:12 +00004951 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004952 }
4953 }
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00004954 if (ImportedBlockDecls.size()) {
4955 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4956 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff30484702009-12-06 21:14:13 +00004957 unsigned IntSize =
4958 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00004959 Expr *FlagExp = new (Context) IntegerLiteral(llvm::APInt(IntSize, flag),
4960 Context->IntTy, SourceLocation());
4961 InitExprs.push_back(FlagExp);
Steve Naroff30484702009-12-06 21:14:13 +00004962 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004963 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4964 FType, SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00004965 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004966 Context->getPointerType(NewRep->getType()),
Steve Narofff4b992a2008-10-28 20:29:00 +00004967 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00004968 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CastExpr::CK_Unknown,
4969 NewRep);
Steve Narofff4b992a2008-10-28 20:29:00 +00004970 BlockDeclRefs.clear();
4971 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004972 BlockByRefDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00004973 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004974 BlockByCopyDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00004975 ImportedBlockDecls.clear();
4976 return NewRep;
4977}
4978
4979//===----------------------------------------------------------------------===//
4980// Function Body / Expression rewriting
4981//===----------------------------------------------------------------------===//
4982
Steve Naroff4588d0f2008-12-04 16:24:46 +00004983// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4984// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4985// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4986// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4987// Since the rewriter isn't capable of rewriting rewritten code, it's important
4988// we get this right.
4989void RewriteObjC::CollectPropertySetters(Stmt *S) {
4990 // Perform a bottom up traversal of all children.
4991 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4992 CI != E; ++CI)
4993 if (*CI)
4994 CollectPropertySetters(*CI);
4995
4996 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4997 if (BinOp->isAssignmentOp()) {
4998 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4999 PropSetters[PRE] = BinOp;
5000 }
5001 }
5002}
5003
Steve Narofff4b992a2008-10-28 20:29:00 +00005004Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump11289f42009-09-09 15:08:12 +00005005 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00005006 isa<DoStmt>(S) || isa<ForStmt>(S))
5007 Stmts.push_back(S);
5008 else if (isa<ObjCForCollectionStmt>(S)) {
5009 Stmts.push_back(S);
Chris Lattnerb71980f2010-01-09 21:45:57 +00005010 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofff4b992a2008-10-28 20:29:00 +00005011 }
Mike Stump11289f42009-09-09 15:08:12 +00005012
Steve Narofff4b992a2008-10-28 20:29:00 +00005013 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005014
Steve Narofff4b992a2008-10-28 20:29:00 +00005015 // Perform a bottom up rewrite of all children.
5016 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5017 CI != E; ++CI)
5018 if (*CI) {
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00005019 Stmt *newStmt;
5020 Stmt *S = (*CI);
5021 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5022 Expr *OldBase = IvarRefExpr->getBase();
5023 bool replaced = false;
5024 newStmt = RewriteObjCNestedIvarRefExpr(S, replaced);
5025 if (replaced) {
5026 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
5027 ReplaceStmt(OldBase, IRE->getBase());
5028 else
5029 ReplaceStmt(S, newStmt);
5030 }
5031 }
5032 else
5033 newStmt = RewriteFunctionBodyOrGlobalInitializer(S);
Mike Stump11289f42009-09-09 15:08:12 +00005034 if (newStmt)
Steve Narofff4b992a2008-10-28 20:29:00 +00005035 *CI = newStmt;
5036 }
Mike Stump11289f42009-09-09 15:08:12 +00005037
Steve Narofff4b992a2008-10-28 20:29:00 +00005038 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
5039 // Rewrite the block body in place.
5040 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Mike Stump11289f42009-09-09 15:08:12 +00005041
Steve Narofff4b992a2008-10-28 20:29:00 +00005042 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenekdb2ef372010-01-07 18:00:35 +00005043 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroffd8907b72008-10-29 18:15:37 +00005044 RewrittenBlockExprs[BE] = Str;
Mike Stump11289f42009-09-09 15:08:12 +00005045
Steve Narofff4b992a2008-10-28 20:29:00 +00005046 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
5047 //blockTranscribed->dump();
Steve Naroffd8907b72008-10-29 18:15:37 +00005048 ReplaceStmt(S, blockTranscribed);
Steve Narofff4b992a2008-10-28 20:29:00 +00005049 return blockTranscribed;
5050 }
5051 // Handle specific things.
5052 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5053 return RewriteAtEncode(AtEncode);
Mike Stump11289f42009-09-09 15:08:12 +00005054
Steve Naroff4588d0f2008-12-04 16:24:46 +00005055 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
5056 BinaryOperator *BinOp = PropSetters[PropRefExpr];
5057 if (BinOp) {
5058 // Because the rewriter doesn't allow us to rewrite rewritten code,
5059 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroff08628db2008-12-09 12:56:34 +00005060 DisableReplaceStmt = true;
5061 // Save the source range. Even if we disable the replacement, the
5062 // rewritten node will have been inserted into the tree. If the synthesized
5063 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump11289f42009-09-09 15:08:12 +00005064 // self.errorHandler = handler ? handler :
Steve Naroff08628db2008-12-09 12:56:34 +00005065 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
5066 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroff4588d0f2008-12-04 16:24:46 +00005067 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroff08628db2008-12-09 12:56:34 +00005068 DisableReplaceStmt = false;
Steve Naroff22216db2008-12-04 23:50:32 +00005069 //
5070 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
5071 // we changed the RHS of BinOp, the rewriter would fail (since it needs
5072 // to see the original expression). Consider this example:
5073 //
5074 // Foo *obj1, *obj2;
5075 //
5076 // obj1.i = [obj2 rrrr];
5077 //
5078 // 'BinOp' for the previous expression looks like:
5079 //
5080 // (BinaryOperator 0x231ccf0 'int' '='
5081 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
5082 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
5083 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
5084 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
5085 //
5086 // 'newStmt' represents the rewritten message expression. For example:
5087 //
5088 // (CallExpr 0x231d300 'id':'struct objc_object *'
5089 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
5090 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
5091 // (CStyleCastExpr 0x231d220 'void *'
5092 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
5093 //
5094 // Note that 'newStmt' is passed to RewritePropertySetter so that it
5095 // can be used as the setter argument. ReplaceStmt() will still 'see'
5096 // the original RHS (since we haven't altered BinOp).
5097 //
Mike Stump11289f42009-09-09 15:08:12 +00005098 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff22216db2008-12-04 23:50:32 +00005099 // node. As a result, we now leak the original AST nodes.
5100 //
Steve Naroff08628db2008-12-09 12:56:34 +00005101 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroff4588d0f2008-12-04 16:24:46 +00005102 } else {
5103 return RewritePropertyGetter(PropRefExpr);
Steve Narofff326f402008-12-03 00:56:33 +00005104 }
5105 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005106 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5107 return RewriteAtSelector(AtSelector);
Mike Stump11289f42009-09-09 15:08:12 +00005108
Steve Narofff4b992a2008-10-28 20:29:00 +00005109 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5110 return RewriteObjCStringLiteral(AtString);
Mike Stump11289f42009-09-09 15:08:12 +00005111
Steve Narofff4b992a2008-10-28 20:29:00 +00005112 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00005113#if 0
Steve Narofff4b992a2008-10-28 20:29:00 +00005114 // Before we rewrite it, put the original message expression in a comment.
5115 SourceLocation startLoc = MessExpr->getLocStart();
5116 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00005117
Steve Narofff4b992a2008-10-28 20:29:00 +00005118 const char *startBuf = SM->getCharacterData(startLoc);
5119 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump11289f42009-09-09 15:08:12 +00005120
Steve Narofff4b992a2008-10-28 20:29:00 +00005121 std::string messString;
5122 messString += "// ";
5123 messString.append(startBuf, endBuf-startBuf+1);
5124 messString += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00005125
5126 // FIXME: Missing definition of
Steve Narofff4b992a2008-10-28 20:29:00 +00005127 // InsertText(clang::SourceLocation, char const*, unsigned int).
5128 // InsertText(startLoc, messString.c_str(), messString.size());
5129 // Tried this, but it didn't work either...
5130 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff4588d0f2008-12-04 16:24:46 +00005131#endif
Steve Narofff4b992a2008-10-28 20:29:00 +00005132 return RewriteMessageExpr(MessExpr);
5133 }
Mike Stump11289f42009-09-09 15:08:12 +00005134
Steve Narofff4b992a2008-10-28 20:29:00 +00005135 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5136 return RewriteObjCTryStmt(StmtTry);
5137
5138 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5139 return RewriteObjCSynchronizedStmt(StmtTry);
5140
5141 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5142 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump11289f42009-09-09 15:08:12 +00005143
Steve Narofff4b992a2008-10-28 20:29:00 +00005144 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5145 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump11289f42009-09-09 15:08:12 +00005146
5147 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofff4b992a2008-10-28 20:29:00 +00005148 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump11289f42009-09-09 15:08:12 +00005149 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofff4b992a2008-10-28 20:29:00 +00005150 OrigStmtRange.getEnd());
5151 if (BreakStmt *StmtBreakStmt =
5152 dyn_cast<BreakStmt>(S))
5153 return RewriteBreakStmt(StmtBreakStmt);
5154 if (ContinueStmt *StmtContinueStmt =
5155 dyn_cast<ContinueStmt>(S))
5156 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump11289f42009-09-09 15:08:12 +00005157
5158 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofff4b992a2008-10-28 20:29:00 +00005159 // and cast exprs.
5160 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5161 // FIXME: What we're doing here is modifying the type-specifier that
5162 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump11289f42009-09-09 15:08:12 +00005163 // a separate type-specifier that we can rewrite.
Steve Naroffe70a52a2009-12-05 15:55:59 +00005164 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5165 // the context of an ObjCForCollectionStmt. For example:
5166 // NSArray *someArray;
5167 // for (id <FooProtocol> index in someArray) ;
5168 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5169 // and it depends on the original text locations/positions.
Benjamin Krameracc5fa12009-12-05 22:16:51 +00005170 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroffe70a52a2009-12-05 15:55:59 +00005171 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump11289f42009-09-09 15:08:12 +00005172
Steve Narofff4b992a2008-10-28 20:29:00 +00005173 // Blocks rewrite rules.
5174 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5175 DI != DE; ++DI) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +00005176 Decl *SD = *DI;
Steve Narofff4b992a2008-10-28 20:29:00 +00005177 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005178 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005179 RewriteBlockPointerDecl(ND);
Mike Stump11289f42009-09-09 15:08:12 +00005180 else if (ND->getType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005181 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00005182 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005183 if (VD->hasAttr<BlocksAttr>()) {
5184 static unsigned uniqueByrefDeclCount = 0;
5185 assert(!BlockByRefDeclNo.count(ND) &&
5186 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5187 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005188 RewriteByRefVar(VD);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005189 }
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00005190 else
5191 RewriteTypeOfDecl(VD);
5192 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005193 }
5194 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005195 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005196 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005197 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005198 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5199 }
5200 }
5201 }
Mike Stump11289f42009-09-09 15:08:12 +00005202
Steve Narofff4b992a2008-10-28 20:29:00 +00005203 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5204 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump11289f42009-09-09 15:08:12 +00005205
5206 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00005207 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5208 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump11289f42009-09-09 15:08:12 +00005209 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5210 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005211 && "Statement stack mismatch");
5212 Stmts.pop_back();
5213 }
5214 // Handle blocks rewriting.
5215 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5216 if (BDRE->isByRef())
Steve Naroffd9803712009-04-29 16:37:50 +00005217 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofff4b992a2008-10-28 20:29:00 +00005218 }
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005219 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5220 ValueDecl *VD = DRE->getDecl();
5221 if (VD->hasAttr<BlocksAttr>())
5222 return RewriteBlockDeclRefExpr(DRE);
5223 }
5224
Steve Narofff4b992a2008-10-28 20:29:00 +00005225 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff350b6652008-10-30 10:07:53 +00005226 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00005227 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00005228 ReplaceStmt(S, BlockCall);
5229 return BlockCall;
5230 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005231 }
Steve Naroffc989a7b2008-11-03 23:29:32 +00005232 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005233 RewriteCastExpr(CE);
5234 }
5235#if 0
5236 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek5a201952009-02-07 01:47:29 +00005237 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00005238 // Get the new text.
5239 std::string SStr;
5240 llvm::raw_string_ostream Buf(SStr);
Eli Friedman0905f142009-05-30 05:19:26 +00005241 Replacement->printPretty(Buf, *Context);
Steve Narofff4b992a2008-10-28 20:29:00 +00005242 const std::string &Str = Buf.str();
5243
5244 printf("CAST = %s\n", &Str[0]);
5245 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5246 delete S;
5247 return Replacement;
5248 }
5249#endif
5250 // Return this stmt unmodified.
5251 return S;
5252}
5253
Steve Naroffe70a52a2009-12-05 15:55:59 +00005254void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5255 for (RecordDecl::field_iterator i = RD->field_begin(),
5256 e = RD->field_end(); i != e; ++i) {
5257 FieldDecl *FD = *i;
5258 if (isTopLevelBlockPointerType(FD->getType()))
5259 RewriteBlockPointerDecl(FD);
5260 if (FD->getType()->isObjCQualifiedIdType() ||
5261 FD->getType()->isObjCQualifiedInterfaceType())
5262 RewriteObjCQualifiedInterfaceTypes(FD);
5263 }
5264}
5265
Steve Narofff4b992a2008-10-28 20:29:00 +00005266/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5267/// main file of the input.
5268void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5269 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffb1368882008-12-17 00:20:22 +00005270 if (FD->isOverloadedOperator())
5271 return;
Mike Stump11289f42009-09-09 15:08:12 +00005272
Steve Narofff4b992a2008-10-28 20:29:00 +00005273 // Since function prototypes don't have ParmDecl's, we check the function
5274 // prototype. This enables us to rewrite function declarations and
5275 // definitions using the same code.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005276 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005277
Sebastian Redla7b98a72009-04-26 20:35:05 +00005278 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005279 if (CompoundStmt *Body = FD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005280 CurFunctionDef = FD;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005281 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005282 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005283 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005284 Body =
5285 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5286 FD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005287 CurrentBody = 0;
5288 if (PropParentMap) {
5289 delete PropParentMap;
5290 PropParentMap = 0;
5291 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005292 // This synthesizes and inserts the block "impl" struct, invoke function,
5293 // and any copy/dispose helper functions.
5294 InsertBlockLiteralsWithinFunction(FD);
5295 CurFunctionDef = 0;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005296 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005297 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005298 return;
5299 }
5300 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005301 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005302 CurMethodDef = MD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005303 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005304 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005305 Body =
5306 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5307 MD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005308 CurrentBody = 0;
5309 if (PropParentMap) {
5310 delete PropParentMap;
5311 PropParentMap = 0;
5312 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005313 InsertBlockLiteralsWithinMethod(MD);
5314 CurMethodDef = 0;
5315 }
5316 }
5317 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5318 ClassImplementation.push_back(CI);
5319 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5320 CategoryImplementation.push_back(CI);
5321 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5322 RewriteForwardClassDecl(CD);
5323 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5324 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroffa5c0db82008-12-11 21:05:33 +00005325 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005326 RewriteBlockPointerDecl(VD);
Steve Naroffd8907b72008-10-29 18:15:37 +00005327 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005328 CheckFunctionPointerDecl(VD->getType(), VD);
5329 if (VD->getInit()) {
Steve Naroffc989a7b2008-11-03 23:29:32 +00005330 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005331 RewriteCastExpr(CE);
5332 }
5333 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00005334 } else if (VD->getType()->isRecordType()) {
5335 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5336 if (RD->isDefinition())
5337 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005338 }
Steve Naroffd8907b72008-10-29 18:15:37 +00005339 if (VD->getInit()) {
5340 GlobalVarDecl = VD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005341 CollectPropertySetters(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005342 CurrentBody = VD->getInit();
Steve Naroffd8907b72008-10-29 18:15:37 +00005343 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005344 CurrentBody = 0;
5345 if (PropParentMap) {
5346 delete PropParentMap;
5347 PropParentMap = 0;
5348 }
Mike Stump11289f42009-09-09 15:08:12 +00005349 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner86d7d912008-11-24 03:54:41 +00005350 VD->getNameAsCString());
Steve Naroffd8907b72008-10-29 18:15:37 +00005351 GlobalVarDecl = 0;
5352
5353 // This is needed for blocks.
Steve Naroffc989a7b2008-11-03 23:29:32 +00005354 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroffd8907b72008-10-29 18:15:37 +00005355 RewriteCastExpr(CE);
5356 }
5357 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005358 return;
5359 }
5360 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005361 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005362 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005363 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005364 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5365 return;
5366 }
5367 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroffe70a52a2009-12-05 15:55:59 +00005368 if (RD->isDefinition())
5369 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005370 return;
5371 }
5372 // Nothing yet.
5373}
5374
Chris Lattnercf169832009-03-28 04:11:33 +00005375void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005376 if (Diags.hasErrorOccurred())
5377 return;
Mike Stump11289f42009-09-09 15:08:12 +00005378
Steve Narofff4b992a2008-10-28 20:29:00 +00005379 RewriteInclude();
Mike Stump11289f42009-09-09 15:08:12 +00005380
Steve Naroffd9803712009-04-29 16:37:50 +00005381 // Here's a great place to add any extra declarations that may be needed.
5382 // Write out meta data for each @protocol(<expr>).
Mike Stump11289f42009-09-09 15:08:12 +00005383 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00005384 E = ProtocolExprDecls.end(); I != E; ++I)
5385 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5386
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005387 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005388 if (ClassImplementation.size() || CategoryImplementation.size())
5389 RewriteImplementations();
Steve Naroffd9803712009-04-29 16:37:50 +00005390
Steve Narofff4b992a2008-10-28 20:29:00 +00005391 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5392 // we are done.
Mike Stump11289f42009-09-09 15:08:12 +00005393 if (const RewriteBuffer *RewriteBuf =
Steve Narofff4b992a2008-10-28 20:29:00 +00005394 Rewrite.getRewriteBufferFor(MainFileID)) {
5395 //printf("Changed:\n");
5396 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5397 } else {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005398 llvm::errs() << "No changes\n";
Steve Narofff4b992a2008-10-28 20:29:00 +00005399 }
Steve Narofff8cfd162008-11-13 20:07:04 +00005400
Steve Naroffd9803712009-04-29 16:37:50 +00005401 if (ClassImplementation.size() || CategoryImplementation.size() ||
5402 ProtocolExprDecls.size()) {
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005403 // Rewrite Objective-c meta data*
5404 std::string ResultStr;
5405 SynthesizeMetaDataIntoBuffer(ResultStr);
5406 // Emit metadata.
5407 *OutFile << ResultStr;
5408 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005409 OutFile->flush();
5410}
5411