blob: 8d5f4992aea827d80f7e5b37998da60ab793d605 [file] [log] [blame]
Steve Naroff44e81222008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattnerb429ae42007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-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 Lattnerb429ae42007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Eli Friedman22a4efd2009-05-18 22:50:54 +000014#include "clang/Frontend/ASTConsumers.h"
Chris Lattner569faa62007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattnerb429ae42007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Steve Narofffbed6802008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.h"
Chris Lattner569faa62007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffe9780582007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner4478db92007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattnerae43eb72007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Benjamin Kramer2ec17292009-08-23 12:08:50 +000023#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000025#include "llvm/ADT/StringExtras.h"
Fariborz Jahanianf185aef2007-10-26 19:46:17 +000026#include "llvm/ADT/SmallPtrSet.h"
Ted Kremenek7b6f67b2008-09-13 05:16:45 +000027#include "llvm/ADT/OwningPtr.h"
Chris Lattnerb429ae42007-10-11 00:43:27 +000028using namespace clang;
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000029using llvm::utostr;
Chris Lattnerb429ae42007-10-11 00:43:27 +000030
Chris Lattnerb429ae42007-10-11 00:43:27 +000031namespace {
Steve Naroff44e81222008-04-14 22:03:09 +000032 class RewriteObjC : public ASTConsumer {
Chris Lattner74db1682007-10-16 21:07:07 +000033 Rewriter Rewrite;
Chris Lattner258f26c2007-11-30 22:25:36 +000034 Diagnostic &Diags;
Steve Naroff7fd0aff2008-03-10 20:43:59 +000035 const LangOptions &LangOpts;
Steve Naroff53b6f4c2008-01-30 19:17:43 +000036 unsigned RewriteFailedDiag;
Steve Naroff43964fb2008-12-05 17:03:39 +000037 unsigned TryFinallyContainsReturnDiag;
38
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000039 ASTContext *Context;
Chris Lattnerb429ae42007-10-11 00:43:27 +000040 SourceManager *SM;
Argiris Kirtzidisd3586002008-04-17 14:40:12 +000041 TranslationUnitDecl *TUDecl;
Chris Lattnerf4f776a2009-01-17 06:22:33 +000042 FileID MainFileID;
Chris Lattnerae43eb72007-12-02 01:13:47 +000043 const char *MainFileStart, *MainFileEnd;
Chris Lattner74db1682007-10-16 21:07:07 +000044 SourceLocation LastIncLoc;
Steve Narofffef037c2008-03-27 22:29:16 +000045
Ted Kremenek42730c52008-01-07 19:49:32 +000046 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
47 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
48 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Naroff04eaa192008-05-06 18:26:51 +000049 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremenek42730c52008-01-07 19:49:32 +000050 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
51 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian13dad332008-01-15 23:58:23 +000052 llvm::SmallVector<Stmt *, 32> Stmts;
53 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroff450d2fc2009-04-29 16:37:50 +000054 // Remember all the @protocol(<expr>) expressions.
55 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Steve Naroffe9780582007-10-23 23:50:29 +000056
Steve Naroff47e7fa22008-03-15 00:55:56 +000057 unsigned NumObjCStringLiterals;
58
Steve Naroffe9780582007-10-23 23:50:29 +000059 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000060 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000061 FunctionDecl *MsgSendStretFunctionDecl;
62 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +000063 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffe9780582007-10-23 23:50:29 +000064 FunctionDecl *GetClassFunctionDecl;
Steve Naroff3b1caac2007-12-07 03:50:46 +000065 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff71226032007-10-24 22:48:43 +000066 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroffabb96362007-11-08 14:30:50 +000067 FunctionDecl *CFStringFunctionDecl;
Steve Naroffbec4bf52008-03-11 17:37:02 +000068 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000069
Steve Naroff0add5d22007-11-03 11:27:19 +000070 // ObjC string constant support.
Steve Naroff72a6ebc2008-04-15 22:42:06 +000071 VarDecl *ConstantStringClassReference;
Steve Naroff0add5d22007-11-03 11:27:19 +000072 RecordDecl *NSStringRecord;
Steve Naroff0744c472007-11-04 22:37:50 +000073
Fariborz Jahanian22277422008-01-16 00:09:11 +000074 // ObjC foreach break/continue generation support.
Fariborz Jahanian13dad332008-01-15 23:58:23 +000075 int BcLabelCount;
76
Steve Naroff764c1ae2007-11-15 10:28:18 +000077 // Needed for super.
Steve Naroff38a9e3f2008-10-27 17:20:55 +000078 ObjCMethodDecl *CurMethodDef;
Steve Naroff764c1ae2007-11-15 10:28:18 +000079 RecordDecl *SuperStructDecl;
Steve Naroff47e7fa22008-03-15 00:55:56 +000080 RecordDecl *ConstantStringDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000081
Steve Naroff450d2fc2009-04-29 16:37:50 +000082 TypeDecl *ProtocolTypeDecl;
83 QualType getProtocolType();
84
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +000085 // Needed for header files being rewritten
86 bool IsHeader;
87
Steve Naroffcfd9f4c2008-03-28 22:26:09 +000088 std::string InFileName;
Eli Friedmana9c310842009-05-18 22:20:00 +000089 llvm::raw_ostream* OutFile;
Eli Friedman35ba7a62009-05-18 22:39:16 +000090
91 bool SilenceRewriteMacroWarning;
92
Steve Narofffef037c2008-03-27 22:29:16 +000093 std::string Preamble;
Steve Naroff38a9e3f2008-10-27 17:20:55 +000094
95 // Block expressions.
96 llvm::SmallVector<BlockExpr *, 32> Blocks;
97 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
98 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Steve Narofffef037c2008-03-27 22:29:16 +000099
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000100 // Block related declarations.
101 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
102 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
103 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
104
105 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
106
Steve Naroff0e948412008-12-04 16:24:46 +0000107 // This maps a property to it's assignment statement.
108 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Narofffbed6802008-12-08 16:43:47 +0000109 // This maps a property to it's synthesied message expression.
110 // This allows us to rewrite chained getters (e.g. o.a.b.c).
111 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
112
Steve Naroff102c3f22008-12-04 23:50:32 +0000113 // This maps an original source AST to it's rewritten form. This allows
114 // us to avoid rewriting the same node twice (which is very uncommon).
115 // This is needed to support some of the exotic property rewriting.
116 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Narofff6ce8a12008-12-03 00:56:33 +0000117
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000118 FunctionDecl *CurFunctionDef;
Steve Naroff80c54752008-10-29 18:15:37 +0000119 VarDecl *GlobalVarDecl;
120
Steve Naroffedb4bc92008-12-09 12:56:34 +0000121 bool DisableReplaceStmt;
122
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000123 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnerb429ae42007-10-11 00:43:27 +0000124 public:
Ted Kremenek79b50cb2008-05-31 20:11:04 +0000125 virtual void Initialize(ASTContext &context);
126
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000127 // Top Level Driver code.
Chris Lattnera17991f2009-03-29 16:50:03 +0000128 virtual void HandleTopLevelDecl(DeclGroupRef D) {
129 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
130 HandleTopLevelSingleDecl(*I);
131 }
132 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner74db1682007-10-16 21:07:07 +0000133 void HandleDeclInMainFile(Decl *D);
Eli Friedmana9c310842009-05-18 22:20:00 +0000134 RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
Eli Friedman35ba7a62009-05-18 22:39:16 +0000135 Diagnostic &D, const LangOptions &LOpts,
136 bool silenceMacroWarn);
Ted Kremenekcab0b0c2008-08-08 04:15:52 +0000137
138 ~RewriteObjC() {}
139
Chris Lattner2a594d02009-03-28 04:11:33 +0000140 virtual void HandleTranslationUnit(ASTContext &C);
Chris Lattnerb1548372008-01-31 19:37:57 +0000141
142 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff102c3f22008-12-04 23:50:32 +0000143 Stmt *ReplacingStmt = ReplacedNodes[Old];
144
145 if (ReplacingStmt)
146 return; // We can't rewrite the same node twice.
Chris Lattnerb1548372008-01-31 19:37:57 +0000147
Steve Naroffedb4bc92008-12-09 12:56:34 +0000148 if (DisableReplaceStmt)
149 return; // Used when rewriting the assignment of a property setter.
150
Steve Naroff102c3f22008-12-04 23:50:32 +0000151 // If replacement succeeded or warning disabled return with no warning.
152 if (!Rewrite.ReplaceStmt(Old, New)) {
153 ReplacedNodes[Old] = New;
154 return;
155 }
156 if (SilenceRewriteMacroWarning)
157 return;
Chris Lattner6948ae62008-11-18 07:04:44 +0000158 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
159 << Old->getSourceRange();
Chris Lattnerb1548372008-01-31 19:37:57 +0000160 }
Steve Naroffedb4bc92008-12-09 12:56:34 +0000161
162 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
163 // Measaure the old text.
164 int Size = Rewrite.getRangeSize(SrcRange);
165 if (Size == -1) {
166 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
167 << Old->getSourceRange();
168 return;
169 }
170 // Get the new text.
171 std::string SStr;
172 llvm::raw_string_ostream S(SStr);
Chris Lattner7099c782009-06-30 01:26:17 +0000173 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroffedb4bc92008-12-09 12:56:34 +0000174 const std::string &Str = S.str();
175
176 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbar60987c92009-08-19 19:10:30 +0000177 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroffedb4bc92008-12-09 12:56:34 +0000178 ReplacedNodes[Old] = New;
179 return;
180 }
181 if (SilenceRewriteMacroWarning)
182 return;
183 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
184 << Old->getSourceRange();
185 }
186
Steve Narofffef037c2008-03-27 22:29:16 +0000187 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
188 bool InsertAfter = true) {
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000189 // If insertion succeeded or warning disabled return with no warning.
Daniel Dunbar60987c92009-08-19 19:10:30 +0000190 if (!Rewrite.InsertText(Loc, llvm::StringRef(StrData, StrLen),
191 InsertAfter) ||
Chris Lattner6216f292008-01-31 19:42:41 +0000192 SilenceRewriteMacroWarning)
193 return;
194
195 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
196 }
Chris Lattnerb1548372008-01-31 19:37:57 +0000197
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000198 void RemoveText(SourceLocation Loc, unsigned StrLen) {
199 // If removal succeeded or warning disabled return with no warning.
200 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
201 return;
202
203 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
204 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000205
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000206 void ReplaceText(SourceLocation Start, unsigned OrigLength,
207 const char *NewStr, unsigned NewLength) {
208 // If removal succeeded or warning disabled return with no warning.
Daniel Dunbar60987c92009-08-19 19:10:30 +0000209 if (!Rewrite.ReplaceText(Start, OrigLength,
210 llvm::StringRef(NewStr, NewLength)) ||
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000211 SilenceRewriteMacroWarning)
212 return;
213
214 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
215 }
216
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000217 // Syntactic Rewriting.
Steve Naroff0744c472007-11-04 22:37:50 +0000218 void RewritePrologue(SourceLocation Loc);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000219 void RewriteInclude();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000220 void RewriteTabs();
Ted Kremenek42730c52008-01-07 19:49:32 +0000221 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffea6610f2008-12-02 17:36:43 +0000222 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
223 ObjCImplementationDecl *IMD,
224 ObjCCategoryImplDecl *CID);
Ted Kremenek42730c52008-01-07 19:49:32 +0000225 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000226 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremenek42730c52008-01-07 19:49:32 +0000227 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
228 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
229 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
230 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
231 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff56af2002009-01-11 01:06:09 +0000232 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000233 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000234 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffd06c88d2008-07-29 18:15:38 +0000235 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffc8a92d12007-11-01 13:24:47 +0000236 bool needToScanForQualifiers(QualType T);
Ted Kremenek42730c52008-01-07 19:49:32 +0000237 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff764c1ae2007-11-15 10:28:18 +0000238 QualType getSuperStructType();
Steve Naroff47e7fa22008-03-15 00:55:56 +0000239 QualType getConstantStringStructType();
Steve Naroffef82b742008-05-31 14:15:04 +0000240 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Chris Lattner6fe8b272007-10-16 22:36:42 +0000241
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000242 // Expression Rewriting.
Steve Naroff334fbc22007-11-09 15:20:18 +0000243 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroff0e948412008-12-04 16:24:46 +0000244 void CollectPropertySetters(Stmt *S);
245
Steve Narofffbed6802008-12-08 16:43:47 +0000246 Stmt *CurrentBody;
247 ParentMap *PropParentMap; // created lazily.
248
Chris Lattner0021f452007-10-24 16:57:36 +0000249 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner343c82b2008-05-23 20:40:52 +0000250 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroff0e948412008-12-04 16:24:46 +0000251 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Steve Naroffedb4bc92008-12-09 12:56:34 +0000252 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
253 SourceRange SrcRange);
Steve Naroff296b74f2007-11-05 14:50:49 +0000254 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner0021f452007-10-24 16:57:36 +0000255 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroff0add5d22007-11-03 11:27:19 +0000256 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000257 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroff43964fb2008-12-05 17:03:39 +0000258 void WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S);
Ted Kremenek42730c52008-01-07 19:49:32 +0000259 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian499bf412008-01-29 22:59:37 +0000260 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek42730c52008-01-07 19:49:32 +0000261 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
262 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
263 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner2c022162008-01-31 05:10:40 +0000264 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
265 SourceLocation OrigEnd);
Steve Naroff71226032007-10-24 22:48:43 +0000266 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
267 Expr **args, unsigned nargs);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000268 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000269 Stmt *RewriteBreakStmt(BreakStmt *S);
270 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000271 void SynthCountByEnumWithState(std::string &buf);
272
Steve Naroff02a82aa2007-10-30 23:14:51 +0000273 void SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +0000274 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000275 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +0000276 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000277 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +0000278 void SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +0000279 void SynthGetMetaClassFunctionDecl();
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +0000280 void SynthSelGetUidFunctionDecl();
Steve Naroffbec4bf52008-03-11 17:37:02 +0000281 void SynthSuperContructorFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000282
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000283 // Metadata emission.
Ted Kremenek42730c52008-01-07 19:49:32 +0000284 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000285 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000286
Ted Kremenek42730c52008-01-07 19:49:32 +0000287 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000288 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000289
Douglas Gregorcd19b572009-04-23 01:02:12 +0000290 template<typename MethodIterator>
291 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
292 MethodIterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +0000293 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000294 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +0000295 const char *ClassName,
296 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000297
Steve Naroff450d2fc2009-04-29 16:37:50 +0000298 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
299 const char *prefix,
300 const char *ClassName,
301 std::string &Result);
302 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
303 const char *prefix,
304 const char *ClassName,
305 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000306 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000307 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000308 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
309 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000310 std::string &Result);
Steve Naroff21658f62008-11-13 20:07:04 +0000311 void RewriteImplementations();
312 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000313
314 // Block rewriting.
Douglas Gregor4fa58902009-02-26 23:50:07 +0000315 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000316 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
317
318 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
319 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
320
Steve Naroff80c54752008-10-29 18:15:37 +0000321 // Block specific rewrite rules.
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000322 void RewriteBlockCall(CallExpr *Exp);
323 void RewriteBlockPointerDecl(NamedDecl *VD);
Steve Naroff450d2fc2009-04-29 16:37:50 +0000324 Stmt *RewriteBlockDeclRefExpr(BlockDeclRefExpr *VD);
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000325 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
326
327 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
328 const char *funcName, std::string Tag);
329 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
330 const char *funcName, std::string Tag);
331 std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
332 bool hasCopyDisposeHelpers);
Steve Naroff85eb17b2008-10-30 10:07:53 +0000333 Stmt *SynthesizeBlockCall(CallExpr *Exp);
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000334 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
335 const char *FunName);
336
337 void CollectBlockDeclRefInfo(BlockExpr *Exp);
338 void GetBlockCallExprs(Stmt *S);
339 void GetBlockDeclRefExprs(Stmt *S);
340
341 // We avoid calling Type::isBlockPointerType(), since it operates on the
342 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek0c97e042009-02-07 01:47:29 +0000343 bool isTopLevelBlockPointerType(QualType T) {
344 return isa<BlockPointerType>(T);
345 }
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000346
347 // FIXME: This predicate seems like it would be useful to add to ASTContext.
348 bool isObjCType(QualType T) {
349 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
350 return false;
351
352 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
353
354 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
355 OCT == Context->getCanonicalType(Context->getObjCClassType()))
356 return true;
357
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000358 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000359 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffc75c1a82009-06-17 22:40:22 +0000360 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000361 return true;
362 }
363 return false;
364 }
365 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek0c97e042009-02-07 01:47:29 +0000366 void GetExtentOfArgList(const char *Name, const char *&LParen,
367 const char *&RParen);
Steve Naroff7f1412d2008-11-03 23:29:32 +0000368 void RewriteCastExpr(CStyleCastExpr *CE);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +0000369
370 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroff80c54752008-10-29 18:15:37 +0000371 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Steve Naroff450d2fc2009-04-29 16:37:50 +0000372
373 void QuoteDoublequotes(std::string &From, std::string &To) {
374 for(unsigned i = 0; i < From.length(); i++) {
375 if (From[i] == '"')
376 To += "\\\"";
377 else
378 To += From[i];
379 }
380 }
Chris Lattnerb429ae42007-10-11 00:43:27 +0000381 };
382}
383
Douglas Gregor4fa58902009-02-26 23:50:07 +0000384void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000385 NamedDecl *D) {
Douglas Gregor4fa58902009-02-26 23:50:07 +0000386 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
387 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000388 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroffd896f4b2008-12-11 21:05:33 +0000389 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000390 // All the args are checked/rewritten. Don't call twice!
391 RewriteBlockPointerDecl(D);
392 break;
393 }
394 }
395}
396
397void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000398 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000399 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor4fa58902009-02-26 23:50:07 +0000400 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000401}
402
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +0000403static bool IsHeaderFile(const std::string &Filename) {
404 std::string::size_type DotPos = Filename.rfind('.');
405
406 if (DotPos == std::string::npos) {
407 // no file extension
408 return false;
409 }
410
411 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
412 // C header: .h
413 // C++ header: .hh or .H;
414 return Ext == "h" || Ext == "hh" || Ext == "H";
415}
416
Eli Friedmana9c310842009-05-18 22:20:00 +0000417RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedman35ba7a62009-05-18 22:39:16 +0000418 Diagnostic &D, const LangOptions &LOpts,
419 bool silenceMacroWarn)
420 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
421 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000422 IsHeader = IsHeaderFile(inFile);
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000423 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
424 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff43964fb2008-12-05 17:03:39 +0000425 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek0c97e042009-02-07 01:47:29 +0000426 "rewriter doesn't support user-specified control flow semantics "
427 "for @try/@finally (code may not execute properly)");
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000428}
429
Eli Friedman848763f2009-05-18 22:29:17 +0000430ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
431 llvm::raw_ostream* OS,
432 Diagnostic &Diags,
Eli Friedman35ba7a62009-05-18 22:39:16 +0000433 const LangOptions &LOpts,
434 bool SilenceRewriteMacroWarning) {
435 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattner258f26c2007-11-30 22:25:36 +0000436}
Chris Lattnerb429ae42007-10-11 00:43:27 +0000437
Steve Naroff44e81222008-04-14 22:03:09 +0000438void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner12499682008-01-31 19:38:44 +0000439 Context = &context;
440 SM = &Context->getSourceManager();
Argiris Kirtzidisd3586002008-04-17 14:40:12 +0000441 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner12499682008-01-31 19:38:44 +0000442 MsgSendFunctionDecl = 0;
443 MsgSendSuperFunctionDecl = 0;
444 MsgSendStretFunctionDecl = 0;
445 MsgSendSuperStretFunctionDecl = 0;
446 MsgSendFpretFunctionDecl = 0;
447 GetClassFunctionDecl = 0;
448 GetMetaClassFunctionDecl = 0;
449 SelGetUidFunctionDecl = 0;
450 CFStringFunctionDecl = 0;
Chris Lattner12499682008-01-31 19:38:44 +0000451 ConstantStringClassReference = 0;
452 NSStringRecord = 0;
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000453 CurMethodDef = 0;
454 CurFunctionDef = 0;
Steve Naroffedb4bc92008-12-09 12:56:34 +0000455 GlobalVarDecl = 0;
Chris Lattner12499682008-01-31 19:38:44 +0000456 SuperStructDecl = 0;
Steve Naroff450d2fc2009-04-29 16:37:50 +0000457 ProtocolTypeDecl = 0;
Steve Naroff053ae3f2008-03-27 22:59:54 +0000458 ConstantStringDecl = 0;
Chris Lattner12499682008-01-31 19:38:44 +0000459 BcLabelCount = 0;
Steve Naroffbec4bf52008-03-11 17:37:02 +0000460 SuperContructorFunctionDecl = 0;
Steve Naroff47e7fa22008-03-15 00:55:56 +0000461 NumObjCStringLiterals = 0;
Steve Naroffbad6f3b2008-12-08 20:01:41 +0000462 PropParentMap = 0;
463 CurrentBody = 0;
Steve Naroffedb4bc92008-12-09 12:56:34 +0000464 DisableReplaceStmt = false;
465
Chris Lattner12499682008-01-31 19:38:44 +0000466 // Get the ID and start/end of the main file.
467 MainFileID = SM->getMainFileID();
468 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
469 MainFileStart = MainBuf->getBufferStart();
470 MainFileEnd = MainBuf->getBufferEnd();
Steve Narofffef037c2008-03-27 22:29:16 +0000471
Chris Lattnere1be6022009-04-14 23:22:57 +0000472 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Steve Naroffde0da102008-03-10 23:16:54 +0000473
Chris Lattner12499682008-01-31 19:38:44 +0000474 // declaring objc_selector outside the parameter list removes a silly
475 // scope related warning...
Steve Narofffef037c2008-03-27 22:29:16 +0000476 if (IsHeader)
Steve Naroff08299f82009-02-03 20:39:18 +0000477 Preamble = "#pragma once\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000478 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff12673622008-12-23 20:11:22 +0000479 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Narofffef037c2008-03-27 22:29:16 +0000480 Preamble += "struct objc_object *superClass; ";
Steve Naroffbec4bf52008-03-11 17:37:02 +0000481 if (LangOpts.Microsoft) {
482 // Add a constructor for creating temporary objects.
Ted Kremenek0c97e042009-02-07 01:47:29 +0000483 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
484 ": ";
Steve Narofffef037c2008-03-27 22:29:16 +0000485 Preamble += "object(o), superClass(s) {} ";
Steve Naroffbec4bf52008-03-11 17:37:02 +0000486 }
Steve Narofffef037c2008-03-27 22:29:16 +0000487 Preamble += "};\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000488 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
489 Preamble += "typedef struct objc_object Protocol;\n";
490 Preamble += "#define _REWRITER_typedef_Protocol\n";
491 Preamble += "#endif\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000492 if (LangOpts.Microsoft) {
493 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
494 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
495 } else
496 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
497 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Narofffef037c2008-03-27 22:29:16 +0000498 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000499 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Narofffef037c2008-03-27 22:29:16 +0000500 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000501 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Narofffef037c2008-03-27 22:29:16 +0000502 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000503 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Narofffef037c2008-03-27 22:29:16 +0000504 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000505 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Narofffef037c2008-03-27 22:29:16 +0000506 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000507 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Narofffef037c2008-03-27 22:29:16 +0000508 Preamble += "(const char *);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000509 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Narofffef037c2008-03-27 22:29:16 +0000510 Preamble += "(const char *);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000511 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
512 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
513 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
514 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
515 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff3e2c98c2008-05-09 21:17:56 +0000516 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroffcd25d782008-07-16 18:58:11 +0000517 // @synchronized hooks.
Steve Naroff1b208d72008-12-08 17:30:33 +0000518 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
519 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
520 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000521 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
522 Preamble += "struct __objcFastEnumerationState {\n\t";
523 Preamble += "unsigned long state;\n\t";
Steve Naroffc960e9d2008-04-04 22:58:22 +0000524 Preamble += "void **itemsPtr;\n\t";
Steve Narofffef037c2008-03-27 22:29:16 +0000525 Preamble += "unsigned long *mutationsPtr;\n\t";
526 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000527 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000528 Preamble += "#define __FASTENUMERATIONSTATE\n";
529 Preamble += "#endif\n";
530 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
531 Preamble += "struct __NSConstantStringImpl {\n";
532 Preamble += " int *isa;\n";
533 Preamble += " int flags;\n";
534 Preamble += " char *str;\n";
535 Preamble += " long length;\n";
536 Preamble += "};\n";
Steve Naroffc6e571e2008-08-05 20:04:48 +0000537 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
538 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
539 Preamble += "#else\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000540 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroffc6e571e2008-08-05 20:04:48 +0000541 Preamble += "#endif\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000542 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
543 Preamble += "#endif\n";
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000544 // Blocks preamble.
545 Preamble += "#ifndef BLOCK_IMPL\n";
546 Preamble += "#define BLOCK_IMPL\n";
547 Preamble += "struct __block_impl {\n";
548 Preamble += " void *isa;\n";
549 Preamble += " int Flags;\n";
550 Preamble += " int Size;\n";
551 Preamble += " void *FuncPtr;\n";
552 Preamble += "};\n";
Steve Naroff44fe1e32008-12-16 15:50:30 +0000553 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
554 Preamble += "__OBJC_RW_STATICIMPORT void _Block_object_assign(void *, const void *, const int);\n";
555 Preamble += "__OBJC_RW_STATICIMPORT void _Block_object_dispose(const void *, const int);\n";
556 Preamble += "__OBJC_RW_STATICIMPORT void *_NSConcreteGlobalBlock[32];\n";
557 Preamble += "__OBJC_RW_STATICIMPORT void *_NSConcreteStackBlock[32];\n";
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000558 Preamble += "#endif\n";
Steve Naroff39ba90e2008-10-27 18:50:14 +0000559 if (LangOpts.Microsoft) {
Steve Naroff1b208d72008-12-08 17:30:33 +0000560 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
561 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroff39ba90e2008-10-27 18:50:14 +0000562 Preamble += "#define __attribute__(X)\n";
563 }
Chris Lattner12499682008-01-31 19:38:44 +0000564}
565
566
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000567//===----------------------------------------------------------------------===//
568// Top Level Driver Code
569//===----------------------------------------------------------------------===//
570
Chris Lattnera17991f2009-03-29 16:50:03 +0000571void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Chris Lattner74db1682007-10-16 21:07:07 +0000572 // Two cases: either the decl could be in the main file, or it could be in a
573 // #included file. If the former, rewrite it now. If the later, check to see
574 // if we rewrote the #include/#import.
575 SourceLocation Loc = D->getLocation();
Chris Lattner18c8dc02009-01-16 07:36:28 +0000576 Loc = SM->getInstantiationLoc(Loc);
Chris Lattner74db1682007-10-16 21:07:07 +0000577
578 // If this is for a builtin, ignore it.
579 if (Loc.isInvalid()) return;
580
Steve Naroffe9780582007-10-23 23:50:29 +0000581 // Look for built-in declarations that we need to refer during the rewrite.
582 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff02a82aa2007-10-30 23:14:51 +0000583 RewriteFunctionDecl(FD);
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000584 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000585 // declared in <Foundation/NSString.h>
Chris Lattnerd120b9e2008-11-24 03:54:41 +0000586 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000587 ConstantStringClassReference = FVD;
588 return;
589 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000590 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff3774dd92007-10-26 20:53:56 +0000591 RewriteInterfaceDecl(MD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000592 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff667f1682007-10-30 13:30:57 +0000593 RewriteCategoryDecl(CD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000594 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000595 RewriteProtocolDecl(PD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000596 } else if (ObjCForwardProtocolDecl *FP =
597 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000598 RewriteForwardProtocolDecl(FP);
Douglas Gregor6e4fa2c2009-01-09 00:49:46 +0000599 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
600 // Recurse into linkage specifications
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000601 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
602 DIEnd = LSD->decls_end();
Douglas Gregor6e4fa2c2009-01-09 00:49:46 +0000603 DI != DIEnd; ++DI)
Chris Lattnera17991f2009-03-29 16:50:03 +0000604 HandleTopLevelSingleDecl(*DI);
Steve Naroffe9780582007-10-23 23:50:29 +0000605 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000606 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenek2450c262008-04-14 21:24:13 +0000607 if (SM->isFromMainFile(Loc))
Chris Lattner74db1682007-10-16 21:07:07 +0000608 return HandleDeclInMainFile(D);
Chris Lattner74db1682007-10-16 21:07:07 +0000609}
610
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000611//===----------------------------------------------------------------------===//
612// Syntactic (non-AST) Rewriting Code
613//===----------------------------------------------------------------------===//
614
Steve Naroff44e81222008-04-14 22:03:09 +0000615void RewriteObjC::RewriteInclude() {
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000616 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000617 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
618 const char *MainBufStart = MainBuf.first;
619 const char *MainBufEnd = MainBuf.second;
620 size_t ImportLen = strlen("import");
621 size_t IncludeLen = strlen("include");
622
Fariborz Jahanianc81ed742008-01-19 01:03:17 +0000623 // Loop over the whole file, looking for includes.
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000624 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
625 if (*BufPtr == '#') {
626 if (++BufPtr == MainBufEnd)
627 return;
628 while (*BufPtr == ' ' || *BufPtr == '\t')
629 if (++BufPtr == MainBufEnd)
630 return;
631 if (!strncmp(BufPtr, "import", ImportLen)) {
632 // replace import with include
633 SourceLocation ImportLoc =
634 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000635 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000636 BufPtr += ImportLen;
637 }
638 }
639 }
Chris Lattner74db1682007-10-16 21:07:07 +0000640}
641
Steve Naroff44e81222008-04-14 22:03:09 +0000642void RewriteObjC::RewriteTabs() {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000643 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
644 const char *MainBufStart = MainBuf.first;
645 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000646
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000647 // Loop over the whole file, looking for tabs.
648 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
649 if (*BufPtr != '\t')
650 continue;
651
652 // Okay, we found a tab. This tab will turn into at least one character,
653 // but it depends on which 'virtual column' it is in. Compute that now.
654 unsigned VCol = 0;
655 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
656 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
657 ++VCol;
658
659 // Okay, now that we know the virtual column, we know how many spaces to
660 // insert. We assume 8-character tab-stops.
661 unsigned Spaces = 8-(VCol & 7);
662
663 // Get the location of the tab.
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000664 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
665 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000666
667 // Rewrite the single tab character into a sequence of spaces.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000668 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000669 }
Chris Lattner569faa62007-10-11 18:38:32 +0000670}
671
Steve Naroff121ed222008-12-02 15:48:25 +0000672static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
673 ObjCIvarDecl *OID) {
674 std::string S;
675 S = "((struct ";
676 S += ClassDecl->getIdentifier()->getName();
677 S += "_IMPL *)self)->";
678 S += OID->getNameAsCString();
679 return S;
680}
681
Steve Naroffea6610f2008-12-02 17:36:43 +0000682void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
683 ObjCImplementationDecl *IMD,
684 ObjCCategoryImplDecl *CID) {
Steve Naroff110be842008-12-01 20:33:01 +0000685 SourceLocation startLoc = PID->getLocStart();
686 InsertText(startLoc, "// ", 3);
Steve Naroff121ed222008-12-02 15:48:25 +0000687 const char *startBuf = SM->getCharacterData(startLoc);
688 assert((*startBuf == '@') && "bogus @synthesize location");
689 const char *semiBuf = strchr(startBuf, ';');
690 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek0c97e042009-02-07 01:47:29 +0000691 SourceLocation onePastSemiLoc =
692 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroff121ed222008-12-02 15:48:25 +0000693
694 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
695 return; // FIXME: is this correct?
696
697 // Generate the 'getter' function.
Steve Naroff121ed222008-12-02 15:48:25 +0000698 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroff121ed222008-12-02 15:48:25 +0000699 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroff121ed222008-12-02 15:48:25 +0000700 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Steve Naroff1e7b7962008-12-02 16:05:55 +0000701
702 if (!OID)
703 return;
704
705 std::string Getr;
706 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
707 Getr += "{ ";
708 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroff11671e72008-12-02 17:54:50 +0000709 // FIXME: deal with code generation implications for various property
710 // attributes (copy, retain, nonatomic).
711 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroff1e7b7962008-12-02 16:05:55 +0000712 Getr += "return " + getIvarAccessString(ClassDecl, OID);
713 Getr += "; }";
Steve Naroff121ed222008-12-02 15:48:25 +0000714 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroff121ed222008-12-02 15:48:25 +0000715 if (PD->isReadOnly())
716 return;
717
718 // Generate the 'setter' function.
719 std::string Setr;
720 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroff121ed222008-12-02 15:48:25 +0000721 Setr += "{ ";
Steve Naroff1e7b7962008-12-02 16:05:55 +0000722 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff11671e72008-12-02 17:54:50 +0000723 // FIXME: deal with code generation implications for various property
724 // attributes (copy, retain, nonatomic).
Steve Narofff6ce8a12008-12-03 00:56:33 +0000725 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroff1e7b7962008-12-02 16:05:55 +0000726 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Steve Naroff20f67392008-12-11 19:29:16 +0000727 Setr += PD->getNameAsCString();
Steve Naroff1e7b7962008-12-02 16:05:55 +0000728 Setr += "; }";
Steve Naroff121ed222008-12-02 15:48:25 +0000729 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroff110be842008-12-01 20:33:01 +0000730}
Chris Lattner569faa62007-10-11 18:38:32 +0000731
Steve Naroff44e81222008-04-14 22:03:09 +0000732void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000733 // Get the start location and compute the semi location.
734 SourceLocation startLoc = ClassDecl->getLocation();
735 const char *startBuf = SM->getCharacterData(startLoc);
736 const char *semiPtr = strchr(startBuf, ';');
737
738 // Translate to typedef's that forward reference structs with the same name
739 // as the class. As a convenience, we include the original declaration
740 // as a comment.
741 std::string typedefString;
742 typedefString += "// ";
Steve Naroff71226032007-10-24 22:48:43 +0000743 typedefString.append(startBuf, semiPtr-startBuf+1);
744 typedefString += "\n";
Chris Lattner6a028742009-02-20 18:04:31 +0000745 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
746 I != E; ++I) {
747 ObjCInterfaceDecl *ForwardDecl = *I;
Steve Naroff2aeae312007-11-09 12:50:28 +0000748 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattner271d4c22008-11-24 05:29:24 +0000749 typedefString += ForwardDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +0000750 typedefString += "\n";
751 typedefString += "#define _REWRITER_typedef_";
Chris Lattner271d4c22008-11-24 05:29:24 +0000752 typedefString += ForwardDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +0000753 typedefString += "\n";
Steve Naroff4242b972007-11-05 14:36:37 +0000754 typedefString += "typedef struct objc_object ";
Chris Lattner271d4c22008-11-24 05:29:24 +0000755 typedefString += ForwardDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +0000756 typedefString += ";\n#endif\n";
Steve Naroff71226032007-10-24 22:48:43 +0000757 }
758
759 // Replace the @class with typedefs corresponding to the classes.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000760 ReplaceText(startLoc, semiPtr-startBuf+1,
761 typedefString.c_str(), typedefString.size());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000762}
763
Steve Naroff44e81222008-04-14 22:03:09 +0000764void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff2ce399a2007-12-14 23:37:57 +0000765 SourceLocation LocStart = Method->getLocStart();
766 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff667f1682007-10-30 13:30:57 +0000767
Chris Lattner2d89c562009-02-04 01:06:56 +0000768 if (SM->getInstantiationLineNumber(LocEnd) >
769 SM->getInstantiationLineNumber(LocStart)) {
Steve Naroff99f50fe2008-10-21 13:37:27 +0000770 InsertText(LocStart, "#if 0\n", 6);
771 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff2ce399a2007-12-14 23:37:57 +0000772 } else {
Chris Lattner6216f292008-01-31 19:42:41 +0000773 InsertText(LocStart, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000774 }
775}
776
Steve Naroff56af2002009-01-11 01:06:09 +0000777void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop)
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000778{
Steve Naroff56af2002009-01-11 01:06:09 +0000779 SourceLocation Loc = prop->getLocation();
780
781 ReplaceText(Loc, 0, "// ", 3);
782
783 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000784}
785
Steve Naroff44e81222008-04-14 22:03:09 +0000786void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff667f1682007-10-30 13:30:57 +0000787 SourceLocation LocStart = CatDecl->getLocStart();
788
789 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000790 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000791
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000792 for (ObjCCategoryDecl::instmeth_iterator
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000793 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000794 I != E; ++I)
Steve Naroff2ce399a2007-12-14 23:37:57 +0000795 RewriteMethodDeclaration(*I);
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000796 for (ObjCCategoryDecl::classmeth_iterator
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000797 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000798 I != E; ++I)
Steve Naroff2ce399a2007-12-14 23:37:57 +0000799 RewriteMethodDeclaration(*I);
800
Steve Naroff667f1682007-10-30 13:30:57 +0000801 // Lastly, comment out the @end.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000802 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000803}
804
Steve Naroff44e81222008-04-14 22:03:09 +0000805void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000806 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000807
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000808 SourceLocation LocStart = PDecl->getLocStart();
809
810 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000811 ReplaceText(LocStart, 0, "// ", 3);
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000812
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000813 for (ObjCProtocolDecl::instmeth_iterator
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000814 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000815 I != E; ++I)
Steve Naroff2ce399a2007-12-14 23:37:57 +0000816 RewriteMethodDeclaration(*I);
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000817 for (ObjCProtocolDecl::classmeth_iterator
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000818 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000819 I != E; ++I)
Steve Naroff2ce399a2007-12-14 23:37:57 +0000820 RewriteMethodDeclaration(*I);
821
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000822 // Lastly, comment out the @end.
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000823 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000824 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff268fa592007-11-14 15:03:57 +0000825
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000826 // Must comment out @optional/@required
827 const char *startBuf = SM->getCharacterData(LocStart);
828 const char *endBuf = SM->getCharacterData(LocEnd);
829 for (const char *p = startBuf; p < endBuf; p++) {
830 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
831 std::string CommentedOptional = "/* @optional */";
Steve Naroff268fa592007-11-14 15:03:57 +0000832 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000833 ReplaceText(OptionalLoc, strlen("@optional"),
834 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000835
836 }
837 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
838 std::string CommentedRequired = "/* @required */";
Steve Naroff268fa592007-11-14 15:03:57 +0000839 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000840 ReplaceText(OptionalLoc, strlen("@required"),
841 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000842
843 }
844 }
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000845}
846
Steve Naroff44e81222008-04-14 22:03:09 +0000847void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000848 SourceLocation LocStart = PDecl->getLocation();
Steve Naroff0540f3f2007-11-14 03:37:28 +0000849 if (LocStart.isInvalid())
850 assert(false && "Invalid SourceLocation");
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000851 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000852 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000853}
854
Steve Naroff44e81222008-04-14 22:03:09 +0000855void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000856 std::string &ResultStr) {
Steve Naroff6449c6c2008-10-30 12:09:33 +0000857 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroff91044cf2008-07-16 14:40:40 +0000858 const FunctionType *FPRetType = 0;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000859 ResultStr += "\nstatic ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000860 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000861 ResultStr += "id";
Steve Naroff20f67392008-12-11 19:29:16 +0000862 else if (OMD->getResultType()->isFunctionPointerType() ||
863 OMD->getResultType()->isBlockPointerType()) {
Steve Naroff91044cf2008-07-16 14:40:40 +0000864 // needs special handling, since pointer-to-functions have special
865 // syntax (where a decaration models use).
866 QualType retType = OMD->getResultType();
Steve Naroff20f67392008-12-11 19:29:16 +0000867 QualType PointeeTy;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000868 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Naroff20f67392008-12-11 19:29:16 +0000869 PointeeTy = PT->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000870 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Naroff20f67392008-12-11 19:29:16 +0000871 PointeeTy = BPT->getPointeeType();
872 if ((FPRetType = PointeeTy->getAsFunctionType())) {
873 ResultStr += FPRetType->getResultType().getAsString();
874 ResultStr += "(*";
Steve Naroff91044cf2008-07-16 14:40:40 +0000875 }
876 } else
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000877 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000878 ResultStr += " ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000879
880 // Unique method name
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000881 std::string NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000882
Douglas Gregor5d764842009-01-09 17:18:27 +0000883 if (OMD->isInstanceMethod())
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000884 NameStr += "_I_";
885 else
886 NameStr += "_C_";
887
Chris Lattner271d4c22008-11-24 05:29:24 +0000888 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000889 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000890
Ted Kremenek42730c52008-01-07 19:49:32 +0000891 if (ObjCCategoryImplDecl *CID =
Steve Naroff438be772009-01-08 19:41:02 +0000892 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattner271d4c22008-11-24 05:29:24 +0000893 NameStr += CID->getNameAsString();
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000894 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000895 }
Steve Naroff5cb1e6e2008-04-04 22:23:44 +0000896 // Append selector names, replacing ':' with '_'
Chris Lattner3a8f2942008-11-24 03:33:13 +0000897 {
898 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000899 int len = selString.size();
900 for (int i = 0; i < len; i++)
901 if (selString[i] == ':')
902 selString[i] = '_';
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000903 NameStr += selString;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000904 }
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000905 // Remember this name for metadata emission
906 MethodInternalNames[OMD] = NameStr;
907 ResultStr += NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000908
909 // Rewrite arguments
910 ResultStr += "(";
911
912 // invisible arguments
Douglas Gregor5d764842009-01-09 17:18:27 +0000913 if (OMD->isInstanceMethod()) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000914 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000915 selfTy = Context->getPointerType(selfTy);
Steve Naroff60dfb6b2008-03-12 00:25:36 +0000916 if (!LangOpts.Microsoft) {
917 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
918 ResultStr += "struct ";
919 }
920 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattner271d4c22008-11-24 05:29:24 +0000921 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroffde0da102008-03-10 23:16:54 +0000922 ResultStr += " *";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000923 }
924 else
Steve Naroff450d2fc2009-04-29 16:37:50 +0000925 ResultStr += Context->getObjCClassType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000926
927 ResultStr += " self, ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000928 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000929 ResultStr += " _cmd";
930
931 // Method arguments.
Chris Lattner5c6b2c62009-02-20 18:43:26 +0000932 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
933 E = OMD->param_end(); PI != E; ++PI) {
934 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000935 ResultStr += ", ";
Steve Naroff133dfda2008-04-18 21:13:19 +0000936 if (PDecl->getType()->isObjCQualifiedIdType()) {
937 ResultStr += "id ";
Chris Lattner271d4c22008-11-24 05:29:24 +0000938 ResultStr += PDecl->getNameAsString();
Steve Naroff133dfda2008-04-18 21:13:19 +0000939 } else {
Chris Lattner271d4c22008-11-24 05:29:24 +0000940 std::string Name = PDecl->getNameAsString();
Steve Naroffd896f4b2008-12-11 21:05:33 +0000941 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroff4e2ae512008-10-30 14:45:29 +0000942 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000943 const BlockPointerType *BPT = PDecl->getType()->getAs<BlockPointerType>();
Douglas Gregor3bf3bbc2009-05-29 20:38:28 +0000944 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name,
945 Context->PrintingPolicy);
Steve Naroff4e2ae512008-10-30 14:45:29 +0000946 } else
Douglas Gregor3bf3bbc2009-05-29 20:38:28 +0000947 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroff133dfda2008-04-18 21:13:19 +0000948 ResultStr += Name;
949 }
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000950 }
Fariborz Jahanian2fab94e2008-01-21 20:14:23 +0000951 if (OMD->isVariadic())
952 ResultStr += ", ...";
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000953 ResultStr += ") ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000954
Steve Naroff91044cf2008-07-16 14:40:40 +0000955 if (FPRetType) {
956 ResultStr += ")"; // close the precedence "scope" for "*".
957
958 // Now, emit the argument types (if any).
Douglas Gregor4fa58902009-02-26 23:50:07 +0000959 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff91044cf2008-07-16 14:40:40 +0000960 ResultStr += "(";
961 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
962 if (i) ResultStr += ", ";
963 std::string ParamStr = FT->getArgType(i).getAsString();
964 ResultStr += ParamStr;
965 }
966 if (FT->isVariadic()) {
967 if (FT->getNumArgs()) ResultStr += ", ";
968 ResultStr += "...";
969 }
970 ResultStr += ")";
971 } else {
972 ResultStr += "()";
973 }
974 }
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000975}
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000976void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000977 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
978 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000979
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000980 if (IMD)
Chris Lattner6216f292008-01-31 19:42:41 +0000981 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000982 else
Chris Lattner6216f292008-01-31 19:42:41 +0000983 InsertText(CID->getLocStart(), "// ", 3);
Steve Naroff21658f62008-11-13 20:07:04 +0000984
Ted Kremenek42730c52008-01-07 19:49:32 +0000985 for (ObjCCategoryImplDecl::instmeth_iterator
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000986 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
987 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregorcd19b572009-04-23 01:02:12 +0000988 I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000989 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000990 ObjCMethodDecl *OMD = *I;
991 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000992 SourceLocation LocStart = OMD->getLocStart();
Argiris Kirtzidisccb9efe2009-06-30 02:35:26 +0000993 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redlbc9ef252009-04-26 20:35:05 +0000994
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000995 const char *startBuf = SM->getCharacterData(LocStart);
996 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000997 ReplaceText(LocStart, endBuf-startBuf,
998 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000999 }
1000
Ted Kremenek42730c52008-01-07 19:49:32 +00001001 for (ObjCCategoryImplDecl::classmeth_iterator
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001002 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1003 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregorcd19b572009-04-23 01:02:12 +00001004 I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +00001005 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +00001006 ObjCMethodDecl *OMD = *I;
1007 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +00001008 SourceLocation LocStart = OMD->getLocStart();
Argiris Kirtzidisccb9efe2009-06-30 02:35:26 +00001009 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +00001010
1011 const char *startBuf = SM->getCharacterData(LocStart);
1012 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001013 ReplaceText(LocStart, endBuf-startBuf,
1014 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +00001015 }
Steve Naroff110be842008-12-01 20:33:01 +00001016 for (ObjCCategoryImplDecl::propimpl_iterator
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001017 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1018 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregorcd19b572009-04-23 01:02:12 +00001019 I != E; ++I) {
Steve Naroffea6610f2008-12-02 17:36:43 +00001020 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroff110be842008-12-01 20:33:01 +00001021 }
1022
Fariborz Jahanian0136e372007-11-13 20:04:28 +00001023 if (IMD)
Chris Lattner6216f292008-01-31 19:42:41 +00001024 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian0136e372007-11-13 20:04:28 +00001025 else
Chris Lattner6216f292008-01-31 19:42:41 +00001026 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +00001027}
1028
Steve Naroff44e81222008-04-14 22:03:09 +00001029void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffef20ed32007-10-30 02:23:23 +00001030 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +00001031 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff77d081b2007-11-01 03:35:41 +00001032 // we haven't seen a forward decl - generate a typedef.
Steve Naroff2adead72007-11-14 23:02:56 +00001033 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattner271d4c22008-11-24 05:29:24 +00001034 ResultStr += ClassDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +00001035 ResultStr += "\n";
1036 ResultStr += "#define _REWRITER_typedef_";
Chris Lattner271d4c22008-11-24 05:29:24 +00001037 ResultStr += ClassDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +00001038 ResultStr += "\n";
Steve Naroffde0da102008-03-10 23:16:54 +00001039 ResultStr += "typedef struct objc_object ";
Chris Lattner271d4c22008-11-24 05:29:24 +00001040 ResultStr += ClassDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +00001041 ResultStr += ";\n#endif\n";
Steve Naroff77d081b2007-11-01 03:35:41 +00001042 // Mark this typedef as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +00001043 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff77d081b2007-11-01 03:35:41 +00001044 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001045 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Naroffef20ed32007-10-30 02:23:23 +00001046
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001047 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
1048 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff56af2002009-01-11 01:06:09 +00001049 RewriteProperty(*I);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001050 for (ObjCInterfaceDecl::instmeth_iterator
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001051 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001052 I != E; ++I)
Steve Naroff2ce399a2007-12-14 23:37:57 +00001053 RewriteMethodDeclaration(*I);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001054 for (ObjCInterfaceDecl::classmeth_iterator
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001055 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001056 I != E; ++I)
Steve Naroff2ce399a2007-12-14 23:37:57 +00001057 RewriteMethodDeclaration(*I);
1058
Steve Naroff1ccf4632007-10-30 03:43:13 +00001059 // Lastly, comment out the @end.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001060 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff3774dd92007-10-26 20:53:56 +00001061}
1062
Steve Naroffedb4bc92008-12-09 12:56:34 +00001063Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1064 SourceRange SrcRange) {
Steve Naroff0e948412008-12-04 16:24:46 +00001065 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1066 // This allows us to reuse all the fun and games in SynthMessageExpr().
1067 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1068 ObjCMessageExpr *MsgExpr;
1069 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1070 llvm::SmallVector<Expr *, 1> ExprVec;
1071 ExprVec.push_back(newStmt);
1072
Steve Narofffbed6802008-12-08 16:43:47 +00001073 Stmt *Receiver = PropRefExpr->getBase();
1074 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1075 if (PRE && PropGetters[PRE]) {
1076 // This allows us to handle chain/nested property getters.
1077 Receiver = PropGetters[PRE];
1078 }
Ted Kremenek0c97e042009-02-07 01:47:29 +00001079 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
Steve Naroff0e948412008-12-04 16:24:46 +00001080 PDecl->getSetterName(), PDecl->getType(),
1081 PDecl->getSetterMethodDecl(),
1082 SourceLocation(), SourceLocation(),
1083 &ExprVec[0], 1);
1084 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
1085
1086 // Now do the actual rewrite.
Steve Naroffedb4bc92008-12-09 12:56:34 +00001087 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroff478f7382008-12-10 14:53:27 +00001088 //delete BinOp;
Ted Kremenek0c97e042009-02-07 01:47:29 +00001089 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1090 // to things that stay around.
1091 Context->Deallocate(MsgExpr);
Steve Naroff0e948412008-12-04 16:24:46 +00001092 return ReplacingStmt;
Steve Narofff6ce8a12008-12-03 00:56:33 +00001093}
1094
Steve Naroff0e948412008-12-04 16:24:46 +00001095Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Narofff6ce8a12008-12-03 00:56:33 +00001096 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1097 // This allows us to reuse all the fun and games in SynthMessageExpr().
1098 ObjCMessageExpr *MsgExpr;
1099 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1100
Steve Narofffbed6802008-12-08 16:43:47 +00001101 Stmt *Receiver = PropRefExpr->getBase();
1102
1103 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1104 if (PRE && PropGetters[PRE]) {
1105 // This allows us to handle chain/nested property getters.
1106 Receiver = PropGetters[PRE];
1107 }
Ted Kremenek0c97e042009-02-07 01:47:29 +00001108 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
Steve Narofff6ce8a12008-12-03 00:56:33 +00001109 PDecl->getGetterName(), PDecl->getType(),
1110 PDecl->getGetterMethodDecl(),
1111 SourceLocation(), SourceLocation(),
1112 0, 0);
1113
Steve Naroff102c3f22008-12-04 23:50:32 +00001114 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Narofffbed6802008-12-08 16:43:47 +00001115
1116 if (!PropParentMap)
1117 PropParentMap = new ParentMap(CurrentBody);
1118
1119 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1120 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1121 // We stash away the ReplacingStmt since actually doing the
1122 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1123 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek0c97e042009-02-07 01:47:29 +00001124 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1125 // to things that stay around.
1126 Context->Deallocate(MsgExpr);
Steve Narofffbed6802008-12-08 16:43:47 +00001127 return PropRefExpr; // return the original...
1128 } else {
1129 ReplaceStmt(PropRefExpr, ReplacingStmt);
Ted Kremenek0c97e042009-02-07 01:47:29 +00001130 // delete PropRefExpr; elsewhere...
1131 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1132 // to things that stay around.
1133 Context->Deallocate(MsgExpr);
Steve Narofffbed6802008-12-08 16:43:47 +00001134 return ReplacingStmt;
1135 }
Steve Narofff6ce8a12008-12-03 00:56:33 +00001136}
1137
Chris Lattner343c82b2008-05-23 20:40:52 +00001138Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
1139 SourceLocation OrigStart) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001140 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00001141 if (CurMethodDef) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001142 if (const PointerType *pType = IV->getBase()->getType()->getAs<PointerType>()) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00001143 ObjCInterfaceType *iFaceDecl =
1144 dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroffa9636222008-05-08 17:52:16 +00001145 // lookup which class implements the instance variable.
1146 ObjCInterfaceDecl *clsDeclared = 0;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001147 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001148 clsDeclared);
Steve Naroffa9636222008-05-08 17:52:16 +00001149 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1150
1151 // Synthesize an explicit cast to gain access to the ivar.
1152 std::string RecName = clsDeclared->getIdentifier()->getName();
1153 RecName += "_IMPL";
1154 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001155 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek2c984042008-09-05 01:34:33 +00001156 SourceLocation(), II);
Steve Naroffa9636222008-05-08 17:52:16 +00001157 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1158 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Anders Carlsson7ef181c2009-07-31 00:48:10 +00001159 CastExpr *castExpr = new (Context) CStyleCastExpr(castT,
1160 CastExpr::CK_Unknown,
1161 IV->getBase(),
1162 castT,SourceLocation(),
1163 SourceLocation());
Steve Naroffa9636222008-05-08 17:52:16 +00001164 // Don't forget the parens to enforce the proper binding.
Ted Kremenek0c97e042009-02-07 01:47:29 +00001165 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1166 IV->getBase()->getLocEnd(),
1167 castExpr);
Steve Naroffa9636222008-05-08 17:52:16 +00001168 if (IV->isFreeIvar() &&
Steve Naroff38a9e3f2008-10-27 17:20:55 +00001169 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00001170 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1171 IV->getLocation(),
1172 D->getType());
Steve Naroffa9636222008-05-08 17:52:16 +00001173 ReplaceStmt(IV, ME);
Steve Naroff102c3f22008-12-04 23:50:32 +00001174 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffa9636222008-05-08 17:52:16 +00001175 return ME;
Steve Naroff292b7b92007-11-15 11:33:00 +00001176 }
Chris Lattner343c82b2008-05-23 20:40:52 +00001177
1178 ReplaceStmt(IV->getBase(), PE);
1179 // Cannot delete IV->getBase(), since PE points to it.
1180 // Replace the old base with the cast. This is important when doing
1181 // embedded rewrites. For example, [newInv->_container addObject:0].
1182 IV->setBase(PE);
1183 return IV;
Steve Naroff292b7b92007-11-15 11:33:00 +00001184 }
Steve Naroffe6155362008-04-18 21:55:08 +00001185 } else { // we are outside a method.
Steve Naroffd8d30b92008-05-06 23:20:07 +00001186 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
1187
1188 // Explicit ivar refs need to have a cast inserted.
1189 // FIXME: consider sharing some of this code with the code above.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001190 if (const PointerType *pType = IV->getBase()->getType()->getAs<PointerType>()) {
Steve Naroffa9636222008-05-08 17:52:16 +00001191 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroffd8d30b92008-05-06 23:20:07 +00001192 // lookup which class implements the instance variable.
1193 ObjCInterfaceDecl *clsDeclared = 0;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001194 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001195 clsDeclared);
Steve Naroffd8d30b92008-05-06 23:20:07 +00001196 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1197
1198 // Synthesize an explicit cast to gain access to the ivar.
1199 std::string RecName = clsDeclared->getIdentifier()->getName();
1200 RecName += "_IMPL";
1201 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001202 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek2c984042008-09-05 01:34:33 +00001203 SourceLocation(), II);
Steve Naroffd8d30b92008-05-06 23:20:07 +00001204 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1205 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Anders Carlsson7ef181c2009-07-31 00:48:10 +00001206 CastExpr *castExpr = new (Context) CStyleCastExpr(castT,
1207 CastExpr::CK_Unknown,
1208 IV->getBase(),
Ted Kremenek0c97e042009-02-07 01:47:29 +00001209 castT, SourceLocation(),
1210 SourceLocation());
Steve Naroffd8d30b92008-05-06 23:20:07 +00001211 // Don't forget the parens to enforce the proper binding.
Ted Kremenek0c97e042009-02-07 01:47:29 +00001212 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner3cca6612008-05-28 16:38:23 +00001213 IV->getBase()->getLocEnd(), castExpr);
Steve Naroffd8d30b92008-05-06 23:20:07 +00001214 ReplaceStmt(IV->getBase(), PE);
1215 // Cannot delete IV->getBase(), since PE points to it.
1216 // Replace the old base with the cast. This is important when doing
1217 // embedded rewrites. For example, [newInv->_container addObject:0].
1218 IV->setBase(PE);
1219 return IV;
1220 }
Steve Naroff292b7b92007-11-15 11:33:00 +00001221 }
Steve Naroffe6155362008-04-18 21:55:08 +00001222 return IV;
Steve Naroff6b759ce2007-11-15 02:58:25 +00001223}
1224
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001225/// SynthCountByEnumWithState - To print:
1226/// ((unsigned int (*)
1227/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1228/// (void *)objc_msgSend)((id)l_collection,
1229/// sel_registerName(
1230/// "countByEnumeratingWithState:objects:count:"),
1231/// &enumState,
1232/// (id *)items, (unsigned int)16)
1233///
Steve Naroff44e81222008-04-14 22:03:09 +00001234void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001235 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1236 "id *, unsigned int))(void *)objc_msgSend)";
1237 buf += "\n\t\t";
1238 buf += "((id)l_collection,\n\t\t";
1239 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1240 buf += "\n\t\t";
1241 buf += "&enumState, "
1242 "(id *)items, (unsigned int)16)";
1243}
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001244
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001245/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1246/// statement to exit to its outer synthesized loop.
1247///
Steve Naroff44e81222008-04-14 22:03:09 +00001248Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001249 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1250 return S;
1251 // replace break with goto __break_label
1252 std::string buf;
1253
1254 SourceLocation startLoc = S->getLocStart();
1255 buf = "goto __break_label_";
1256 buf += utostr(ObjCBcLabelNo.back());
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001257 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001258
1259 return 0;
1260}
1261
1262/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1263/// statement to continue with its inner synthesized loop.
1264///
Steve Naroff44e81222008-04-14 22:03:09 +00001265Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001266 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1267 return S;
1268 // replace continue with goto __continue_label
1269 std::string buf;
1270
1271 SourceLocation startLoc = S->getLocStart();
1272 buf = "goto __continue_label_";
1273 buf += utostr(ObjCBcLabelNo.back());
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001274 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001275
1276 return 0;
1277}
1278
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001279/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001280/// It rewrites:
1281/// for ( type elem in collection) { stmts; }
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00001282
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001283/// Into:
1284/// {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001285/// type elem;
1286/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001287/// id items[16];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001288/// id l_collection = (id)collection;
1289/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1290/// objects:items count:16];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001291/// if (limit) {
1292/// unsigned long startMutations = *enumState.mutationsPtr;
1293/// do {
1294/// unsigned long counter = 0;
1295/// do {
1296/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001297/// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001298/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001299/// stmts;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001300/// __continue_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001301/// } while (counter < limit);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001302/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1303/// objects:items count:16]);
1304/// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001305/// __break_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001306/// }
1307/// else
1308/// elem = nil;
1309/// }
1310///
Steve Naroff44e81222008-04-14 22:03:09 +00001311Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner2c022162008-01-31 05:10:40 +00001312 SourceLocation OrigEnd) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001313 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1314 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1315 "ObjCForCollectionStmt Statement stack mismatch");
1316 assert(!ObjCBcLabelNo.empty() &&
1317 "ObjCForCollectionStmt - Label No stack empty");
1318
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001319 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001320 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001321 const char *elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001322 std::string elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001323 std::string buf;
1324 buf = "\n{\n\t";
1325 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1326 // type elem;
Chris Lattner4a9a85e2009-03-28 06:33:19 +00001327 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek91a2bd32008-10-06 22:16:13 +00001328 QualType ElementType = cast<ValueDecl>(D)->getType();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001329 elementTypeAsString = ElementType.getAsString();
1330 buf += elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001331 buf += " ";
Chris Lattnerd120b9e2008-11-24 03:54:41 +00001332 elementName = D->getNameAsCString();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001333 buf += elementName;
1334 buf += ";\n\t";
1335 }
Chris Lattner690c2872008-04-08 05:52:18 +00001336 else {
1337 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattnerd120b9e2008-11-24 03:54:41 +00001338 elementName = DR->getDecl()->getNameAsCString();
Douglas Gregord2baafd2008-10-21 16:13:35 +00001339 elementTypeAsString
1340 = cast<ValueDecl>(DR->getDecl())->getType().getAsString();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001341 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001342
1343 // struct __objcFastEnumerationState enumState = { 0 };
1344 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1345 // id items[16];
1346 buf += "id items[16];\n\t";
1347 // id l_collection = (id)
1348 buf += "id l_collection = (id)";
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +00001349 // Find start location of 'collection' the hard way!
1350 const char *startCollectionBuf = startBuf;
1351 startCollectionBuf += 3; // skip 'for'
1352 startCollectionBuf = strchr(startCollectionBuf, '(');
1353 startCollectionBuf++; // skip '('
1354 // find 'in' and skip it.
1355 while (*startCollectionBuf != ' ' ||
1356 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1357 (*(startCollectionBuf+3) != ' ' &&
1358 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1359 startCollectionBuf++;
1360 startCollectionBuf += 3;
1361
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001362 // Replace: "for (type element in" with string constructed thus far.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001363 ReplaceText(startLoc, startCollectionBuf - startBuf,
1364 buf.c_str(), buf.size());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001365 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +00001366 SourceLocation rightParenLoc = S->getRParenLoc();
1367 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1368 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001369 buf = ";\n\t";
1370
1371 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1372 // objects:items count:16];
1373 // which is synthesized into:
1374 // unsigned int limit =
1375 // ((unsigned int (*)
1376 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1377 // (void *)objc_msgSend)((id)l_collection,
1378 // sel_registerName(
1379 // "countByEnumeratingWithState:objects:count:"),
1380 // (struct __objcFastEnumerationState *)&state,
1381 // (id *)items, (unsigned int)16);
1382 buf += "unsigned long limit =\n\t\t";
1383 SynthCountByEnumWithState(buf);
1384 buf += ";\n\t";
1385 /// if (limit) {
1386 /// unsigned long startMutations = *enumState.mutationsPtr;
1387 /// do {
1388 /// unsigned long counter = 0;
1389 /// do {
1390 /// if (startMutations != *enumState.mutationsPtr)
1391 /// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001392 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001393 buf += "if (limit) {\n\t";
1394 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1395 buf += "do {\n\t\t";
1396 buf += "unsigned long counter = 0;\n\t\t";
1397 buf += "do {\n\t\t\t";
1398 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1399 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1400 buf += elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001401 buf += " = (";
1402 buf += elementTypeAsString;
1403 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001404 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001405 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001406
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001407 /// __continue_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001408 /// } while (counter < limit);
1409 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1410 /// objects:items count:16]);
1411 /// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001412 /// __break_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001413 /// }
1414 /// else
1415 /// elem = nil;
1416 /// }
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001417 ///
1418 buf = ";\n\t";
1419 buf += "__continue_label_";
1420 buf += utostr(ObjCBcLabelNo.back());
1421 buf += ": ;";
1422 buf += "\n\t\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001423 buf += "} while (counter < limit);\n\t";
1424 buf += "} while (limit = ";
1425 SynthCountByEnumWithState(buf);
1426 buf += ");\n\t";
1427 buf += elementName;
Steve Naroffa9dc0262008-12-17 14:24:39 +00001428 buf += " = ((id)0);\n\t";
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001429 buf += "__break_label_";
1430 buf += utostr(ObjCBcLabelNo.back());
1431 buf += ": ;\n\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001432 buf += "}\n\t";
1433 buf += "else\n\t\t";
1434 buf += elementName;
Steve Naroffa9dc0262008-12-17 14:24:39 +00001435 buf += " = ((id)0);\n";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001436 buf += "}\n";
Steve Naroff5f238fe2008-07-21 18:26:02 +00001437
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001438 // Insert all these *after* the statement body.
Sebastian Redlbc9ef252009-04-26 20:35:05 +00001439 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff5f238fe2008-07-21 18:26:02 +00001440 if (isa<CompoundStmt>(S->getBody())) {
1441 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1442 InsertText(endBodyLoc, buf.c_str(), buf.size());
1443 } else {
1444 /* Need to treat single statements specially. For example:
1445 *
1446 * for (A *a in b) if (stuff()) break;
1447 * for (A *a in b) xxxyy;
1448 *
1449 * The following code simply scans ahead to the semi to find the actual end.
1450 */
1451 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1452 const char *semiBuf = strchr(stmtBuf, ';');
1453 assert(semiBuf && "Can't find ';'");
1454 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1455 InsertText(endBodyLoc, buf.c_str(), buf.size());
1456 }
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001457 Stmts.pop_back();
1458 ObjCBcLabelNo.pop_back();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001459 return 0;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001460}
1461
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001462/// RewriteObjCSynchronizedStmt -
1463/// This routine rewrites @synchronized(expr) stmt;
1464/// into:
1465/// objc_sync_enter(expr);
1466/// @try stmt @finally { objc_sync_exit(expr); }
1467///
Steve Naroff44e81222008-04-14 22:03:09 +00001468Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001469 // Get the start location and compute the semi location.
1470 SourceLocation startLoc = S->getLocStart();
1471 const char *startBuf = SM->getCharacterData(startLoc);
1472
1473 assert((*startBuf == '@') && "bogus @synchronized location");
1474
1475 std::string buf;
Steve Naroffc1656a62008-08-21 13:03:03 +00001476 buf = "objc_sync_enter((id)";
1477 const char *lparenBuf = startBuf;
1478 while (*lparenBuf != '(') lparenBuf++;
1479 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Steve Naroff027cd0b2008-08-19 13:04:19 +00001480 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1481 // the sync expression is typically a message expression that's already
1482 // been rewritten! (which implies the SourceLocation's are invalid).
1483 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001484 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroff027cd0b2008-08-19 13:04:19 +00001485 while (*endBuf != ')') endBuf--;
1486 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001487 buf = ");\n";
1488 // declare a new scope with two variables, _stack and _rethrow.
1489 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1490 buf += "int buf[18/*32-bit i386*/];\n";
1491 buf += "char *pointers[4];} _stack;\n";
1492 buf += "id volatile _rethrow = 0;\n";
1493 buf += "objc_exception_try_enter(&_stack);\n";
1494 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001495 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001496 startLoc = S->getSynchBody()->getLocEnd();
1497 startBuf = SM->getCharacterData(startLoc);
1498
Steve Naroff027cd0b2008-08-19 13:04:19 +00001499 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001500 SourceLocation lastCurlyLoc = startLoc;
1501 buf = "}\nelse {\n";
1502 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff450d2fc2009-04-29 16:37:50 +00001503 buf += "}\n";
1504 buf += "{ /* implicit finally clause */\n";
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001505 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroff17919b52008-07-16 19:47:39 +00001506 buf += " objc_sync_exit(";
Ted Kremenek0c97e042009-02-07 01:47:29 +00001507 Expr *syncExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlsson7ef181c2009-07-31 00:48:10 +00001508 CastExpr::CK_Unknown,
Ted Kremenek0c97e042009-02-07 01:47:29 +00001509 S->getSynchExpr(),
1510 Context->getObjCIdType(),
1511 SourceLocation(),
1512 SourceLocation());
Ted Kremenek7b6f67b2008-09-13 05:16:45 +00001513 std::string syncExprBufS;
1514 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattner7099c782009-06-30 01:26:17 +00001515 syncExpr->printPretty(syncExprBuf, *Context, 0,
1516 PrintingPolicy(LangOpts));
Steve Naroff17919b52008-07-16 19:47:39 +00001517 buf += syncExprBuf.str();
1518 buf += ");\n";
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001519 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1520 buf += "}\n";
1521 buf += "}";
1522
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001523 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001524 return 0;
1525}
1526
Steve Naroff43964fb2008-12-05 17:03:39 +00001527void RewriteObjC::WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S) {
1528 // Perform a bottom up traversal of all children.
1529 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1530 CI != E; ++CI)
1531 if (*CI)
1532 WarnAboutReturnGotoContinueOrBreakStmts(*CI);
1533
1534 if (isa<ReturnStmt>(S) || isa<ContinueStmt>(S) ||
1535 isa<BreakStmt>(S) || isa<GotoStmt>(S)) {
1536 Diags.Report(Context->getFullLoc(S->getLocStart()),
1537 TryFinallyContainsReturnDiag);
1538 }
1539 return;
1540}
1541
Steve Naroff44e81222008-04-14 22:03:09 +00001542Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001543 // Get the start location and compute the semi location.
1544 SourceLocation startLoc = S->getLocStart();
1545 const char *startBuf = SM->getCharacterData(startLoc);
1546
1547 assert((*startBuf == '@') && "bogus @try location");
1548
1549 std::string buf;
1550 // declare a new scope with two variables, _stack and _rethrow.
1551 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1552 buf += "int buf[18/*32-bit i386*/];\n";
1553 buf += "char *pointers[4];} _stack;\n";
1554 buf += "id volatile _rethrow = 0;\n";
1555 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +00001556 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffe9f69842007-11-07 04:08:17 +00001557
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001558 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001559
1560 startLoc = S->getTryBody()->getLocEnd();
1561 startBuf = SM->getCharacterData(startLoc);
1562
1563 assert((*startBuf == '}') && "bogus @try block");
Steve Naroff9d0ff352008-07-16 15:31:30 +00001564
Steve Naroffe9f69842007-11-07 04:08:17 +00001565 SourceLocation lastCurlyLoc = startLoc;
Steve Naroff9d0ff352008-07-16 15:31:30 +00001566 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1567 if (catchList) {
1568 startLoc = startLoc.getFileLocWithOffset(1);
1569 buf = " /* @catch begin */ else {\n";
1570 buf += " id _caught = objc_exception_extract(&_stack);\n";
1571 buf += " objc_exception_try_enter (&_stack);\n";
1572 buf += " if (_setjmp(_stack.buf))\n";
1573 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1574 buf += " else { /* @catch continue */";
1575
1576 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff36269d22008-09-09 19:59:12 +00001577 } else { /* no catch list */
1578 buf = "}\nelse {\n";
1579 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1580 buf += "}";
1581 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroff9d0ff352008-07-16 15:31:30 +00001582 }
Steve Naroffe9f69842007-11-07 04:08:17 +00001583 bool sawIdTypedCatch = false;
1584 Stmt *lastCatchBody = 0;
Steve Naroffe9f69842007-11-07 04:08:17 +00001585 while (catchList) {
Steve Naroff0e8b96a2009-03-03 19:52:17 +00001586 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroffe9f69842007-11-07 04:08:17 +00001587
1588 if (catchList == S->getCatchStmts())
1589 buf = "if ("; // we are generating code for the first catch clause
1590 else
1591 buf = "else if (";
1592 startLoc = catchList->getLocStart();
1593 startBuf = SM->getCharacterData(startLoc);
1594
1595 assert((*startBuf == '@') && "bogus @catch location");
1596
1597 const char *lParenLoc = strchr(startBuf, '(');
1598
Steve Naroff397c4ce2008-02-01 22:08:12 +00001599 if (catchList->hasEllipsis()) {
Steve Naroff929c77e2008-02-01 20:02:07 +00001600 // Now rewrite the body...
1601 lastCatchBody = catchList->getCatchBody();
Steve Naroff929c77e2008-02-01 20:02:07 +00001602 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1603 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner690c2872008-04-08 05:52:18 +00001604 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1605 "bogus @catch paren location");
Steve Naroff929c77e2008-02-01 20:02:07 +00001606 assert((*bodyBuf == '{') && "bogus @catch body location");
1607
1608 buf += "1) { id _tmp = _caught;";
Daniel Dunbar60987c92009-08-19 19:10:30 +00001609 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff0e8b96a2009-03-03 19:52:17 +00001610 } else if (catchDecl) {
1611 QualType t = catchDecl->getType();
Ted Kremenek42730c52008-01-07 19:49:32 +00001612 if (t == Context->getObjCIdType()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001613 buf += "1) { ";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001614 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001615 sawIdTypedCatch = true;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001616 } else if (const PointerType *pType = t->getAs<PointerType>()) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001617 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroffe9f69842007-11-07 04:08:17 +00001618
Ted Kremenek42730c52008-01-07 19:49:32 +00001619 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroffe9f69842007-11-07 04:08:17 +00001620 if (cls) {
Steve Naroffd3287d82007-11-07 18:43:40 +00001621 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattner271d4c22008-11-24 05:29:24 +00001622 buf += cls->getDecl()->getNameAsString();
Steve Naroffd3287d82007-11-07 18:43:40 +00001623 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001624 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001625 }
1626 }
1627 // Now rewrite the body...
1628 lastCatchBody = catchList->getCatchBody();
1629 SourceLocation rParenLoc = catchList->getRParenLoc();
1630 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1631 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1632 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1633 assert((*rParenBuf == ')') && "bogus @catch paren location");
1634 assert((*bodyBuf == '{') && "bogus @catch body location");
1635
1636 buf = " = _caught;";
1637 // Here we replace ") {" with "= _caught;" (which initializes and
1638 // declares the @catch parameter).
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001639 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff0e8b96a2009-03-03 19:52:17 +00001640 } else {
Steve Naroffe9f69842007-11-07 04:08:17 +00001641 assert(false && "@catch rewrite bug");
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001642 }
Steve Naroff929c77e2008-02-01 20:02:07 +00001643 // make sure all the catch bodies get rewritten!
Steve Naroffe9f69842007-11-07 04:08:17 +00001644 catchList = catchList->getNextCatchStmt();
1645 }
1646 // Complete the catch list...
1647 if (lastCatchBody) {
1648 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner690c2872008-04-08 05:52:18 +00001649 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1650 "bogus @catch body location");
Steve Naroffe9f69842007-11-07 04:08:17 +00001651
Steve Naroff31325c12008-09-11 15:29:03 +00001652 // Insert the last (implicit) else clause *before* the right curly brace.
1653 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1654 buf = "} /* last catch end */\n";
1655 buf += "else {\n";
1656 buf += " _rethrow = _caught;\n";
1657 buf += " objc_exception_try_exit(&_stack);\n";
1658 buf += "} } /* @catch end */\n";
1659 if (!S->getFinallyStmt())
1660 buf += "}\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001661 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001662
1663 // Set lastCurlyLoc
1664 lastCurlyLoc = lastCatchBody->getLocEnd();
1665 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001666 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001667 startLoc = finalStmt->getLocStart();
1668 startBuf = SM->getCharacterData(startLoc);
1669 assert((*startBuf == '@') && "bogus @finally start");
1670
1671 buf = "/* @finally */";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001672 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001673
1674 Stmt *body = finalStmt->getFinallyBody();
1675 SourceLocation startLoc = body->getLocStart();
1676 SourceLocation endLoc = body->getLocEnd();
Chris Lattner690c2872008-04-08 05:52:18 +00001677 assert(*SM->getCharacterData(startLoc) == '{' &&
1678 "bogus @finally body location");
1679 assert(*SM->getCharacterData(endLoc) == '}' &&
1680 "bogus @finally body location");
Steve Naroffe9f69842007-11-07 04:08:17 +00001681
1682 startLoc = startLoc.getFileLocWithOffset(1);
1683 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001684 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001685 endLoc = endLoc.getFileLocWithOffset(-1);
1686 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001687 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001688
1689 // Set lastCurlyLoc
1690 lastCurlyLoc = body->getLocEnd();
Steve Naroff43964fb2008-12-05 17:03:39 +00001691
1692 // Now check for any return/continue/go statements within the @try.
1693 WarnAboutReturnGotoContinueOrBreakStmts(S->getTryBody());
Steve Naroff31325c12008-09-11 15:29:03 +00001694 } else { /* no finally clause - make sure we synthesize an implicit one */
1695 buf = "{ /* implicit finally clause */\n";
1696 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1697 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1698 buf += "}";
1699 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001700 }
1701 // Now emit the final closing curly brace...
1702 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1703 buf = " } /* @try scope end */\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001704 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001705 return 0;
1706}
1707
Steve Naroff44e81222008-04-14 22:03:09 +00001708Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001709 return 0;
1710}
1711
Steve Naroff44e81222008-04-14 22:03:09 +00001712Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001713 return 0;
1714}
1715
Chris Lattnerb1548372008-01-31 19:37:57 +00001716// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001717// the throw expression is typically a message expression that's already
1718// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff44e81222008-04-14 22:03:09 +00001719Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001720 // Get the start location and compute the semi location.
1721 SourceLocation startLoc = S->getLocStart();
1722 const char *startBuf = SM->getCharacterData(startLoc);
1723
1724 assert((*startBuf == '@') && "bogus @throw location");
1725
1726 std::string buf;
1727 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffbe72efa2008-01-19 00:42:38 +00001728 if (S->getThrowExpr())
1729 buf = "objc_exception_throw(";
1730 else // add an implicit argument
1731 buf = "objc_exception_throw(_caught";
Steve Naroff3de6eaa2008-07-25 15:41:30 +00001732
1733 // handle "@ throw" correctly.
1734 const char *wBuf = strchr(startBuf, 'w');
1735 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1736 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1737
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001738 const char *semiBuf = strchr(startBuf, ';');
1739 assert((*semiBuf == ';') && "@throw: can't find ';'");
1740 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1741 buf = ");";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001742 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001743 return 0;
1744}
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001745
Steve Naroff44e81222008-04-14 22:03:09 +00001746Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +00001747 // Create a new string expression.
1748 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001749 std::string StrEncoding;
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00001750 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattneraa491192009-02-18 06:40:38 +00001751 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
1752 StrEncoding.length(), false,StrType,
1753 SourceLocation());
Chris Lattnerb1548372008-01-31 19:37:57 +00001754 ReplaceStmt(Exp, Replacement);
Chris Lattner258f26c2007-11-30 22:25:36 +00001755
Chris Lattner4478db92007-11-30 22:53:43 +00001756 // Replace this subexpr in the parent.
Steve Naroff102c3f22008-12-04 23:50:32 +00001757 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattner0021f452007-10-24 16:57:36 +00001758 return Replacement;
Chris Lattner6fe8b272007-10-16 22:36:42 +00001759}
1760
Steve Naroff44e81222008-04-14 22:03:09 +00001761Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff95f6bce2008-12-22 22:16:07 +00001762 if (!SelGetUidFunctionDecl)
1763 SynthSelGetUidFunctionDecl();
Steve Naroff296b74f2007-11-05 14:50:49 +00001764 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1765 // Create a call to sel_registerName("selName").
1766 llvm::SmallVector<Expr*, 8> SelExprs;
1767 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattneraa491192009-02-18 06:40:38 +00001768 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek4f530a92009-02-06 19:55:15 +00001769 Exp->getSelector().getAsString().c_str(),
Chris Lattner3a8f2942008-11-24 03:33:13 +00001770 Exp->getSelector().getAsString().size(),
Chris Lattnerc3144742009-02-18 05:49:11 +00001771 false, argType, SourceLocation()));
Steve Naroff296b74f2007-11-05 14:50:49 +00001772 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1773 &SelExprs[0], SelExprs.size());
Chris Lattnerb1548372008-01-31 19:37:57 +00001774 ReplaceStmt(Exp, SelExp);
Steve Naroff102c3f22008-12-04 23:50:32 +00001775 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff296b74f2007-11-05 14:50:49 +00001776 return SelExp;
1777}
1778
Steve Naroff44e81222008-04-14 22:03:09 +00001779CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff71226032007-10-24 22:48:43 +00001780 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffe9780582007-10-23 23:50:29 +00001781 // Get the type, we will need to reference it in a couple spots.
Steve Naroff71226032007-10-24 22:48:43 +00001782 QualType msgSendType = FD->getType();
Steve Naroffe9780582007-10-23 23:50:29 +00001783
1784 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek0c97e042009-02-07 01:47:29 +00001785 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffe9780582007-10-23 23:50:29 +00001786
1787 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerfce2c5a2007-10-24 17:06:59 +00001788 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson7ef181c2009-07-31 00:48:10 +00001789 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc,
1790 CastExpr::CK_Unknown,
1791 DRE,
Douglas Gregor70d26122008-11-12 17:17:38 +00001792 /*isLvalue=*/false);
Steve Naroffe9780582007-10-23 23:50:29 +00001793
1794 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattner0021f452007-10-24 16:57:36 +00001795
Ted Kremenek362abcd2009-02-09 20:51:47 +00001796 return new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
1797 SourceLocation());
Steve Naroff71226032007-10-24 22:48:43 +00001798}
1799
Steve Naroffc8a92d12007-11-01 13:24:47 +00001800static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1801 const char *&startRef, const char *&endRef) {
1802 while (startBuf < endBuf) {
1803 if (*startBuf == '<')
1804 startRef = startBuf; // mark the start.
1805 if (*startBuf == '>') {
Steve Naroff2aeae312007-11-09 12:50:28 +00001806 if (startRef && *startRef == '<') {
1807 endRef = startBuf; // mark the end.
1808 return true;
1809 }
1810 return false;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001811 }
1812 startBuf++;
1813 }
1814 return false;
1815}
1816
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001817static void scanToNextArgument(const char *&argRef) {
1818 int angle = 0;
1819 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1820 if (*argRef == '<')
1821 angle++;
1822 else if (*argRef == '>')
1823 angle--;
1824 argRef++;
1825 }
1826 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1827}
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001828
Steve Naroff44e81222008-04-14 22:03:09 +00001829bool RewriteObjC::needToScanForQualifiers(QualType T) {
Steve Naroff77763c52009-07-18 15:33:26 +00001830 return T->isObjCQualifiedIdType() || T->isObjCQualifiedInterfaceType();
Steve Naroffc8a92d12007-11-01 13:24:47 +00001831}
1832
Steve Naroffd06c88d2008-07-29 18:15:38 +00001833void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1834 QualType Type = E->getType();
1835 if (needToScanForQualifiers(Type)) {
Steve Narofff31ece92008-11-19 21:15:47 +00001836 SourceLocation Loc, EndLoc;
1837
1838 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1839 Loc = ECE->getLParenLoc();
1840 EndLoc = ECE->getRParenLoc();
1841 } else {
1842 Loc = E->getLocStart();
1843 EndLoc = E->getLocEnd();
1844 }
1845 // This will defend against trying to rewrite synthesized expressions.
1846 if (Loc.isInvalid() || EndLoc.isInvalid())
1847 return;
1848
Steve Naroffd06c88d2008-07-29 18:15:38 +00001849 const char *startBuf = SM->getCharacterData(Loc);
Steve Narofff31ece92008-11-19 21:15:47 +00001850 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroffd06c88d2008-07-29 18:15:38 +00001851 const char *startRef = 0, *endRef = 0;
1852 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1853 // Get the locations of the startRef, endRef.
1854 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1855 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1856 // Comment out the protocol references.
1857 InsertText(LessLoc, "/*", 2);
1858 InsertText(GreaterLoc, "*/", 2);
1859 }
1860 }
1861}
1862
Steve Naroff44e81222008-04-14 22:03:09 +00001863void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001864 SourceLocation Loc;
1865 QualType Type;
Douglas Gregor4fa58902009-02-26 23:50:07 +00001866 const FunctionProtoType *proto = 0;
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001867 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1868 Loc = VD->getLocation();
1869 Type = VD->getType();
1870 }
1871 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1872 Loc = FD->getLocation();
1873 // Check for ObjC 'id' and class types that have been adorned with protocol
1874 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1875 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1876 assert(funcType && "missing function type");
Douglas Gregor4fa58902009-02-26 23:50:07 +00001877 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001878 if (!proto)
1879 return;
1880 Type = proto->getResultType();
1881 }
1882 else
1883 return;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001884
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001885 if (needToScanForQualifiers(Type)) {
Steve Naroffc8a92d12007-11-01 13:24:47 +00001886 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001887
1888 const char *endBuf = SM->getCharacterData(Loc);
1889 const char *startBuf = endBuf;
Steve Naroffff2fa192008-05-31 05:02:17 +00001890 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffc8a92d12007-11-01 13:24:47 +00001891 startBuf--; // scan backward (from the decl location) for return type.
1892 const char *startRef = 0, *endRef = 0;
1893 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1894 // Get the locations of the startRef, endRef.
1895 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1896 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1897 // Comment out the protocol references.
Chris Lattner6216f292008-01-31 19:42:41 +00001898 InsertText(LessLoc, "/*", 2);
1899 InsertText(GreaterLoc, "*/", 2);
Steve Naroff05d6ff52007-10-31 04:38:33 +00001900 }
1901 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001902 if (!proto)
1903 return; // most likely, was a variable
Steve Naroffc8a92d12007-11-01 13:24:47 +00001904 // Now check arguments.
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001905 const char *startBuf = SM->getCharacterData(Loc);
1906 const char *startFuncBuf = startBuf;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001907 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1908 if (needToScanForQualifiers(proto->getArgType(i))) {
1909 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001910
Steve Naroffc8a92d12007-11-01 13:24:47 +00001911 const char *endBuf = startBuf;
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001912 // scan forward (from the decl location) for argument types.
1913 scanToNextArgument(endBuf);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001914 const char *startRef = 0, *endRef = 0;
1915 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1916 // Get the locations of the startRef, endRef.
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001917 SourceLocation LessLoc =
1918 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1919 SourceLocation GreaterLoc =
1920 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001921 // Comment out the protocol references.
Chris Lattner6216f292008-01-31 19:42:41 +00001922 InsertText(LessLoc, "/*", 2);
1923 InsertText(GreaterLoc, "*/", 2);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001924 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001925 startBuf = ++endBuf;
1926 }
1927 else {
Steve Naroff6a1d88b2008-08-06 15:58:23 +00001928 // If the function name is derived from a macro expansion, then the
1929 // argument buffer will not follow the name. Need to speak with Chris.
1930 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001931 startBuf++; // scan forward (from the decl location) for argument types.
1932 startBuf++;
1933 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001934 }
Steve Naroff05d6ff52007-10-31 04:38:33 +00001935}
1936
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001937// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff44e81222008-04-14 22:03:09 +00001938void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001939 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1940 llvm::SmallVector<QualType, 16> ArgTys;
1941 ArgTys.push_back(Context->getPointerType(
1942 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001943 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001944 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001945 false /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001946 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001947 SourceLocation(),
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00001948 SelGetUidIdent, getFuncType, 0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001949 FunctionDecl::Extern, false);
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001950}
1951
Steve Naroff44e81222008-04-14 22:03:09 +00001952void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001953 // declared in <objc/objc.h>
Douglas Gregor7339c9e2009-01-09 01:47:02 +00001954 if (FD->getIdentifier() &&
1955 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001956 SelGetUidFunctionDecl = FD;
Steve Naroff05d6ff52007-10-31 04:38:33 +00001957 return;
1958 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001959 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff02a82aa2007-10-30 23:14:51 +00001960}
1961
Steve Naroffbec4bf52008-03-11 17:37:02 +00001962// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff44e81222008-04-14 22:03:09 +00001963void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffbec4bf52008-03-11 17:37:02 +00001964 if (SuperContructorFunctionDecl)
1965 return;
Steve Naroff12673622008-12-23 20:11:22 +00001966 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroffbec4bf52008-03-11 17:37:02 +00001967 llvm::SmallVector<QualType, 16> ArgTys;
1968 QualType argT = Context->getObjCIdType();
1969 assert(!argT.isNull() && "Can't find 'id' type");
1970 ArgTys.push_back(argT);
1971 ArgTys.push_back(argT);
1972 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1973 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001974 false, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001975 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001976 SourceLocation(),
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00001977 msgSendIdent, msgSendType, 0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001978 FunctionDecl::Extern, false);
Steve Naroffbec4bf52008-03-11 17:37:02 +00001979}
1980
Steve Naroff02a82aa2007-10-30 23:14:51 +00001981// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001982void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001983 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1984 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001985 QualType argT = Context->getObjCIdType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001986 assert(!argT.isNull() && "Can't find 'id' type");
1987 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001988 argT = Context->getObjCSelType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001989 assert(!argT.isNull() && "Can't find 'SEL' type");
1990 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001991 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001992 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001993 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001994 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001995 SourceLocation(),
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00001996 msgSendIdent, msgSendType, 0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001997 FunctionDecl::Extern, false);
Steve Naroff02a82aa2007-10-30 23:14:51 +00001998}
1999
Steve Naroff764c1ae2007-11-15 10:28:18 +00002000// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00002001void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff764c1ae2007-11-15 10:28:18 +00002002 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2003 llvm::SmallVector<QualType, 16> ArgTys;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002004 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002005 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00002006 &Context->Idents.get("objc_super"));
Steve Naroff764c1ae2007-11-15 10:28:18 +00002007 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2008 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2009 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002010 argT = Context->getObjCSelType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00002011 assert(!argT.isNull() && "Can't find 'SEL' type");
2012 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002013 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00002014 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002015 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002016 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002017 SourceLocation(),
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00002018 msgSendIdent, msgSendType, 0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002019 FunctionDecl::Extern, false);
Steve Naroff764c1ae2007-11-15 10:28:18 +00002020}
2021
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002022// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00002023void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002024 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2025 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00002026 QualType argT = Context->getObjCIdType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002027 assert(!argT.isNull() && "Can't find 'id' type");
2028 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002029 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002030 assert(!argT.isNull() && "Can't find 'SEL' type");
2031 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002032 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002033 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002034 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002035 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002036 SourceLocation(),
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00002037 msgSendIdent, msgSendType, 0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002038 FunctionDecl::Extern, false);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002039}
2040
2041// SynthMsgSendSuperStretFunctionDecl -
2042// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00002043void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002044 IdentifierInfo *msgSendIdent =
2045 &Context->Idents.get("objc_msgSendSuper_stret");
2046 llvm::SmallVector<QualType, 16> ArgTys;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002047 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002048 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00002049 &Context->Idents.get("objc_super"));
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002050 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2051 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2052 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002053 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002054 assert(!argT.isNull() && "Can't find 'SEL' type");
2055 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002056 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002057 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002058 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002059 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner4c7802b2008-03-15 21:24:04 +00002060 SourceLocation(),
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00002061 msgSendIdent, msgSendType, 0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002062 FunctionDecl::Extern, false);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002063}
2064
Steve Naroff31316a12008-05-08 22:02:18 +00002065// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00002066void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002067 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2068 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00002069 QualType argT = Context->getObjCIdType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002070 assert(!argT.isNull() && "Can't find 'id' type");
2071 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002072 argT = Context->getObjCSelType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002073 assert(!argT.isNull() && "Can't find 'SEL' type");
2074 ArgTys.push_back(argT);
Steve Naroff31316a12008-05-08 22:02:18 +00002075 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002076 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002077 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002078 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002079 SourceLocation(),
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00002080 msgSendIdent, msgSendType, 0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002081 FunctionDecl::Extern, false);
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002082}
2083
Steve Naroff02a82aa2007-10-30 23:14:51 +00002084// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff44e81222008-04-14 22:03:09 +00002085void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff02a82aa2007-10-30 23:14:51 +00002086 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2087 llvm::SmallVector<QualType, 16> ArgTys;
2088 ArgTys.push_back(Context->getPointerType(
2089 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00002090 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00002091 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002092 false /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002093 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002094 SourceLocation(),
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00002095 getClassIdent, getClassType, 0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002096 FunctionDecl::Extern, false);
Steve Naroff02a82aa2007-10-30 23:14:51 +00002097}
2098
Steve Naroff3b1caac2007-12-07 03:50:46 +00002099// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff44e81222008-04-14 22:03:09 +00002100void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff3b1caac2007-12-07 03:50:46 +00002101 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2102 llvm::SmallVector<QualType, 16> ArgTys;
2103 ArgTys.push_back(Context->getPointerType(
2104 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00002105 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00002106 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002107 false /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002108 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002109 SourceLocation(),
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00002110 getClassIdent, getClassType, 0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002111 FunctionDecl::Extern, false);
Steve Naroff3b1caac2007-12-07 03:50:46 +00002112}
2113
Steve Naroff44e81222008-04-14 22:03:09 +00002114Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff47e7fa22008-03-15 00:55:56 +00002115 QualType strType = getConstantStringStructType();
2116
2117 std::string S = "__NSConstantStringImpl_";
Steve Naroffa1f00992008-05-31 03:35:42 +00002118
2119 std::string tmpName = InFileName;
2120 unsigned i;
2121 for (i=0; i < tmpName.length(); i++) {
2122 char c = tmpName.at(i);
2123 // replace any non alphanumeric characters with '_'.
2124 if (!isalpha(c) && (c < '0' || c > '9'))
2125 tmpName[i] = '_';
2126 }
2127 S += tmpName;
2128 S += "_";
Steve Naroff47e7fa22008-03-15 00:55:56 +00002129 S += utostr(NumObjCStringLiterals++);
2130
Steve Narofffef037c2008-03-27 22:29:16 +00002131 Preamble += "static __NSConstantStringImpl " + S;
2132 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2133 Preamble += "0x000007c8,"; // utf8_str
Steve Naroff47e7fa22008-03-15 00:55:56 +00002134 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek7b6f67b2008-09-13 05:16:45 +00002135 std::string prettyBufS;
2136 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattner7099c782009-06-30 01:26:17 +00002137 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2138 PrintingPolicy(LangOpts));
Steve Narofffef037c2008-03-27 22:29:16 +00002139 Preamble += prettyBuf.str();
2140 Preamble += ",";
Steve Naroff64bce352008-03-15 01:36:04 +00002141 // The minus 2 removes the begin/end double quotes.
Steve Narofffef037c2008-03-27 22:29:16 +00002142 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroff47e7fa22008-03-15 00:55:56 +00002143
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002144 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00002145 &Context->Idents.get(S.c_str()), strType, 0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002146 VarDecl::Static);
Ted Kremenek0c97e042009-02-07 01:47:29 +00002147 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2148 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Steve Naroff47e7fa22008-03-15 00:55:56 +00002149 Context->getPointerType(DRE->getType()),
2150 SourceLocation());
Steve Naroffabb96362007-11-08 14:30:50 +00002151 // cast to NSConstantString *
Anders Carlsson7ef181c2009-07-31 00:48:10 +00002152 CastExpr *cast = new (Context) CStyleCastExpr(Exp->getType(),
2153 CastExpr::CK_Unknown,
2154 Unop, Exp->getType(),
2155 SourceLocation(),
2156 SourceLocation());
Chris Lattnerb1548372008-01-31 19:37:57 +00002157 ReplaceStmt(Exp, cast);
Steve Naroff102c3f22008-12-04 23:50:32 +00002158 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffabb96362007-11-08 14:30:50 +00002159 return cast;
Steve Naroff0add5d22007-11-03 11:27:19 +00002160}
2161
Steve Naroff44e81222008-04-14 22:03:09 +00002162ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff3b1caac2007-12-07 03:50:46 +00002163 // check if we are sending a message to 'super'
Douglas Gregor5d764842009-01-09 17:18:27 +00002164 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Chris Lattnere4650482008-03-15 06:12:44 +00002165
Douglas Gregord8606632008-11-04 14:56:14 +00002166 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
Steve Naroff329ec222009-07-10 23:34:53 +00002167 const ObjCObjectPointerType *OPT =
2168 Super->getType()->getAsObjCObjectPointerType();
2169 assert(OPT);
2170 const ObjCInterfaceType *IT = OPT->getInterfaceType();
Chris Lattner4423d372008-06-21 18:04:54 +00002171 return IT->getDecl();
2172 }
2173 return 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +00002174}
2175
2176// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff44e81222008-04-14 22:03:09 +00002177QualType RewriteObjC::getSuperStructType() {
Steve Naroff764c1ae2007-11-15 10:28:18 +00002178 if (!SuperStructDecl) {
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002179 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner58114f02008-03-15 21:32:50 +00002180 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00002181 &Context->Idents.get("objc_super"));
Steve Naroff764c1ae2007-11-15 10:28:18 +00002182 QualType FieldTypes[2];
2183
2184 // struct objc_object *receiver;
Ted Kremenek42730c52008-01-07 19:49:32 +00002185 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00002186 // struct objc_class *super;
Ted Kremenek42730c52008-01-07 19:49:32 +00002187 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor8acb7272008-12-11 16:49:14 +00002188
Steve Naroff764c1ae2007-11-15 10:28:18 +00002189 // Create fields
Douglas Gregor8acb7272008-12-11 16:49:14 +00002190 for (unsigned i = 0; i < 2; ++i) {
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002191 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
Douglas Gregor8acb7272008-12-11 16:49:14 +00002192 SourceLocation(), 0,
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00002193 FieldTypes[i], 0,
2194 /*BitWidth=*/0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002195 /*Mutable=*/false));
Douglas Gregor8acb7272008-12-11 16:49:14 +00002196 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00002197
Douglas Gregor8acb7272008-12-11 16:49:14 +00002198 SuperStructDecl->completeDefinition(*Context);
Steve Naroff764c1ae2007-11-15 10:28:18 +00002199 }
2200 return Context->getTagDeclType(SuperStructDecl);
2201}
2202
Steve Naroff44e81222008-04-14 22:03:09 +00002203QualType RewriteObjC::getConstantStringStructType() {
Steve Naroff47e7fa22008-03-15 00:55:56 +00002204 if (!ConstantStringDecl) {
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002205 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner58114f02008-03-15 21:32:50 +00002206 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00002207 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroff47e7fa22008-03-15 00:55:56 +00002208 QualType FieldTypes[4];
2209
2210 // struct objc_object *receiver;
2211 FieldTypes[0] = Context->getObjCIdType();
2212 // int flags;
2213 FieldTypes[1] = Context->IntTy;
2214 // char *str;
2215 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2216 // long length;
2217 FieldTypes[3] = Context->LongTy;
Douglas Gregor8acb7272008-12-11 16:49:14 +00002218
Steve Naroff47e7fa22008-03-15 00:55:56 +00002219 // Create fields
Douglas Gregor8acb7272008-12-11 16:49:14 +00002220 for (unsigned i = 0; i < 4; ++i) {
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002221 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
Douglas Gregor8acb7272008-12-11 16:49:14 +00002222 ConstantStringDecl,
2223 SourceLocation(), 0,
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00002224 FieldTypes[i], 0,
Douglas Gregor8acb7272008-12-11 16:49:14 +00002225 /*BitWidth=*/0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002226 /*Mutable=*/true));
Douglas Gregor8acb7272008-12-11 16:49:14 +00002227 }
2228
2229 ConstantStringDecl->completeDefinition(*Context);
Steve Naroff47e7fa22008-03-15 00:55:56 +00002230 }
2231 return Context->getTagDeclType(ConstantStringDecl);
2232}
2233
Steve Naroff44e81222008-04-14 22:03:09 +00002234Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00002235 if (!SelGetUidFunctionDecl)
2236 SynthSelGetUidFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00002237 if (!MsgSendFunctionDecl)
2238 SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +00002239 if (!MsgSendSuperFunctionDecl)
2240 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002241 if (!MsgSendStretFunctionDecl)
2242 SynthMsgSendStretFunctionDecl();
2243 if (!MsgSendSuperStretFunctionDecl)
2244 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002245 if (!MsgSendFpretFunctionDecl)
2246 SynthMsgSendFpretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00002247 if (!GetClassFunctionDecl)
2248 SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +00002249 if (!GetMetaClassFunctionDecl)
2250 SynthGetMetaClassFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002251
Steve Naroff764c1ae2007-11-15 10:28:18 +00002252 // default to objc_msgSend().
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002253 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2254 // May need to use objc_msgSend_stret() as well.
2255 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff450d2fc2009-04-29 16:37:50 +00002256 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2257 QualType resultType = mDecl->getResultType();
Chris Lattnerb724ab22008-07-26 22:36:27 +00002258 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002259 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattnerb724ab22008-07-26 22:36:27 +00002260 else if (resultType->isRealFloatingType())
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002261 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002262 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00002263
Steve Naroff71226032007-10-24 22:48:43 +00002264 // Synthesize a call to objc_msgSend().
2265 llvm::SmallVector<Expr*, 8> MsgExprs;
2266 IdentifierInfo *clsName = Exp->getClassName();
2267
2268 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2269 if (clsName) { // class message.
Steve Naroff91a69202008-07-24 19:44:33 +00002270 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2271 // the 'super' idiom within a class method.
Steve Naroff3b1caac2007-12-07 03:50:46 +00002272 if (!strcmp(clsName->getName(), "super")) {
2273 MsgSendFlavor = MsgSendSuperFunctionDecl;
2274 if (MsgSendStretFlavor)
2275 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2276 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2277
Ted Kremenek42730c52008-01-07 19:49:32 +00002278 ObjCInterfaceDecl *SuperDecl =
Steve Naroff38a9e3f2008-10-27 17:20:55 +00002279 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff3b1caac2007-12-07 03:50:46 +00002280
2281 llvm::SmallVector<Expr*, 4> InitExprs;
2282
2283 // set the receiver to self, the first argument to all methods.
Steve Naroff450d2fc2009-04-29 16:37:50 +00002284 InitExprs.push_back(
2285 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlsson7ef181c2009-07-31 00:48:10 +00002286 CastExpr::CK_Unknown,
Steve Naroff450d2fc2009-04-29 16:37:50 +00002287 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2288 Context->getObjCIdType(),
2289 SourceLocation()),
2290 Context->getObjCIdType(),
2291 SourceLocation(), SourceLocation())); // set the 'receiver'.
2292
Steve Naroff3b1caac2007-12-07 03:50:46 +00002293 llvm::SmallVector<Expr*, 8> ClsExprs;
2294 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattneraa491192009-02-18 06:40:38 +00002295 ClsExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek4f530a92009-02-06 19:55:15 +00002296 SuperDecl->getIdentifier()->getName(),
2297 SuperDecl->getIdentifier()->getLength(),
Chris Lattnerc3144742009-02-18 05:49:11 +00002298 false, argType, SourceLocation()));
Steve Naroff3b1caac2007-12-07 03:50:46 +00002299 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2300 &ClsExprs[0],
2301 ClsExprs.size());
2302 // To turn off a warning, type-cast to 'id'
Douglas Gregor21a04f32008-10-27 19:41:14 +00002303 InitExprs.push_back( // set 'super class', using objc_getClass().
Ted Kremenek0c97e042009-02-07 01:47:29 +00002304 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlsson7ef181c2009-07-31 00:48:10 +00002305 CastExpr::CK_Unknown,
Douglas Gregor21a04f32008-10-27 19:41:14 +00002306 Cls, Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002307 SourceLocation(), SourceLocation()));
Steve Naroff3b1caac2007-12-07 03:50:46 +00002308 // struct objc_super
2309 QualType superType = getSuperStructType();
Steve Naroffdee066b2008-03-11 18:14:26 +00002310 Expr *SuperRep;
Steve Naroffbec4bf52008-03-11 17:37:02 +00002311
Steve Naroffdee066b2008-03-11 18:14:26 +00002312 if (LangOpts.Microsoft) {
2313 SynthSuperContructorFunctionDecl();
2314 // Simulate a contructor call...
Ted Kremenek0c97e042009-02-07 01:47:29 +00002315 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroffdee066b2008-03-11 18:14:26 +00002316 superType, SourceLocation());
Ted Kremenek362abcd2009-02-09 20:51:47 +00002317 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2318 InitExprs.size(),
2319 superType, SourceLocation());
Steve Naroff12673622008-12-23 20:11:22 +00002320 // The code for super is a little tricky to prevent collision with
2321 // the structure definition in the header. The rewriter has it's own
2322 // internal definition (__rw_objc_super) that is uses. This is why
2323 // we need the cast below. For example:
2324 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2325 //
Ted Kremenek0c97e042009-02-07 01:47:29 +00002326 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Steve Naroff12673622008-12-23 20:11:22 +00002327 Context->getPointerType(SuperRep->getType()),
2328 SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00002329 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Anders Carlsson7ef181c2009-07-31 00:48:10 +00002330 CastExpr::CK_Unknown, SuperRep,
2331 Context->getPointerType(superType),
Steve Naroff12673622008-12-23 20:11:22 +00002332 SourceLocation(), SourceLocation());
Steve Naroffdee066b2008-03-11 18:14:26 +00002333 } else {
2334 // (struct objc_super) { <exprs from above> }
Ted Kremenek0c97e042009-02-07 01:47:29 +00002335 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
Steve Naroffdee066b2008-03-11 18:14:26 +00002336 &InitExprs[0], InitExprs.size(),
Douglas Gregorf603b472009-01-28 21:54:33 +00002337 SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00002338 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE,
Chris Lattner71ca8c82008-10-26 23:43:26 +00002339 false);
Steve Naroff12673622008-12-23 20:11:22 +00002340 // struct objc_super *
Ted Kremenek0c97e042009-02-07 01:47:29 +00002341 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Steve Naroff12673622008-12-23 20:11:22 +00002342 Context->getPointerType(SuperRep->getType()),
2343 SourceLocation());
Steve Naroffdee066b2008-03-11 18:14:26 +00002344 }
Steve Naroff12673622008-12-23 20:11:22 +00002345 MsgExprs.push_back(SuperRep);
Steve Naroff3b1caac2007-12-07 03:50:46 +00002346 } else {
2347 llvm::SmallVector<Expr*, 8> ClsExprs;
2348 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattneraa491192009-02-18 06:40:38 +00002349 ClsExprs.push_back(StringLiteral::Create(*Context,
2350 clsName->getName(),
2351 clsName->getLength(),
2352 false, argType,
2353 SourceLocation()));
Steve Naroff3b1caac2007-12-07 03:50:46 +00002354 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2355 &ClsExprs[0],
2356 ClsExprs.size());
2357 MsgExprs.push_back(Cls);
2358 }
Steve Naroff885e2122007-11-14 23:54:14 +00002359 } else { // instance message.
2360 Expr *recExpr = Exp->getReceiver();
Steve Naroff764c1ae2007-11-15 10:28:18 +00002361
Ted Kremenek42730c52008-01-07 19:49:32 +00002362 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00002363 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002364 if (MsgSendStretFlavor)
2365 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +00002366 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2367
2368 llvm::SmallVector<Expr*, 4> InitExprs;
2369
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002370 InitExprs.push_back(
Ted Kremenek0c97e042009-02-07 01:47:29 +00002371 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlsson7ef181c2009-07-31 00:48:10 +00002372 CastExpr::CK_Unknown,
Ted Kremenek0c97e042009-02-07 01:47:29 +00002373 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff23528612008-07-16 22:35:27 +00002374 Context->getObjCIdType(),
Douglas Gregor21a04f32008-10-27 19:41:14 +00002375 SourceLocation()),
2376 Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002377 SourceLocation(), SourceLocation())); // set the 'receiver'.
Steve Naroff764c1ae2007-11-15 10:28:18 +00002378
2379 llvm::SmallVector<Expr*, 8> ClsExprs;
2380 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattneraa491192009-02-18 06:40:38 +00002381 ClsExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek4f530a92009-02-06 19:55:15 +00002382 SuperDecl->getIdentifier()->getName(),
2383 SuperDecl->getIdentifier()->getLength(),
Chris Lattnerc3144742009-02-18 05:49:11 +00002384 false, argType, SourceLocation()));
Steve Naroff764c1ae2007-11-15 10:28:18 +00002385 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002386 &ClsExprs[0],
2387 ClsExprs.size());
Fariborz Jahanianfabf3bf2007-12-05 17:29:46 +00002388 // To turn off a warning, type-cast to 'id'
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002389 InitExprs.push_back(
Douglas Gregor21a04f32008-10-27 19:41:14 +00002390 // set 'super class', using objc_getClass().
Ted Kremenek0c97e042009-02-07 01:47:29 +00002391 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlsson7ef181c2009-07-31 00:48:10 +00002392 CastExpr::CK_Unknown,
Steve Naroff7f1412d2008-11-03 23:29:32 +00002393 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff764c1ae2007-11-15 10:28:18 +00002394 // struct objc_super
2395 QualType superType = getSuperStructType();
Steve Naroffbec4bf52008-03-11 17:37:02 +00002396 Expr *SuperRep;
2397
2398 if (LangOpts.Microsoft) {
2399 SynthSuperContructorFunctionDecl();
2400 // Simulate a contructor call...
Ted Kremenek0c97e042009-02-07 01:47:29 +00002401 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroffbec4bf52008-03-11 17:37:02 +00002402 superType, SourceLocation());
Ted Kremenek362abcd2009-02-09 20:51:47 +00002403 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2404 InitExprs.size(),
2405 superType, SourceLocation());
Steve Naroff12673622008-12-23 20:11:22 +00002406 // The code for super is a little tricky to prevent collision with
2407 // the structure definition in the header. The rewriter has it's own
2408 // internal definition (__rw_objc_super) that is uses. This is why
2409 // we need the cast below. For example:
2410 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2411 //
Ted Kremenek0c97e042009-02-07 01:47:29 +00002412 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Steve Naroff12673622008-12-23 20:11:22 +00002413 Context->getPointerType(SuperRep->getType()),
2414 SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00002415 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Anders Carlsson7ef181c2009-07-31 00:48:10 +00002416 CastExpr::CK_Unknown,
Steve Naroff12673622008-12-23 20:11:22 +00002417 SuperRep, Context->getPointerType(superType),
2418 SourceLocation(), SourceLocation());
Steve Naroffbec4bf52008-03-11 17:37:02 +00002419 } else {
2420 // (struct objc_super) { <exprs from above> }
Ted Kremenek0c97e042009-02-07 01:47:29 +00002421 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
Steve Naroffbec4bf52008-03-11 17:37:02 +00002422 &InitExprs[0], InitExprs.size(),
Douglas Gregorf603b472009-01-28 21:54:33 +00002423 SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00002424 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
Steve Naroffbec4bf52008-03-11 17:37:02 +00002425 }
Steve Naroff12673622008-12-23 20:11:22 +00002426 MsgExprs.push_back(SuperRep);
Steve Naroff764c1ae2007-11-15 10:28:18 +00002427 } else {
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00002428 // Remove all type-casts because it may contain objc-style types; e.g.
2429 // Foo<Proto> *.
Douglas Gregor035d0882008-10-28 15:36:24 +00002430 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00002431 recExpr = CE->getSubExpr();
Anders Carlsson7ef181c2009-07-31 00:48:10 +00002432 recExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
2433 CastExpr::CK_Unknown, recExpr,
Douglas Gregor21a04f32008-10-27 19:41:14 +00002434 Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002435 SourceLocation(), SourceLocation());
Steve Naroff764c1ae2007-11-15 10:28:18 +00002436 MsgExprs.push_back(recExpr);
2437 }
Steve Naroff885e2122007-11-14 23:54:14 +00002438 }
Steve Naroff0add5d22007-11-03 11:27:19 +00002439 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff71226032007-10-24 22:48:43 +00002440 llvm::SmallVector<Expr*, 8> SelExprs;
2441 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattneraa491192009-02-18 06:40:38 +00002442 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek4f530a92009-02-06 19:55:15 +00002443 Exp->getSelector().getAsString().c_str(),
Chris Lattner3a8f2942008-11-24 03:33:13 +00002444 Exp->getSelector().getAsString().size(),
Chris Lattnerc3144742009-02-18 05:49:11 +00002445 false, argType, SourceLocation()));
Steve Naroff71226032007-10-24 22:48:43 +00002446 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2447 &SelExprs[0], SelExprs.size());
2448 MsgExprs.push_back(SelExp);
2449
2450 // Now push any user supplied arguments.
2451 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff885e2122007-11-14 23:54:14 +00002452 Expr *userExpr = Exp->getArg(i);
Steve Naroff6b759ce2007-11-15 02:58:25 +00002453 // Make all implicit casts explicit...ICE comes in handy:-)
2454 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2455 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor21a04f32008-10-27 19:41:14 +00002456 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremenek42730c52008-01-07 19:49:32 +00002457 ? Context->getObjCIdType()
Douglas Gregor21a04f32008-10-27 19:41:14 +00002458 : ICE->getType();
Anders Carlsson7ef181c2009-07-31 00:48:10 +00002459 userExpr = new (Context) CStyleCastExpr(type, CastExpr::CK_Unknown,
2460 userExpr, type, SourceLocation(),
2461 SourceLocation());
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002462 }
2463 // Make id<P...> cast into an 'id' cast.
Douglas Gregor035d0882008-10-28 15:36:24 +00002464 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002465 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor035d0882008-10-28 15:36:24 +00002466 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002467 userExpr = CE->getSubExpr();
Ted Kremenek0c97e042009-02-07 01:47:29 +00002468 userExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlsson7ef181c2009-07-31 00:48:10 +00002469 CastExpr::CK_Unknown,
Douglas Gregor21a04f32008-10-27 19:41:14 +00002470 userExpr, Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002471 SourceLocation(), SourceLocation());
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002472 }
Steve Naroff6b759ce2007-11-15 02:58:25 +00002473 }
Steve Naroff885e2122007-11-14 23:54:14 +00002474 MsgExprs.push_back(userExpr);
Steve Naroff450d2fc2009-04-29 16:37:50 +00002475 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2476 // out the argument in the original expression (since we aren't deleting
2477 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2478 //Exp->setArg(i, 0);
Steve Naroff71226032007-10-24 22:48:43 +00002479 }
Steve Naroff0744c472007-11-04 22:37:50 +00002480 // Generate the funky cast.
2481 CastExpr *cast;
2482 llvm::SmallVector<QualType, 8> ArgTypes;
2483 QualType returnType;
2484
2485 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff0c04bb62007-11-15 10:43:57 +00002486 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2487 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2488 else
Ted Kremenek42730c52008-01-07 19:49:32 +00002489 ArgTypes.push_back(Context->getObjCIdType());
2490 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner5c6b2c62009-02-20 18:43:26 +00002491 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroff0744c472007-11-04 22:37:50 +00002492 // Push any user argument types.
Chris Lattner5c6b2c62009-02-20 18:43:26 +00002493 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2494 E = OMD->param_end(); PI != E; ++PI) {
2495 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Ted Kremenek42730c52008-01-07 19:49:32 +00002496 ? Context->getObjCIdType()
Chris Lattner5c6b2c62009-02-20 18:43:26 +00002497 : (*PI)->getType();
Steve Naroff66c842f2008-10-29 14:49:46 +00002498 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffd896f4b2008-12-11 21:05:33 +00002499 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002500 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff66c842f2008-10-29 14:49:46 +00002501 t = Context->getPointerType(BPT->getPointeeType());
2502 }
Steve Naroff4242b972007-11-05 14:36:37 +00002503 ArgTypes.push_back(t);
2504 }
Chris Lattner5c6b2c62009-02-20 18:43:26 +00002505 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2506 ? Context->getObjCIdType() : OMD->getResultType();
Steve Naroff0744c472007-11-04 22:37:50 +00002507 } else {
Ted Kremenek42730c52008-01-07 19:49:32 +00002508 returnType = Context->getObjCIdType();
Steve Naroff0744c472007-11-04 22:37:50 +00002509 }
2510 // Get the type, we will need to reference it in a couple spots.
Steve Naroff764c1ae2007-11-15 10:28:18 +00002511 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroff0744c472007-11-04 22:37:50 +00002512
2513 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002514 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002515 SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00002516
2517 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2518 // If we don't do this cast, we get the following bizarre warning/note:
2519 // xx.m:13: warning: function called through a non-compatible type
2520 // xx.m:13: note: if this code is reached, the program will abort
Anders Carlsson7ef181c2009-07-31 00:48:10 +00002521 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy),
2522 CastExpr::CK_Unknown, DRE,
Douglas Gregor21a04f32008-10-27 19:41:14 +00002523 Context->getPointerType(Context->VoidTy),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002524 SourceLocation(), SourceLocation());
Steve Naroff29fe7462007-11-15 12:35:21 +00002525
Steve Naroff0744c472007-11-04 22:37:50 +00002526 // Now do the "normal" pointer to function cast.
2527 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00002528 &ArgTypes[0], ArgTypes.size(),
Steve Naroff3b8b4e32008-03-18 02:02:04 +00002529 // If we don't have a method decl, force a variadic cast.
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002530 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroff0744c472007-11-04 22:37:50 +00002531 castType = Context->getPointerType(castType);
Anders Carlsson7ef181c2009-07-31 00:48:10 +00002532 cast = new (Context) CStyleCastExpr(castType, CastExpr::CK_Unknown, cast,
2533 castType, SourceLocation(),
2534 SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00002535
2536 // Don't forget the parens to enforce the proper binding.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002537 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Steve Naroff0744c472007-11-04 22:37:50 +00002538
2539 const FunctionType *FT = msgSendType->getAsFunctionType();
Ted Kremenek362abcd2009-02-09 20:51:47 +00002540 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2541 MsgExprs.size(),
2542 FT->getResultType(), SourceLocation());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002543 Stmt *ReplacingStmt = CE;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002544 if (MsgSendStretFlavor) {
2545 // We have the method which returns a struct/union. Must also generate
2546 // call to objc_msgSend_stret and hang both varieties on a conditional
2547 // expression which dictate which one to envoke depending on size of
2548 // method's return type.
2549
2550 // Create a reference to the objc_msgSend_stret() declaration.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002551 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002552 SourceLocation());
2553 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Anders Carlsson7ef181c2009-07-31 00:48:10 +00002554 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy),
2555 CastExpr::CK_Unknown, STDRE,
Douglas Gregor21a04f32008-10-27 19:41:14 +00002556 Context->getPointerType(Context->VoidTy),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002557 SourceLocation(), SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002558 // Now do the "normal" pointer to function cast.
2559 castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00002560 &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002561 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002562 castType = Context->getPointerType(castType);
Anders Carlsson7ef181c2009-07-31 00:48:10 +00002563 cast = new (Context) CStyleCastExpr(castType, CastExpr::CK_Unknown,
2564 cast, castType, SourceLocation(), SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002565
2566 // Don't forget the parens to enforce the proper binding.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002567 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002568
2569 FT = msgSendType->getAsFunctionType();
Ted Kremenek362abcd2009-02-09 20:51:47 +00002570 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2571 MsgExprs.size(),
2572 FT->getResultType(), SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002573
2574 // Build sizeof(returnType)
Douglas Gregor396f1142009-03-13 21:01:28 +00002575 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
2576 returnType,
Sebastian Redl0cb7c872008-11-11 17:56:53 +00002577 Context->getSizeType(),
2578 SourceLocation(), SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002579 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2580 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2581 // For X86 it is more complicated and some kind of target specific routine
2582 // is needed to decide what to do.
Chris Lattner8cd0e932008-03-05 18:54:05 +00002583 unsigned IntSize =
2584 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Ted Kremenek0c97e042009-02-07 01:47:29 +00002585 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002586 Context->IntTy,
2587 SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00002588 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002589 BinaryOperator::LE,
2590 Context->IntTy,
2591 SourceLocation());
2592 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2593 ConditionalOperator *CondExpr =
Douglas Gregor34619872009-08-26 14:37:04 +00002594 new (Context) ConditionalOperator(lessThanExpr,
2595 SourceLocation(), CE,
2596 SourceLocation(), STCE, returnType);
Ted Kremenek0c97e042009-02-07 01:47:29 +00002597 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002598 }
Steve Naroff450d2fc2009-04-29 16:37:50 +00002599 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002600 return ReplacingStmt;
2601}
2602
Steve Naroff44e81222008-04-14 22:03:09 +00002603Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002604 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroffe8efe892008-10-27 20:54:44 +00002605
Steve Naroff71226032007-10-24 22:48:43 +00002606 // Now do the actual rewrite.
Chris Lattnerb1548372008-01-31 19:37:57 +00002607 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff71226032007-10-24 22:48:43 +00002608
Steve Naroff102c3f22008-12-04 23:50:32 +00002609 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002610 return ReplacingStmt;
Steve Naroffe9780582007-10-23 23:50:29 +00002611}
2612
Steve Naroff450d2fc2009-04-29 16:37:50 +00002613// typedef struct objc_object Protocol;
2614QualType RewriteObjC::getProtocolType() {
2615 if (!ProtocolTypeDecl) {
2616 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
2617 SourceLocation(),
2618 &Context->Idents.get("Protocol"),
2619 Context->getObjCIdType());
2620 }
2621 return Context->getTypeDeclType(ProtocolTypeDecl);
2622}
2623
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002624/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff450d2fc2009-04-29 16:37:50 +00002625/// a synthesized/forward data reference (to the protocol's metadata).
2626/// The forward references (and metadata) are generated in
2627/// RewriteObjC::HandleTranslationUnit().
Steve Naroff44e81222008-04-14 22:03:09 +00002628Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff450d2fc2009-04-29 16:37:50 +00002629 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
2630 IdentifierInfo *ID = &Context->Idents.get(Name);
2631 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00002632 ID, QualType()/*UNUSED*/, 0, VarDecl::Extern);
Steve Naroff450d2fc2009-04-29 16:37:50 +00002633 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
2634 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
2635 Context->getPointerType(DRE->getType()),
2636 SourceLocation());
Anders Carlsson7ef181c2009-07-31 00:48:10 +00002637 CastExpr *castExpr = new (Context) CStyleCastExpr(DerefExpr->getType(),
2638 CastExpr::CK_Unknown,
2639 DerefExpr, DerefExpr->getType(),
Steve Naroff450d2fc2009-04-29 16:37:50 +00002640 SourceLocation(), SourceLocation());
2641 ReplaceStmt(Exp, castExpr);
2642 ProtocolExprDecls.insert(Exp->getProtocol());
2643 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
2644 return castExpr;
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002645
2646}
2647
Steve Naroffef82b742008-05-31 14:15:04 +00002648bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2649 const char *endBuf) {
2650 while (startBuf < endBuf) {
2651 if (*startBuf == '#') {
2652 // Skip whitespace.
2653 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2654 ;
2655 if (!strncmp(startBuf, "if", strlen("if")) ||
2656 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2657 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2658 !strncmp(startBuf, "define", strlen("define")) ||
2659 !strncmp(startBuf, "undef", strlen("undef")) ||
2660 !strncmp(startBuf, "else", strlen("else")) ||
2661 !strncmp(startBuf, "elif", strlen("elif")) ||
2662 !strncmp(startBuf, "endif", strlen("endif")) ||
2663 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2664 !strncmp(startBuf, "include", strlen("include")) ||
2665 !strncmp(startBuf, "import", strlen("import")) ||
2666 !strncmp(startBuf, "include_next", strlen("include_next")))
2667 return true;
2668 }
2669 startBuf++;
2670 }
2671 return false;
2672}
2673
Ted Kremenek42730c52008-01-07 19:49:32 +00002674/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002675/// an objective-c class with ivars.
Steve Naroff44e81222008-04-14 22:03:09 +00002676void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002677 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002678 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Chris Lattnerd120b9e2008-11-24 03:54:41 +00002679 assert(CDecl->getNameAsCString() &&
Douglas Gregor24afd4a2008-11-17 14:58:09 +00002680 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002681 // Do not synthesize more than once.
Ted Kremenek42730c52008-01-07 19:49:32 +00002682 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002683 return;
Ted Kremenek42730c52008-01-07 19:49:32 +00002684 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerec4979b2008-03-16 21:08:55 +00002685 int NumIvars = CDecl->ivar_size();
Steve Naroff2c7afc92007-11-14 19:25:57 +00002686 SourceLocation LocStart = CDecl->getLocStart();
2687 SourceLocation LocEnd = CDecl->getLocEnd();
2688
2689 const char *startBuf = SM->getCharacterData(LocStart);
2690 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffef82b742008-05-31 14:15:04 +00002691
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002692 // If no ivars and no root or if its root, directly or indirectly,
2693 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerec4979b2008-03-16 21:08:55 +00002694 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2695 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattnere1be6022009-04-14 23:22:57 +00002696 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002697 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002698 return;
2699 }
2700
2701 // FIXME: This has potential of causing problem. If
Ted Kremenek42730c52008-01-07 19:49:32 +00002702 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002703 Result += "\nstruct ";
Chris Lattner271d4c22008-11-24 05:29:24 +00002704 Result += CDecl->getNameAsString();
Steve Naroffde0da102008-03-10 23:16:54 +00002705 if (LangOpts.Microsoft)
2706 Result += "_IMPL";
Steve Naroff60dfb6b2008-03-12 00:25:36 +00002707
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002708 if (NumIvars > 0) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002709 const char *cursor = strchr(startBuf, '{');
2710 assert((cursor && endBuf)
Ted Kremenek42730c52008-01-07 19:49:32 +00002711 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffef82b742008-05-31 14:15:04 +00002712 // If the buffer contains preprocessor directives, we do more fine-grained
2713 // rewrites. This is intended to fix code that looks like (which occurs in
2714 // NSURL.h, for example):
2715 //
2716 // #ifdef XYZ
2717 // @interface Foo : NSObject
2718 // #else
2719 // @interface FooBar : NSObject
2720 // #endif
2721 // {
2722 // int i;
2723 // }
2724 // @end
2725 //
2726 // This clause is segregated to avoid breaking the common case.
2727 if (BufferContainsPPDirectives(startBuf, cursor)) {
2728 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2729 CDecl->getClassLoc();
2730 const char *endHeader = SM->getCharacterData(L);
Chris Lattnere1be6022009-04-14 23:22:57 +00002731 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffef82b742008-05-31 14:15:04 +00002732
Chris Lattner179fd522009-02-20 18:18:36 +00002733 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffef82b742008-05-31 14:15:04 +00002734 // advance to the end of the referenced protocols.
2735 while (endHeader < cursor && *endHeader != '>') endHeader++;
2736 endHeader++;
2737 }
2738 // rewrite the original header
2739 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2740 } else {
2741 // rewrite the original header *without* disturbing the '{'
2742 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2743 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002744 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002745 Result = "\n struct ";
Chris Lattner271d4c22008-11-24 05:29:24 +00002746 Result += RCDecl->getNameAsString();
Steve Naroffcbf88fe2008-03-12 21:09:20 +00002747 Result += "_IMPL ";
Chris Lattner271d4c22008-11-24 05:29:24 +00002748 Result += RCDecl->getNameAsString();
Steve Naroff4850dfe2008-03-12 21:22:52 +00002749 Result += "_IVARS;\n";
Steve Naroff2c7afc92007-11-14 19:25:57 +00002750
2751 // insert the super class structure definition.
Chris Lattner6216f292008-01-31 19:42:41 +00002752 SourceLocation OnePastCurly =
2753 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2754 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Naroff2c7afc92007-11-14 19:25:57 +00002755 }
2756 cursor++; // past '{'
2757
2758 // Now comment out any visibility specifiers.
2759 while (cursor < endBuf) {
2760 if (*cursor == '@') {
2761 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf04ead52007-11-14 22:57:51 +00002762 // Skip whitespace.
2763 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2764 /*scan*/;
2765
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002766 // FIXME: presence of @public, etc. inside comment results in
2767 // this transformation as well, which is still correct c-code.
Steve Naroff2c7afc92007-11-14 19:25:57 +00002768 if (!strncmp(cursor, "public", strlen("public")) ||
2769 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffa93924a2008-04-04 22:34:24 +00002770 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002771 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattner6216f292008-01-31 19:42:41 +00002772 InsertText(atLoc, "// ", 3);
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002773 }
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002774 // FIXME: If there are cases where '<' is used in ivar declaration part
2775 // of user code, then scan the ivar list and use needToScanForQualifiers
2776 // for type checking.
2777 else if (*cursor == '<') {
2778 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner6216f292008-01-31 19:42:41 +00002779 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002780 cursor = strchr(cursor, '>');
2781 cursor++;
2782 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner6216f292008-01-31 19:42:41 +00002783 InsertText(atLoc, " */", 3);
Steve Naroff6449c6c2008-10-30 12:09:33 +00002784 } else if (*cursor == '^') { // rewrite block specifier.
2785 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2786 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002787 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002788 cursor++;
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002789 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002790 // Don't forget to add a ';'!!
Chris Lattner6216f292008-01-31 19:42:41 +00002791 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Naroff2c7afc92007-11-14 19:25:57 +00002792 } else { // we don't have any instance variables - insert super struct.
Chris Lattnere1be6022009-04-14 23:22:57 +00002793 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroff2c7afc92007-11-14 19:25:57 +00002794 Result += " {\n struct ";
Chris Lattner271d4c22008-11-24 05:29:24 +00002795 Result += RCDecl->getNameAsString();
Steve Naroffcbf88fe2008-03-12 21:09:20 +00002796 Result += "_IMPL ";
Chris Lattner271d4c22008-11-24 05:29:24 +00002797 Result += RCDecl->getNameAsString();
Steve Naroff4850dfe2008-03-12 21:22:52 +00002798 Result += "_IVARS;\n};\n";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002799 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002800 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002801 // Mark this struct as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +00002802 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff04eaa192008-05-06 18:26:51 +00002803 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002804}
2805
Ted Kremenek42730c52008-01-07 19:49:32 +00002806// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002807/// class methods.
Douglas Gregorcd19b572009-04-23 01:02:12 +00002808template<typename MethodIterator>
2809void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
2810 MethodIterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +00002811 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002812 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002813 const char *ClassName,
2814 std::string &Result) {
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002815 if (MethodBegin == MethodEnd) return;
2816
Fariborz Jahanian04455192007-10-22 21:41:37 +00002817 static bool objc_impl_method = false;
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002818 if (!objc_impl_method) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002819 /* struct _objc_method {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002820 SEL _cmd;
2821 char *method_types;
2822 void *_imp;
2823 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002824 */
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002825 Result += "\nstruct _objc_method {\n";
2826 Result += "\tSEL _cmd;\n";
2827 Result += "\tchar *method_types;\n";
2828 Result += "\tvoid *_imp;\n";
2829 Result += "};\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002830
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002831 objc_impl_method = true;
Fariborz Jahanian96b55da2007-10-19 00:36:46 +00002832 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002833
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002834 // Build _objc_method_list for class's methods if needed
Steve Naroffc723eec2008-03-11 00:12:29 +00002835
2836 /* struct {
2837 struct _objc_method_list *next_method;
2838 int method_count;
2839 struct _objc_method method_list[];
2840 }
2841 */
Douglas Gregorcd19b572009-04-23 01:02:12 +00002842 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroffc723eec2008-03-11 00:12:29 +00002843 Result += "\nstatic struct {\n";
2844 Result += "\tstruct _objc_method_list *next_method;\n";
2845 Result += "\tint method_count;\n";
2846 Result += "\tstruct _objc_method method_list[";
Douglas Gregorcd19b572009-04-23 01:02:12 +00002847 Result += utostr(NumMethods);
Steve Naroffc723eec2008-03-11 00:12:29 +00002848 Result += "];\n} _OBJC_";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002849 Result += prefix;
2850 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2851 Result += "_METHODS_";
2852 Result += ClassName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00002853 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002854 Result += IsInstanceMethod ? "inst" : "cls";
2855 Result += "_meth\")))= ";
Douglas Gregorcd19b572009-04-23 01:02:12 +00002856 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002857
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002858 Result += "\t,{{(SEL)\"";
Chris Lattner3a8f2942008-11-24 03:33:13 +00002859 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002860 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002861 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002862 Result += "\", \"";
2863 Result += MethodTypeString;
Steve Naroffc723eec2008-03-11 00:12:29 +00002864 Result += "\", (void *)";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002865 Result += MethodInternalNames[*MethodBegin];
2866 Result += "}\n";
2867 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2868 Result += "\t ,{(SEL)\"";
Chris Lattner3a8f2942008-11-24 03:33:13 +00002869 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002870 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002871 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002872 Result += "\", \"";
2873 Result += MethodTypeString;
Steve Naroffc723eec2008-03-11 00:12:29 +00002874 Result += "\", (void *)";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002875 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00002876 Result += "}\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002877 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002878 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002879}
2880
Steve Naroff450d2fc2009-04-29 16:37:50 +00002881/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner0be08822008-07-21 21:32:27 +00002882void RewriteObjC::
Steve Naroff450d2fc2009-04-29 16:37:50 +00002883RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
2884 const char *ClassName, std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002885 static bool objc_protocol_methods = false;
Steve Naroff450d2fc2009-04-29 16:37:50 +00002886
2887 // Output struct protocol_methods holder of method selector and type.
2888 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2889 /* struct protocol_methods {
2890 SEL _cmd;
2891 char *method_types;
2892 }
2893 */
2894 Result += "\nstruct _protocol_methods {\n";
2895 Result += "\tstruct objc_selector *_cmd;\n";
2896 Result += "\tchar *method_types;\n";
2897 Result += "};\n";
2898
2899 objc_protocol_methods = true;
2900 }
2901 // Do not synthesize the protocol more than once.
2902 if (ObjCSynthesizedProtocols.count(PDecl))
2903 return;
2904
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002905 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2906 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
2907 PDecl->instmeth_end());
Steve Naroff450d2fc2009-04-29 16:37:50 +00002908 /* struct _objc_protocol_method_list {
2909 int protocol_method_count;
2910 struct protocol_methods protocols[];
2911 }
Steve Naroff27429432008-03-12 01:06:30 +00002912 */
Steve Naroff450d2fc2009-04-29 16:37:50 +00002913 Result += "\nstatic struct {\n";
2914 Result += "\tint protocol_method_count;\n";
2915 Result += "\tstruct _protocol_methods protocol_methods[";
2916 Result += utostr(NumMethods);
2917 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
2918 Result += PDecl->getNameAsString();
2919 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2920 "{\n\t" + utostr(NumMethods) + "\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002921
Steve Naroff450d2fc2009-04-29 16:37:50 +00002922 // Output instance methods declared in this protocol.
2923 for (ObjCProtocolDecl::instmeth_iterator
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002924 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroff450d2fc2009-04-29 16:37:50 +00002925 I != E; ++I) {
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002926 if (I == PDecl->instmeth_begin())
Steve Naroff450d2fc2009-04-29 16:37:50 +00002927 Result += "\t ,{{(struct objc_selector *)\"";
2928 else
2929 Result += "\t ,{(struct objc_selector *)\"";
2930 Result += (*I)->getSelector().getAsString().c_str();
2931 std::string MethodTypeString;
2932 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2933 Result += "\", \"";
2934 Result += MethodTypeString;
2935 Result += "\"}\n";
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002936 }
Steve Naroff450d2fc2009-04-29 16:37:50 +00002937 Result += "\t }\n};\n";
2938 }
2939
2940 // Output class methods declared in this protocol.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002941 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
2942 PDecl->classmeth_end());
Steve Naroff450d2fc2009-04-29 16:37:50 +00002943 if (NumMethods > 0) {
2944 /* struct _objc_protocol_method_list {
2945 int protocol_method_count;
2946 struct protocol_methods protocols[];
2947 }
2948 */
2949 Result += "\nstatic struct {\n";
2950 Result += "\tint protocol_method_count;\n";
2951 Result += "\tstruct _protocol_methods protocol_methods[";
2952 Result += utostr(NumMethods);
2953 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
2954 Result += PDecl->getNameAsString();
2955 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2956 "{\n\t";
2957 Result += utostr(NumMethods);
2958 Result += "\n";
2959
2960 // Output instance methods declared in this protocol.
2961 for (ObjCProtocolDecl::classmeth_iterator
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002962 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroff450d2fc2009-04-29 16:37:50 +00002963 I != E; ++I) {
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002964 if (I == PDecl->classmeth_begin())
Steve Naroff450d2fc2009-04-29 16:37:50 +00002965 Result += "\t ,{{(struct objc_selector *)\"";
2966 else
2967 Result += "\t ,{(struct objc_selector *)\"";
2968 Result += (*I)->getSelector().getAsString().c_str();
2969 std::string MethodTypeString;
2970 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2971 Result += "\", \"";
2972 Result += MethodTypeString;
2973 Result += "\"}\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002974 }
Steve Naroff450d2fc2009-04-29 16:37:50 +00002975 Result += "\t }\n};\n";
2976 }
2977
2978 // Output:
2979 /* struct _objc_protocol {
2980 // Objective-C 1.0 extensions
2981 struct _objc_protocol_extension *isa;
2982 char *protocol_name;
2983 struct _objc_protocol **protocol_list;
2984 struct _objc_protocol_method_list *instance_methods;
2985 struct _objc_protocol_method_list *class_methods;
2986 };
2987 */
2988 static bool objc_protocol = false;
2989 if (!objc_protocol) {
2990 Result += "\nstruct _objc_protocol {\n";
2991 Result += "\tstruct _objc_protocol_extension *isa;\n";
2992 Result += "\tchar *protocol_name;\n";
2993 Result += "\tstruct _objc_protocol **protocol_list;\n";
2994 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2995 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002996 Result += "};\n";
2997
Steve Naroff450d2fc2009-04-29 16:37:50 +00002998 objc_protocol = true;
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002999 }
Steve Naroff450d2fc2009-04-29 16:37:50 +00003000
3001 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3002 Result += PDecl->getNameAsString();
3003 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3004 "{\n\t0, \"";
3005 Result += PDecl->getNameAsString();
3006 Result += "\", 0, ";
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003007 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff450d2fc2009-04-29 16:37:50 +00003008 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3009 Result += PDecl->getNameAsString();
3010 Result += ", ";
3011 }
3012 else
3013 Result += "0, ";
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003014 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroff450d2fc2009-04-29 16:37:50 +00003015 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3016 Result += PDecl->getNameAsString();
3017 Result += "\n";
3018 }
3019 else
3020 Result += "0\n";
3021 Result += "};\n";
3022
3023 // Mark this protocol as having been generated.
3024 if (!ObjCSynthesizedProtocols.insert(PDecl))
3025 assert(false && "protocol already synthesized");
3026
3027}
3028
3029void RewriteObjC::
3030RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3031 const char *prefix, const char *ClassName,
3032 std::string &Result) {
3033 if (Protocols.empty()) return;
3034
3035 for (unsigned i = 0; i != Protocols.size(); i++)
3036 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3037
Chris Lattnera19b5ec2008-07-21 21:33:21 +00003038 // Output the top lovel protocol meta-data for the class.
3039 /* struct _objc_protocol_list {
3040 struct _objc_protocol_list *next;
3041 int protocol_count;
3042 struct _objc_protocol *class_protocols[];
3043 }
3044 */
3045 Result += "\nstatic struct {\n";
3046 Result += "\tstruct _objc_protocol_list *next;\n";
3047 Result += "\tint protocol_count;\n";
3048 Result += "\tstruct _objc_protocol *class_protocols[";
3049 Result += utostr(Protocols.size());
3050 Result += "];\n} _OBJC_";
3051 Result += prefix;
3052 Result += "_PROTOCOLS_";
3053 Result += ClassName;
3054 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3055 "{\n\t0, ";
3056 Result += utostr(Protocols.size());
3057 Result += "\n";
3058
3059 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003060 Result += Protocols[0]->getNameAsString();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00003061 Result += " \n";
3062
3063 for (unsigned i = 1; i != Protocols.size(); i++) {
3064 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003065 Result += Protocols[i]->getNameAsString();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00003066 Result += "\n";
3067 }
3068 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003069}
3070
Steve Naroff450d2fc2009-04-29 16:37:50 +00003071
Ted Kremenek42730c52008-01-07 19:49:32 +00003072/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003073/// implementation.
Steve Naroff44e81222008-04-14 22:03:09 +00003074void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003075 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00003076 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003077 // Find category declaration for this implementation.
Ted Kremenek42730c52008-01-07 19:49:32 +00003078 ObjCCategoryDecl *CDecl;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003079 for (CDecl = ClassDecl->getCategoryList(); CDecl;
3080 CDecl = CDecl->getNextClassCategory())
3081 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3082 break;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003083
Chris Lattner271d4c22008-11-24 05:29:24 +00003084 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnera661a4d2007-12-23 01:40:15 +00003085 FullCategoryName += '_';
Chris Lattner271d4c22008-11-24 05:29:24 +00003086 FullCategoryName += IDecl->getNameAsString();
Steve Naroff450d2fc2009-04-29 16:37:50 +00003087
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003088 // Build _objc_method_list for class's instance methods if needed
Douglas Gregorcd19b572009-04-23 01:02:12 +00003089 llvm::SmallVector<ObjCMethodDecl *, 32>
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003090 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregorcd19b572009-04-23 01:02:12 +00003091
3092 // If any of our property implementations have associated getters or
3093 // setters, produce metadata for them as well.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003094 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3095 PropEnd = IDecl->propimpl_end();
Douglas Gregorcd19b572009-04-23 01:02:12 +00003096 Prop != PropEnd; ++Prop) {
3097 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3098 continue;
3099 if (!(*Prop)->getPropertyIvarDecl())
3100 continue;
3101 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3102 if (!PD)
3103 continue;
3104 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3105 InstanceMethods.push_back(Getter);
3106 if (PD->isReadOnly())
3107 continue;
3108 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3109 InstanceMethods.push_back(Setter);
3110 }
3111 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00003112 true, "CATEGORY_", FullCategoryName.c_str(),
3113 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003114
3115 // Build _objc_method_list for class's class methods if needed
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003116 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00003117 false, "CATEGORY_", FullCategoryName.c_str(),
3118 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003119
3120 // Protocols referenced in class declaration?
Fariborz Jahaniand256e062007-11-13 22:09:49 +00003121 // Null CDecl is case of a category implementation with no category interface
3122 if (CDecl)
Steve Naroff450d2fc2009-04-29 16:37:50 +00003123 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3124 FullCategoryName.c_str(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003125 /* struct _objc_category {
3126 char *category_name;
3127 char *class_name;
3128 struct _objc_method_list *instance_methods;
3129 struct _objc_method_list *class_methods;
3130 struct _objc_protocol_list *protocols;
3131 // Objective-C 1.0 extensions
3132 uint32_t size; // sizeof (struct _objc_category)
3133 struct _objc_property_list *instance_properties; // category's own
3134 // @property decl.
3135 };
3136 */
3137
3138 static bool objc_category = false;
3139 if (!objc_category) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003140 Result += "\nstruct _objc_category {\n";
3141 Result += "\tchar *category_name;\n";
3142 Result += "\tchar *class_name;\n";
3143 Result += "\tstruct _objc_method_list *instance_methods;\n";
3144 Result += "\tstruct _objc_method_list *class_methods;\n";
3145 Result += "\tstruct _objc_protocol_list *protocols;\n";
3146 Result += "\tunsigned int size;\n";
3147 Result += "\tstruct _objc_property_list *instance_properties;\n";
3148 Result += "};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003149 objc_category = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00003150 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003151 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3152 Result += FullCategoryName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00003153 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003154 Result += IDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003155 Result += "\"\n\t, \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003156 Result += ClassDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003157 Result += "\"\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003158
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003159 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003160 Result += "\t, (struct _objc_method_list *)"
3161 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3162 Result += FullCategoryName;
3163 Result += "\n";
3164 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003165 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003166 Result += "\t, 0\n";
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003167 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003168 Result += "\t, (struct _objc_method_list *)"
3169 "&_OBJC_CATEGORY_CLASS_METHODS_";
3170 Result += FullCategoryName;
3171 Result += "\n";
3172 }
3173 else
3174 Result += "\t, 0\n";
3175
Chris Lattner179fd522009-02-20 18:18:36 +00003176 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003177 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
3178 Result += FullCategoryName;
3179 Result += "\n";
3180 }
3181 else
3182 Result += "\t, 0\n";
3183 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003184}
3185
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003186/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3187/// ivar offset.
Steve Naroff44e81222008-04-14 22:03:09 +00003188void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremenek42730c52008-01-07 19:49:32 +00003189 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003190 std::string &Result) {
Steve Naroffd3354222008-07-16 18:22:22 +00003191 if (ivar->isBitField()) {
3192 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3193 // place all bitfields at offset 0.
3194 Result += "0";
3195 } else {
3196 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003197 Result += IDecl->getNameAsString();
Steve Naroffd3354222008-07-16 18:22:22 +00003198 if (LangOpts.Microsoft)
3199 Result += "_IMPL";
3200 Result += ", ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003201 Result += ivar->getNameAsString();
Steve Naroffd3354222008-07-16 18:22:22 +00003202 Result += ")";
3203 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003204}
3205
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003206//===----------------------------------------------------------------------===//
3207// Meta Data Emission
3208//===----------------------------------------------------------------------===//
3209
Steve Naroff44e81222008-04-14 22:03:09 +00003210void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003211 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00003212 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003213
Fariborz Jahanian7e216522007-11-26 20:59:57 +00003214 // Explictly declared @interface's are already synthesized.
Steve Naroff7333b492009-04-20 20:09:33 +00003215 if (CDecl->isImplicitInterfaceDecl()) {
Fariborz Jahanian7e216522007-11-26 20:59:57 +00003216 // FIXME: Implementation of a class with no @interface (legacy) doese not
3217 // produce correct synthesis as yet.
Ted Kremenek42730c52008-01-07 19:49:32 +00003218 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian7e216522007-11-26 20:59:57 +00003219 }
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003220
Chris Lattnerc7b06752007-12-12 07:56:42 +00003221 // Build _objc_ivar_list metadata for classes ivars if needed
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003222 unsigned NumIvars = !IDecl->ivar_empty()
3223 ? IDecl->ivar_size()
Chris Lattnerec4979b2008-03-16 21:08:55 +00003224 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003225 if (NumIvars > 0) {
3226 static bool objc_ivar = false;
3227 if (!objc_ivar) {
3228 /* struct _objc_ivar {
3229 char *ivar_name;
3230 char *ivar_type;
3231 int ivar_offset;
3232 };
3233 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003234 Result += "\nstruct _objc_ivar {\n";
3235 Result += "\tchar *ivar_name;\n";
3236 Result += "\tchar *ivar_type;\n";
3237 Result += "\tint ivar_offset;\n";
3238 Result += "};\n";
3239
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003240 objc_ivar = true;
3241 }
3242
Steve Naroffc723eec2008-03-11 00:12:29 +00003243 /* struct {
3244 int ivar_count;
3245 struct _objc_ivar ivar_list[nIvars];
3246 };
3247 */
3248 Result += "\nstatic struct {\n";
3249 Result += "\tint ivar_count;\n";
3250 Result += "\tstruct _objc_ivar ivar_list[";
3251 Result += utostr(NumIvars);
3252 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003253 Result += IDecl->getNameAsString();
Steve Naroff5ce4a242008-03-12 17:18:30 +00003254 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003255 "{\n\t";
3256 Result += utostr(NumIvars);
3257 Result += "\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00003258
Ted Kremenek42730c52008-01-07 19:49:32 +00003259 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor087dbf32009-04-23 03:23:08 +00003260 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003261 if (!IDecl->ivar_empty()) {
Douglas Gregor087dbf32009-04-23 03:23:08 +00003262 for (ObjCImplementationDecl::ivar_iterator
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003263 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor087dbf32009-04-23 03:23:08 +00003264 IV != IVEnd; ++IV)
3265 IVars.push_back(*IV);
3266 IVI = IVars.begin();
3267 IVE = IVars.end();
Chris Lattnerc7b06752007-12-12 07:56:42 +00003268 } else {
3269 IVI = CDecl->ivar_begin();
3270 IVE = CDecl->ivar_end();
3271 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003272 Result += "\t,{{\"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003273 Result += (*IVI)->getNameAsString();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00003274 Result += "\", \"";
Steve Naroff450d2fc2009-04-29 16:37:50 +00003275 std::string TmpString, StrEncoding;
3276 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3277 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00003278 Result += StrEncoding;
3279 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00003280 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003281 Result += "}\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00003282 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003283 Result += "\t ,{\"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003284 Result += (*IVI)->getNameAsString();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00003285 Result += "\", \"";
Steve Naroff450d2fc2009-04-29 16:37:50 +00003286 std::string TmpString, StrEncoding;
3287 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3288 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00003289 Result += StrEncoding;
3290 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00003291 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003292 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003293 }
3294
3295 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003296 }
3297
3298 // Build _objc_method_list for class's instance methods if needed
Douglas Gregorcd19b572009-04-23 01:02:12 +00003299 llvm::SmallVector<ObjCMethodDecl *, 32>
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003300 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregorcd19b572009-04-23 01:02:12 +00003301
3302 // If any of our property implementations have associated getters or
3303 // setters, produce metadata for them as well.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003304 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3305 PropEnd = IDecl->propimpl_end();
Douglas Gregorcd19b572009-04-23 01:02:12 +00003306 Prop != PropEnd; ++Prop) {
3307 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3308 continue;
3309 if (!(*Prop)->getPropertyIvarDecl())
3310 continue;
3311 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3312 if (!PD)
3313 continue;
3314 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3315 InstanceMethods.push_back(Getter);
3316 if (PD->isReadOnly())
3317 continue;
3318 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3319 InstanceMethods.push_back(Setter);
3320 }
3321 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003322 true, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003323
3324 // Build _objc_method_list for class's class methods if needed
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003325 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003326 false, "", IDecl->getNameAsCString(), Result);
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003327
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003328 // Protocols referenced in class declaration?
Steve Naroff450d2fc2009-04-29 16:37:50 +00003329 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3330 "CLASS", CDecl->getNameAsCString(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003331
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003332 // Declaration of class/meta-class metadata
3333 /* struct _objc_class {
3334 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003335 const char *super_class_name;
3336 char *name;
3337 long version;
3338 long info;
3339 long instance_size;
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003340 struct _objc_ivar_list *ivars;
3341 struct _objc_method_list *methods;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003342 struct objc_cache *cache;
3343 struct objc_protocol_list *protocols;
3344 const char *ivar_layout;
3345 struct _objc_class_ext *ext;
3346 };
3347 */
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003348 static bool objc_class = false;
3349 if (!objc_class) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003350 Result += "\nstruct _objc_class {\n";
3351 Result += "\tstruct _objc_class *isa;\n";
3352 Result += "\tconst char *super_class_name;\n";
3353 Result += "\tchar *name;\n";
3354 Result += "\tlong version;\n";
3355 Result += "\tlong info;\n";
3356 Result += "\tlong instance_size;\n";
3357 Result += "\tstruct _objc_ivar_list *ivars;\n";
3358 Result += "\tstruct _objc_method_list *methods;\n";
3359 Result += "\tstruct objc_cache *cache;\n";
3360 Result += "\tstruct _objc_protocol_list *protocols;\n";
3361 Result += "\tconst char *ivar_layout;\n";
3362 Result += "\tstruct _objc_class_ext *ext;\n";
3363 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003364 objc_class = true;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003365 }
3366
3367 // Meta-class metadata generation.
Ted Kremenek42730c52008-01-07 19:49:32 +00003368 ObjCInterfaceDecl *RootClass = 0;
3369 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003370 while (SuperClass) {
3371 RootClass = SuperClass;
3372 SuperClass = SuperClass->getSuperClass();
3373 }
3374 SuperClass = CDecl->getSuperClass();
3375
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003376 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003377 Result += CDecl->getNameAsString();
Steve Naroff5ce4a242008-03-12 17:18:30 +00003378 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003379 "{\n\t(struct _objc_class *)\"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003380 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003381 Result += "\"";
3382
3383 if (SuperClass) {
3384 Result += ", \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003385 Result += SuperClass->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003386 Result += "\", \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003387 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003388 Result += "\"";
3389 }
3390 else {
3391 Result += ", 0, \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003392 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003393 Result += "\"";
3394 }
Ted Kremenek42730c52008-01-07 19:49:32 +00003395 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003396 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003397 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003398 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroffdee066b2008-03-11 18:14:26 +00003399 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003400 Result += IDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003401 Result += "\n";
3402 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003403 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003404 Result += ", 0\n";
Chris Lattner179fd522009-02-20 18:18:36 +00003405 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff27429432008-03-12 01:06:30 +00003406 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003407 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003408 Result += ",0,0\n";
3409 }
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00003410 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003411 Result += "\t,0,0,0,0\n";
3412 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003413
3414 // class metadata generation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003415 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003416 Result += CDecl->getNameAsString();
Steve Naroff5ce4a242008-03-12 17:18:30 +00003417 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003418 "{\n\t&_OBJC_METACLASS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003419 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003420 if (SuperClass) {
3421 Result += ", \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003422 Result += SuperClass->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003423 Result += "\", \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003424 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003425 Result += "\"";
3426 }
3427 else {
3428 Result += ", 0, \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003429 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003430 Result += "\"";
3431 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003432 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003433 Result += ", 0,1";
Ted Kremenek42730c52008-01-07 19:49:32 +00003434 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003435 Result += ",0";
3436 else {
3437 // class has size. Must synthesize its size.
Fariborz Jahanian9447e462007-11-05 17:47:33 +00003438 Result += ",sizeof(struct ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003439 Result += CDecl->getNameAsString();
Steve Naroffc302e5b2008-03-10 23:33:22 +00003440 if (LangOpts.Microsoft)
3441 Result += "_IMPL";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003442 Result += ")";
3443 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003444 if (NumIvars > 0) {
Steve Naroffbec4bf52008-03-11 17:37:02 +00003445 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003446 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003447 Result += "\n\t";
3448 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003449 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003450 Result += ",0";
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003451 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroffc723eec2008-03-11 00:12:29 +00003452 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003453 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003454 Result += ", 0\n\t";
3455 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003456 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003457 Result += ",0,0";
Chris Lattner179fd522009-02-20 18:18:36 +00003458 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff27429432008-03-12 01:06:30 +00003459 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003460 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003461 Result += ", 0,0\n";
3462 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003463 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003464 Result += ",0,0,0\n";
3465 Result += "};\n";
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003466}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003467
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003468/// RewriteImplementations - This routine rewrites all method implementations
3469/// and emits meta-data.
3470
Steve Naroff21658f62008-11-13 20:07:04 +00003471void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003472 int ClsDefCount = ClassImplementation.size();
3473 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003474
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003475 // Rewrite implemented methods
3476 for (int i = 0; i < ClsDefCount; i++)
3477 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003478
Fariborz Jahanian0136e372007-11-13 20:04:28 +00003479 for (int i = 0; i < CatDefCount; i++)
3480 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Naroff21658f62008-11-13 20:07:04 +00003481}
Fariborz Jahanian0136e372007-11-13 20:04:28 +00003482
Steve Naroff21658f62008-11-13 20:07:04 +00003483void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3484 int ClsDefCount = ClassImplementation.size();
3485 int CatDefCount = CategoryImplementation.size();
3486
Steve Naroff5bf10222008-05-07 21:23:49 +00003487 // This is needed for determining instance variable offsets.
Steve Naroff314c1a62008-08-05 18:47:23 +00003488 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003489 // For each implemented class, write out all its meta data.
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003490 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00003491 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003492
3493 // For each implemented category, write out all its meta data.
3494 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00003495 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroff450d2fc2009-04-29 16:37:50 +00003496
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003497 // Write objc_symtab metadata
3498 /*
3499 struct _objc_symtab
3500 {
3501 long sel_ref_cnt;
3502 SEL *refs;
3503 short cls_def_cnt;
3504 short cat_def_cnt;
3505 void *defs[cls_def_cnt + cat_def_cnt];
3506 };
3507 */
3508
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003509 Result += "\nstruct _objc_symtab {\n";
3510 Result += "\tlong sel_ref_cnt;\n";
3511 Result += "\tSEL *refs;\n";
3512 Result += "\tshort cls_def_cnt;\n";
3513 Result += "\tshort cat_def_cnt;\n";
3514 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3515 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003516
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003517 Result += "static struct _objc_symtab "
Steve Naroff5ce4a242008-03-12 17:18:30 +00003518 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003519 Result += "\t0, 0, " + utostr(ClsDefCount)
3520 + ", " + utostr(CatDefCount) + "\n";
3521 for (int i = 0; i < ClsDefCount; i++) {
3522 Result += "\t,&_OBJC_CLASS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003523 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003524 Result += "\n";
3525 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003526
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003527 for (int i = 0; i < CatDefCount; i++) {
3528 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003529 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003530 Result += "_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003531 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003532 Result += "\n";
3533 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003534
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003535 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003536
3537 // Write objc_module metadata
3538
3539 /*
3540 struct _objc_module {
3541 long version;
3542 long size;
3543 const char *name;
3544 struct _objc_symtab *symtab;
3545 }
3546 */
3547
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003548 Result += "\nstruct _objc_module {\n";
3549 Result += "\tlong version;\n";
3550 Result += "\tlong size;\n";
3551 Result += "\tconst char *name;\n";
3552 Result += "\tstruct _objc_symtab *symtab;\n";
3553 Result += "};\n\n";
3554 Result += "static struct _objc_module "
Steve Naroff5ce4a242008-03-12 17:18:30 +00003555 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003556 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3557 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003558 Result += "};\n\n";
Steve Naroff7fd0aff2008-03-10 20:43:59 +00003559
3560 if (LangOpts.Microsoft) {
Steve Naroff450d2fc2009-04-29 16:37:50 +00003561 if (ProtocolExprDecls.size()) {
3562 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
3563 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
3564 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
3565 E = ProtocolExprDecls.end(); I != E; ++I) {
3566 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
3567 Result += (*I)->getNameAsString();
3568 Result += " = &_OBJC_PROTOCOL_";
3569 Result += (*I)->getNameAsString();
3570 Result += ";\n";
3571 }
3572 Result += "#pragma data_seg(pop)\n\n";
3573 }
Steve Naroff7fd0aff2008-03-10 20:43:59 +00003574 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffbdd2dba2008-05-07 00:06:16 +00003575 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff7fd0aff2008-03-10 20:43:59 +00003576 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3577 Result += "&_OBJC_MODULES;\n";
3578 Result += "#pragma data_seg(pop)\n\n";
3579 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003580}
Chris Lattner6fe8b272007-10-16 22:36:42 +00003581
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003582std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3583 const char *funcName,
3584 std::string Tag) {
3585 const FunctionType *AFT = CE->getFunctionType();
3586 QualType RT = AFT->getResultType();
3587 std::string StructRef = "struct " + Tag;
3588 std::string S = "static " + RT.getAsString() + " __" +
3589 funcName + "_" + "block_func_" + utostr(i);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00003590
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003591 BlockDecl *BD = CE->getBlockDecl();
3592
Douglas Gregor4fa58902009-02-26 23:50:07 +00003593 if (isa<FunctionNoProtoType>(AFT)) {
Steve Naroff16478cf2009-02-02 17:19:26 +00003594 // No user-supplied arguments. Still need to pass in a pointer to the
3595 // block (to reference imported block decl refs).
3596 S += "(" + StructRef + " *__cself)";
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003597 } else if (BD->param_empty()) {
3598 S += "(" + StructRef + " *__cself)";
3599 } else {
Douglas Gregor4fa58902009-02-26 23:50:07 +00003600 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003601 assert(FT && "SynthesizeBlockFunc: No function proto");
3602 S += '(';
3603 // first add the implicit argument.
3604 S += StructRef + " *__cself, ";
3605 std::string ParamStr;
3606 for (BlockDecl::param_iterator AI = BD->param_begin(),
3607 E = BD->param_end(); AI != E; ++AI) {
3608 if (AI != BD->param_begin()) S += ", ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003609 ParamStr = (*AI)->getNameAsString();
Douglas Gregor3bf3bbc2009-05-29 20:38:28 +00003610 (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003611 S += ParamStr;
3612 }
3613 if (FT->isVariadic()) {
3614 if (!BD->param_empty()) S += ", ";
3615 S += "...";
3616 }
3617 S += ')';
3618 }
3619 S += " {\n";
3620
3621 // Create local declarations to avoid rewriting all closure decl ref exprs.
3622 // First, emit a declaration for all "by ref" decls.
3623 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3624 E = BlockByRefDecls.end(); I != E; ++I) {
3625 S += " ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003626 std::string Name = (*I)->getNameAsString();
Douglas Gregor3bf3bbc2009-05-29 20:38:28 +00003627 Context->getPointerType((*I)->getType()).getAsStringInternal(Name,
3628 Context->PrintingPolicy);
Chris Lattner271d4c22008-11-24 05:29:24 +00003629 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003630 }
3631 // Next, emit a declaration for all "by copy" declarations.
3632 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3633 E = BlockByCopyDecls.end(); I != E; ++I) {
3634 S += " ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003635 std::string Name = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003636 // Handle nested closure invocation. For example:
3637 //
3638 // void (^myImportedClosure)(void);
3639 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3640 //
3641 // void (^anotherClosure)(void);
3642 // anotherClosure = ^(void) {
3643 // myImportedClosure(); // import and invoke the closure
3644 // };
3645 //
Steve Naroffd896f4b2008-12-11 21:05:33 +00003646 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003647 S += "struct __block_impl *";
3648 else
Douglas Gregor3bf3bbc2009-05-29 20:38:28 +00003649 (*I)->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Chris Lattner271d4c22008-11-24 05:29:24 +00003650 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003651 }
3652 std::string RewrittenStr = RewrittenBlockExprs[CE];
3653 const char *cstr = RewrittenStr.c_str();
3654 while (*cstr++ != '{') ;
3655 S += cstr;
3656 S += "\n";
3657 return S;
3658}
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003659
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003660std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3661 const char *funcName,
3662 std::string Tag) {
3663 std::string StructRef = "struct " + Tag;
3664 std::string S = "static void __";
3665
3666 S += funcName;
3667 S += "_block_copy_" + utostr(i);
3668 S += "(" + StructRef;
3669 S += "*dst, " + StructRef;
3670 S += "*src) {";
3671 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3672 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff44fe1e32008-12-16 15:50:30 +00003673 S += "_Block_object_assign((void*)&dst->";
Chris Lattner271d4c22008-11-24 05:29:24 +00003674 S += (*I)->getNameAsString();
Steve Naroff1d56d9e2008-12-11 20:51:38 +00003675 S += ", (void*)src->";
Chris Lattner271d4c22008-11-24 05:29:24 +00003676 S += (*I)->getNameAsString();
Steve Naroff44fe1e32008-12-16 15:50:30 +00003677 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);}";
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003678 }
3679 S += "\nstatic void __";
3680 S += funcName;
3681 S += "_block_dispose_" + utostr(i);
3682 S += "(" + StructRef;
3683 S += "*src) {";
3684 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3685 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff44fe1e32008-12-16 15:50:30 +00003686 S += "_Block_object_dispose((void*)src->";
Chris Lattner271d4c22008-11-24 05:29:24 +00003687 S += (*I)->getNameAsString();
Steve Naroff44fe1e32008-12-16 15:50:30 +00003688 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003689 }
3690 S += "}\n";
3691 return S;
3692}
3693
3694std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3695 bool hasCopyDisposeHelpers) {
Steve Naroff6449c6c2008-10-30 12:09:33 +00003696 std::string S = "\nstruct " + Tag;
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003697 std::string Constructor = " " + Tag;
3698
3699 S += " {\n struct __block_impl impl;\n";
3700
3701 if (hasCopyDisposeHelpers)
3702 S += " void *copy;\n void *dispose;\n";
3703
3704 Constructor += "(void *fp";
3705
3706 if (hasCopyDisposeHelpers)
3707 Constructor += ", void *copyHelp, void *disposeHelp";
3708
3709 if (BlockDeclRefs.size()) {
3710 // Output all "by copy" declarations.
3711 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3712 E = BlockByCopyDecls.end(); I != E; ++I) {
3713 S += " ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003714 std::string FieldName = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003715 std::string ArgName = "_" + FieldName;
3716 // Handle nested closure invocation. For example:
3717 //
3718 // void (^myImportedBlock)(void);
3719 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3720 //
3721 // void (^anotherBlock)(void);
3722 // anotherBlock = ^(void) {
3723 // myImportedBlock(); // import and invoke the closure
3724 // };
3725 //
Steve Naroffd896f4b2008-12-11 21:05:33 +00003726 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003727 S += "struct __block_impl *";
3728 Constructor += ", void *" + ArgName;
3729 } else {
Douglas Gregor3bf3bbc2009-05-29 20:38:28 +00003730 (*I)->getType().getAsStringInternal(FieldName, Context->PrintingPolicy);
3731 (*I)->getType().getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003732 Constructor += ", " + ArgName;
3733 }
3734 S += FieldName + ";\n";
3735 }
3736 // Output all "by ref" declarations.
3737 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3738 E = BlockByRefDecls.end(); I != E; ++I) {
3739 S += " ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003740 std::string FieldName = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003741 std::string ArgName = "_" + FieldName;
3742 // Handle nested closure invocation. For example:
3743 //
3744 // void (^myImportedBlock)(void);
3745 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3746 //
3747 // void (^anotherBlock)(void);
3748 // anotherBlock = ^(void) {
3749 // myImportedBlock(); // import and invoke the closure
3750 // };
3751 //
Steve Naroffd896f4b2008-12-11 21:05:33 +00003752 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003753 S += "struct __block_impl *";
3754 Constructor += ", void *" + ArgName;
3755 } else {
Douglas Gregor3bf3bbc2009-05-29 20:38:28 +00003756 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName,
3757 Context->PrintingPolicy);
3758 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName,
3759 Context->PrintingPolicy);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003760 Constructor += ", " + ArgName;
3761 }
3762 S += FieldName + "; // by ref\n";
3763 }
3764 // Finish writing the constructor.
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003765 Constructor += ", int flags=0) {\n";
Steve Naroff450d2fc2009-04-29 16:37:50 +00003766 if (GlobalVarDecl)
3767 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3768 else
3769 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3770 Constructor += " impl.Size = sizeof(";
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003771 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3772
3773 if (hasCopyDisposeHelpers)
3774 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3775
3776 // Initialize all "by copy" arguments.
3777 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3778 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattner271d4c22008-11-24 05:29:24 +00003779 std::string Name = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003780 Constructor += " ";
Steve Naroffd896f4b2008-12-11 21:05:33 +00003781 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003782 Constructor += Name + " = (struct __block_impl *)_";
3783 else
3784 Constructor += Name + " = _";
3785 Constructor += Name + ";\n";
3786 }
3787 // Initialize all "by ref" arguments.
3788 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3789 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner271d4c22008-11-24 05:29:24 +00003790 std::string Name = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003791 Constructor += " ";
Steve Naroffd896f4b2008-12-11 21:05:33 +00003792 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003793 Constructor += Name + " = (struct __block_impl *)_";
3794 else
3795 Constructor += Name + " = _";
3796 Constructor += Name + ";\n";
3797 }
3798 } else {
3799 // Finish writing the constructor.
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003800 Constructor += ", int flags=0) {\n";
Steve Naroff450d2fc2009-04-29 16:37:50 +00003801 if (GlobalVarDecl)
3802 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3803 else
3804 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3805 Constructor += " impl.Size = sizeof(";
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003806 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3807 if (hasCopyDisposeHelpers)
3808 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3809 }
3810 Constructor += " ";
3811 Constructor += "}\n";
3812 S += Constructor;
3813 S += "};\n";
3814 return S;
3815}
3816
3817void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3818 const char *FunName) {
3819 // Insert closures that were part of the function.
3820 for (unsigned i = 0; i < Blocks.size(); i++) {
3821
3822 CollectBlockDeclRefInfo(Blocks[i]);
3823
3824 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3825
3826 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
3827 ImportedBlockDecls.size() > 0);
3828
3829 InsertText(FunLocStart, CI.c_str(), CI.size());
3830
3831 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
3832
3833 InsertText(FunLocStart, CF.c_str(), CF.size());
3834
3835 if (ImportedBlockDecls.size()) {
3836 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3837 InsertText(FunLocStart, HF.c_str(), HF.size());
3838 }
3839
3840 BlockDeclRefs.clear();
3841 BlockByRefDecls.clear();
3842 BlockByCopyDecls.clear();
3843 BlockCallExprs.clear();
3844 ImportedBlockDecls.clear();
3845 }
3846 Blocks.clear();
3847 RewrittenBlockExprs.clear();
3848}
3849
3850void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3851 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003852 const char *FuncName = FD->getNameAsCString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003853
3854 SynthesizeBlockLiterals(FunLocStart, FuncName);
3855}
3856
3857void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff6449c6c2008-10-30 12:09:33 +00003858 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3859 //SourceLocation FunLocStart = MD->getLocStart();
3860 // FIXME: This hack works around a bug in Rewrite.InsertText().
3861 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattner3a8f2942008-11-24 03:33:13 +00003862 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003863 // Convert colons to underscores.
3864 std::string::size_type loc = 0;
3865 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3866 FuncName.replace(loc, 1, "_");
3867
3868 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3869}
3870
3871void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3872 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3873 CI != E; ++CI)
3874 if (*CI) {
3875 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3876 GetBlockDeclRefExprs(CBE->getBody());
3877 else
3878 GetBlockDeclRefExprs(*CI);
3879 }
3880 // Handle specific things.
3881 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3882 // FIXME: Handle enums.
3883 if (!isa<FunctionDecl>(CDRE->getDecl()))
3884 BlockDeclRefs.push_back(CDRE);
3885 return;
3886}
3887
3888void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3889 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3890 CI != E; ++CI)
3891 if (*CI) {
3892 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3893 GetBlockCallExprs(CBE->getBody());
3894 else
3895 GetBlockCallExprs(*CI);
3896 }
3897
3898 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
3899 if (CE->getCallee()->getType()->isBlockPointerType()) {
3900 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
3901 }
3902 }
3903 return;
3904}
3905
Steve Naroff85eb17b2008-10-30 10:07:53 +00003906Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003907 // Navigate to relevant type information.
3908 const char *closureName = 0;
3909 const BlockPointerType *CPT = 0;
3910
3911 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003912 closureName = DRE->getDecl()->getNameAsCString();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003913 CPT = DRE->getType()->getAs<BlockPointerType>();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003914 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003915 closureName = CDRE->getDecl()->getNameAsCString();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003916 CPT = CDRE->getType()->getAs<BlockPointerType>();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003917 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003918 closureName = MExpr->getMemberDecl()->getNameAsCString();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003919 CPT = MExpr->getType()->getAs<BlockPointerType>();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003920 } else {
3921 assert(1 && "RewriteBlockClass: Bad type");
3922 }
3923 assert(CPT && "RewriteBlockClass: Bad type");
3924 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
3925 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor4fa58902009-02-26 23:50:07 +00003926 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003927 // FTP will be null for closures that don't take arguments.
3928
Steve Naroff85eb17b2008-10-30 10:07:53 +00003929 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
3930 SourceLocation(),
3931 &Context->Idents.get("__block_impl"));
3932 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003933
Steve Naroff85eb17b2008-10-30 10:07:53 +00003934 // Generate a funky cast.
3935 llvm::SmallVector<QualType, 8> ArgTypes;
3936
3937 // Push the block argument type.
3938 ArgTypes.push_back(PtrBlock);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003939 if (FTP) {
Douglas Gregor4fa58902009-02-26 23:50:07 +00003940 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff85eb17b2008-10-30 10:07:53 +00003941 E = FTP->arg_type_end(); I && (I != E); ++I) {
3942 QualType t = *I;
3943 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffd896f4b2008-12-11 21:05:33 +00003944 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003945 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff85eb17b2008-10-30 10:07:53 +00003946 t = Context->getPointerType(BPT->getPointeeType());
3947 }
3948 ArgTypes.push_back(t);
3949 }
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003950 }
Steve Naroff85eb17b2008-10-30 10:07:53 +00003951 // Now do the pointer to function cast.
3952 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
3953 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
3954
3955 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003956
Anders Carlsson7ef181c2009-07-31 00:48:10 +00003957 CastExpr *BlkCast = new (Context) CStyleCastExpr(PtrBlock,
3958 CastExpr::CK_Unknown,
3959 Exp->getCallee(),
Ted Kremenek0c97e042009-02-07 01:47:29 +00003960 PtrBlock, SourceLocation(),
3961 SourceLocation());
Steve Naroff85eb17b2008-10-30 10:07:53 +00003962 // Don't forget the parens to enforce the proper binding.
Ted Kremenek0c97e042009-02-07 01:47:29 +00003963 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3964 BlkCast);
Steve Naroff85eb17b2008-10-30 10:07:53 +00003965 //PE->dump();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003966
Douglas Gregor8acb7272008-12-11 16:49:14 +00003967 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00003968 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00003969 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek0c97e042009-02-07 01:47:29 +00003970 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
3971 FD->getType());
Steve Naroff85eb17b2008-10-30 10:07:53 +00003972
Anders Carlsson7ef181c2009-07-31 00:48:10 +00003973 CastExpr *FunkCast = new (Context) CStyleCastExpr(PtrToFuncCastType,
3974 CastExpr::CK_Unknown, ME,
Ted Kremenek0c97e042009-02-07 01:47:29 +00003975 PtrToFuncCastType,
3976 SourceLocation(),
3977 SourceLocation());
3978 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Steve Naroff85eb17b2008-10-30 10:07:53 +00003979
3980 llvm::SmallVector<Expr*, 8> BlkExprs;
3981 // Add the implicit argument.
3982 BlkExprs.push_back(BlkCast);
3983 // Add the user arguments.
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003984 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3985 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff85eb17b2008-10-30 10:07:53 +00003986 BlkExprs.push_back(*I);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003987 }
Ted Kremenek362abcd2009-02-09 20:51:47 +00003988 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
3989 BlkExprs.size(),
Ted Kremenek0c97e042009-02-07 01:47:29 +00003990 Exp->getType(), SourceLocation());
Steve Naroff85eb17b2008-10-30 10:07:53 +00003991 return CE;
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003992}
3993
3994void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Steve Naroff85eb17b2008-10-30 10:07:53 +00003995 Stmt *BlockCall = SynthesizeBlockCall(Exp);
3996 ReplaceStmt(Exp, BlockCall);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003997}
3998
Steve Naroff450d2fc2009-04-29 16:37:50 +00003999// We need to return the rewritten expression to handle cases where the
4000// BlockDeclRefExpr is embedded in another expression being rewritten.
4001// For example:
4002//
4003// int main() {
4004// __block Foo *f;
4005// __block int i;
4006//
4007// void (^myblock)() = ^() {
4008// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4009// i = 77;
4010// };
4011//}
4012Stmt *RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004013 // FIXME: Add more elaborate code generation required by the ABI.
Ted Kremenek0c97e042009-02-07 01:47:29 +00004014 Expr *DerefExpr = new (Context) UnaryOperator(BDRE, UnaryOperator::Deref,
Steve Naroff16478cf2009-02-02 17:19:26 +00004015 Context->getPointerType(BDRE->getType()),
4016 SourceLocation());
4017 // Need parens to enforce precedence.
Ted Kremenek0c97e042009-02-07 01:47:29 +00004018 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), DerefExpr);
Steve Naroff16478cf2009-02-02 17:19:26 +00004019 ReplaceStmt(BDRE, PE);
Steve Naroff450d2fc2009-04-29 16:37:50 +00004020 return PE;
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004021}
4022
Steve Naroff7f1412d2008-11-03 23:29:32 +00004023void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4024 SourceLocation LocStart = CE->getLParenLoc();
4025 SourceLocation LocEnd = CE->getRParenLoc();
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004026
4027 // Need to avoid trying to rewrite synthesized casts.
4028 if (LocStart.isInvalid())
4029 return;
Steve Naroff1c53c022008-11-03 11:20:24 +00004030 // Need to avoid trying to rewrite casts contained in macros.
4031 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4032 return;
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004033
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004034 const char *startBuf = SM->getCharacterData(LocStart);
4035 const char *endBuf = SM->getCharacterData(LocEnd);
4036
4037 // advance the location to startArgList.
4038 const char *argPtr = startBuf;
4039
4040 while (*argPtr++ && (argPtr < endBuf)) {
4041 switch (*argPtr) {
4042 case '^':
4043 // Replace the '^' with '*'.
4044 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
4045 ReplaceText(LocStart, 1, "*", 1);
4046 break;
4047 }
4048 }
4049 return;
4050}
4051
4052void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4053 SourceLocation DeclLoc = FD->getLocation();
4054 unsigned parenCount = 0;
4055
4056 // We have 1 or more arguments that have closure pointers.
4057 const char *startBuf = SM->getCharacterData(DeclLoc);
4058 const char *startArgList = strchr(startBuf, '(');
4059
4060 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4061
4062 parenCount++;
4063 // advance the location to startArgList.
4064 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4065 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4066
4067 const char *argPtr = startArgList;
4068
4069 while (*argPtr++ && parenCount) {
4070 switch (*argPtr) {
4071 case '^':
4072 // Replace the '^' with '*'.
4073 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
4074 ReplaceText(DeclLoc, 1, "*", 1);
4075 break;
4076 case '(':
4077 parenCount++;
4078 break;
4079 case ')':
4080 parenCount--;
4081 break;
4082 }
4083 }
4084 return;
4085}
4086
4087bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor4fa58902009-02-26 23:50:07 +00004088 const FunctionProtoType *FTP;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004089 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004090 if (PT) {
Douglas Gregor4fa58902009-02-26 23:50:07 +00004091 FTP = PT->getPointeeType()->getAsFunctionProtoType();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004092 } else {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004093 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004094 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
Douglas Gregor4fa58902009-02-26 23:50:07 +00004095 FTP = BPT->getPointeeType()->getAsFunctionProtoType();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004096 }
4097 if (FTP) {
Douglas Gregor4fa58902009-02-26 23:50:07 +00004098 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004099 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroffd896f4b2008-12-11 21:05:33 +00004100 if (isTopLevelBlockPointerType(*I))
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004101 return true;
4102 }
4103 return false;
4104}
4105
Ted Kremenek0c97e042009-02-07 01:47:29 +00004106void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4107 const char *&RParen) {
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004108 const char *argPtr = strchr(Name, '(');
4109 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4110
4111 LParen = argPtr; // output the start.
4112 argPtr++; // skip past the left paren.
4113 unsigned parenCount = 1;
4114
4115 while (*argPtr && parenCount) {
4116 switch (*argPtr) {
4117 case '(': parenCount++; break;
4118 case ')': parenCount--; break;
4119 default: break;
4120 }
4121 if (parenCount) argPtr++;
4122 }
4123 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4124 RParen = argPtr; // output the end
4125}
4126
4127void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4128 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4129 RewriteBlockPointerFunctionArgs(FD);
4130 return;
4131 }
4132 // Handle Variables and Typedefs.
4133 SourceLocation DeclLoc = ND->getLocation();
4134 QualType DeclT;
4135 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4136 DeclT = VD->getType();
4137 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4138 DeclT = TDD->getUnderlyingType();
4139 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4140 DeclT = FD->getType();
4141 else
4142 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
4143
4144 const char *startBuf = SM->getCharacterData(DeclLoc);
4145 const char *endBuf = startBuf;
4146 // scan backward (from the decl location) for the end of the previous decl.
4147 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4148 startBuf--;
4149
4150 // *startBuf != '^' if we are dealing with a pointer to function that
4151 // may take block argument types (which will be handled below).
4152 if (*startBuf == '^') {
4153 // Replace the '^' with '*', computing a negative offset.
4154 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4155 ReplaceText(DeclLoc, 1, "*", 1);
4156 }
4157 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4158 // Replace the '^' with '*' for arguments.
4159 DeclLoc = ND->getLocation();
4160 startBuf = SM->getCharacterData(DeclLoc);
4161 const char *argListBegin, *argListEnd;
4162 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4163 while (argListBegin < argListEnd) {
4164 if (*argListBegin == '^') {
4165 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
4166 ReplaceText(CaretLoc, 1, "*", 1);
4167 }
4168 argListBegin++;
4169 }
4170 }
4171 return;
4172}
4173
4174void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4175 // Add initializers for any closure decl refs.
4176 GetBlockDeclRefExprs(Exp->getBody());
4177 if (BlockDeclRefs.size()) {
4178 // Unique all "by copy" declarations.
4179 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4180 if (!BlockDeclRefs[i]->isByRef())
4181 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
4182 // Unique all "by ref" declarations.
4183 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4184 if (BlockDeclRefs[i]->isByRef()) {
4185 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
4186 }
4187 // Find any imported blocks...they will need special attention.
4188 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Steve Naroff1d56d9e2008-12-11 20:51:38 +00004189 if (BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroffe59c8b12008-11-13 17:40:07 +00004190 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004191 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4192 }
4193 }
4194}
4195
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004196FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4197 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor4fa58902009-02-26 23:50:07 +00004198 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004199 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00004200 ID, FType, 0, FunctionDecl::Extern, false,
Douglas Gregor1f88aa72009-02-25 16:33:18 +00004201 false);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004202}
4203
Steve Naroff80c54752008-10-29 18:15:37 +00004204Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004205 Blocks.push_back(Exp);
4206
4207 CollectBlockDeclRefInfo(Exp);
4208 std::string FuncName;
4209
4210 if (CurFunctionDef)
Chris Lattner3a8f2942008-11-24 03:33:13 +00004211 FuncName = CurFunctionDef->getNameAsString();
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004212 else if (CurMethodDef) {
Chris Lattner3a8f2942008-11-24 03:33:13 +00004213 FuncName = CurMethodDef->getSelector().getAsString();
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004214 // Convert colons to underscores.
4215 std::string::size_type loc = 0;
4216 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4217 FuncName.replace(loc, 1, "_");
Steve Naroff80c54752008-10-29 18:15:37 +00004218 } else if (GlobalVarDecl)
Chris Lattner271d4c22008-11-24 05:29:24 +00004219 FuncName = std::string(GlobalVarDecl->getNameAsString());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004220
4221 std::string BlockNumber = utostr(Blocks.size()-1);
4222
4223 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4224 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4225
4226 // Get a pointer to the function type so we can cast appropriately.
4227 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4228
4229 FunctionDecl *FD;
4230 Expr *NewRep;
4231
4232 // Simulate a contructor call...
4233 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004234 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004235
4236 llvm::SmallVector<Expr*, 4> InitExprs;
4237
Steve Naroffd0419d62008-10-29 21:23:59 +00004238 // Initialize the block function.
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004239 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004240 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4241 SourceLocation());
Anders Carlsson7ef181c2009-07-31 00:48:10 +00004242 CastExpr *castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4243 CastExpr::CK_Unknown, Arg,
Ted Kremenek0c97e042009-02-07 01:47:29 +00004244 Context->VoidPtrTy, SourceLocation(),
4245 SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004246 InitExprs.push_back(castExpr);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004247
4248 if (ImportedBlockDecls.size()) {
4249 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
Steve Naroffd0419d62008-10-29 21:23:59 +00004250 FD = SynthBlockInitFunctionDecl(Buf.c_str());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004251 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Anders Carlsson7ef181c2009-07-31 00:48:10 +00004252 castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4253 CastExpr::CK_Unknown, Arg,
Ted Kremenek0c97e042009-02-07 01:47:29 +00004254 Context->VoidPtrTy, SourceLocation(),
4255 SourceLocation());
Steve Naroffd0419d62008-10-29 21:23:59 +00004256 InitExprs.push_back(castExpr);
4257
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004258 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
Steve Naroffd0419d62008-10-29 21:23:59 +00004259 FD = SynthBlockInitFunctionDecl(Buf.c_str());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004260 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Anders Carlsson7ef181c2009-07-31 00:48:10 +00004261 castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4262 CastExpr::CK_Unknown, Arg,
Ted Kremenek0c97e042009-02-07 01:47:29 +00004263 Context->VoidPtrTy, SourceLocation(),
4264 SourceLocation());
Steve Naroffd0419d62008-10-29 21:23:59 +00004265 InitExprs.push_back(castExpr);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004266 }
4267 // Add initializers for any closure decl refs.
4268 if (BlockDeclRefs.size()) {
Steve Naroffd0419d62008-10-29 21:23:59 +00004269 Expr *Exp;
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004270 // Output all "by copy" declarations.
4271 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4272 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004273 if (isObjCType((*I)->getType())) {
Steve Naroffd0419d62008-10-29 21:23:59 +00004274 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattnerd120b9e2008-11-24 03:54:41 +00004275 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004276 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroffd896f4b2008-12-11 21:05:33 +00004277 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00004278 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004279 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Anders Carlsson7ef181c2009-07-31 00:48:10 +00004280 Exp = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4281 CastExpr::CK_Unknown, Arg,
4282 Context->VoidPtrTy,
4283 SourceLocation(),
Ted Kremenek0c97e042009-02-07 01:47:29 +00004284 SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004285 } else {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00004286 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004287 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004288 }
Steve Naroffd0419d62008-10-29 21:23:59 +00004289 InitExprs.push_back(Exp);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004290 }
4291 // Output all "by ref" declarations.
4292 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4293 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00004294 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004295 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4296 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Steve Naroffd0419d62008-10-29 21:23:59 +00004297 Context->getPointerType(Exp->getType()),
4298 SourceLocation());
Steve Naroff362c7562008-11-14 21:36:12 +00004299 InitExprs.push_back(Exp);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004300 }
4301 }
Ted Kremenek362abcd2009-02-09 20:51:47 +00004302 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4303 FType, SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004304 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004305 Context->getPointerType(NewRep->getType()),
4306 SourceLocation());
Anders Carlsson7ef181c2009-07-31 00:48:10 +00004307 NewRep = new (Context) CStyleCastExpr(FType, CastExpr::CK_Unknown, NewRep,
4308 FType, SourceLocation(),
Ted Kremenek0c97e042009-02-07 01:47:29 +00004309 SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004310 BlockDeclRefs.clear();
4311 BlockByRefDecls.clear();
4312 BlockByCopyDecls.clear();
4313 ImportedBlockDecls.clear();
4314 return NewRep;
4315}
4316
4317//===----------------------------------------------------------------------===//
4318// Function Body / Expression rewriting
4319//===----------------------------------------------------------------------===//
4320
Steve Naroff0e948412008-12-04 16:24:46 +00004321// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4322// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4323// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4324// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4325// Since the rewriter isn't capable of rewriting rewritten code, it's important
4326// we get this right.
4327void RewriteObjC::CollectPropertySetters(Stmt *S) {
4328 // Perform a bottom up traversal of all children.
4329 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4330 CI != E; ++CI)
4331 if (*CI)
4332 CollectPropertySetters(*CI);
4333
4334 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4335 if (BinOp->isAssignmentOp()) {
4336 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4337 PropSetters[PRE] = BinOp;
4338 }
4339 }
4340}
4341
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004342Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4343 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4344 isa<DoStmt>(S) || isa<ForStmt>(S))
4345 Stmts.push_back(S);
4346 else if (isa<ObjCForCollectionStmt>(S)) {
4347 Stmts.push_back(S);
4348 ObjCBcLabelNo.push_back(++BcLabelCount);
4349 }
4350
4351 SourceRange OrigStmtRange = S->getSourceRange();
4352
4353 // Perform a bottom up rewrite of all children.
4354 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4355 CI != E; ++CI)
4356 if (*CI) {
4357 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
4358 if (newStmt)
4359 *CI = newStmt;
4360 }
4361
4362 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4363 // Rewrite the block body in place.
4364 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4365
4366 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroff80c54752008-10-29 18:15:37 +00004367 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
4368 RewrittenBlockExprs[BE] = Str;
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004369
4370 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4371 //blockTranscribed->dump();
Steve Naroff80c54752008-10-29 18:15:37 +00004372 ReplaceStmt(S, blockTranscribed);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004373 return blockTranscribed;
4374 }
4375 // Handle specific things.
4376 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4377 return RewriteAtEncode(AtEncode);
4378
4379 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4380 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4381
Steve Naroff0e948412008-12-04 16:24:46 +00004382 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4383 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4384 if (BinOp) {
4385 // Because the rewriter doesn't allow us to rewrite rewritten code,
4386 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffedb4bc92008-12-09 12:56:34 +00004387 DisableReplaceStmt = true;
4388 // Save the source range. Even if we disable the replacement, the
4389 // rewritten node will have been inserted into the tree. If the synthesized
4390 // node is at the 'end', the rewriter will fail. Consider this:
4391 // self.errorHandler = handler ? handler :
4392 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4393 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroff0e948412008-12-04 16:24:46 +00004394 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroffedb4bc92008-12-09 12:56:34 +00004395 DisableReplaceStmt = false;
Steve Naroff102c3f22008-12-04 23:50:32 +00004396 //
4397 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4398 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4399 // to see the original expression). Consider this example:
4400 //
4401 // Foo *obj1, *obj2;
4402 //
4403 // obj1.i = [obj2 rrrr];
4404 //
4405 // 'BinOp' for the previous expression looks like:
4406 //
4407 // (BinaryOperator 0x231ccf0 'int' '='
4408 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4409 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4410 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4411 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4412 //
4413 // 'newStmt' represents the rewritten message expression. For example:
4414 //
4415 // (CallExpr 0x231d300 'id':'struct objc_object *'
4416 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4417 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4418 // (CStyleCastExpr 0x231d220 'void *'
4419 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4420 //
4421 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4422 // can be used as the setter argument. ReplaceStmt() will still 'see'
4423 // the original RHS (since we haven't altered BinOp).
4424 //
4425 // This implies the Rewrite* routines can no longer delete the original
4426 // node. As a result, we now leak the original AST nodes.
4427 //
Steve Naroffedb4bc92008-12-09 12:56:34 +00004428 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroff0e948412008-12-04 16:24:46 +00004429 } else {
4430 return RewritePropertyGetter(PropRefExpr);
Steve Narofff6ce8a12008-12-03 00:56:33 +00004431 }
4432 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004433 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4434 return RewriteAtSelector(AtSelector);
4435
4436 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4437 return RewriteObjCStringLiteral(AtString);
4438
4439 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff0e948412008-12-04 16:24:46 +00004440#if 0
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004441 // Before we rewrite it, put the original message expression in a comment.
4442 SourceLocation startLoc = MessExpr->getLocStart();
4443 SourceLocation endLoc = MessExpr->getLocEnd();
4444
4445 const char *startBuf = SM->getCharacterData(startLoc);
4446 const char *endBuf = SM->getCharacterData(endLoc);
4447
4448 std::string messString;
4449 messString += "// ";
4450 messString.append(startBuf, endBuf-startBuf+1);
4451 messString += "\n";
4452
4453 // FIXME: Missing definition of
4454 // InsertText(clang::SourceLocation, char const*, unsigned int).
4455 // InsertText(startLoc, messString.c_str(), messString.size());
4456 // Tried this, but it didn't work either...
4457 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff0e948412008-12-04 16:24:46 +00004458#endif
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004459 return RewriteMessageExpr(MessExpr);
4460 }
4461
4462 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4463 return RewriteObjCTryStmt(StmtTry);
4464
4465 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4466 return RewriteObjCSynchronizedStmt(StmtTry);
4467
4468 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4469 return RewriteObjCThrowStmt(StmtThrow);
4470
4471 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4472 return RewriteObjCProtocolExpr(ProtocolExp);
4473
4474 if (ObjCForCollectionStmt *StmtForCollection =
4475 dyn_cast<ObjCForCollectionStmt>(S))
4476 return RewriteObjCForCollectionStmt(StmtForCollection,
4477 OrigStmtRange.getEnd());
4478 if (BreakStmt *StmtBreakStmt =
4479 dyn_cast<BreakStmt>(S))
4480 return RewriteBreakStmt(StmtBreakStmt);
4481 if (ContinueStmt *StmtContinueStmt =
4482 dyn_cast<ContinueStmt>(S))
4483 return RewriteContinueStmt(StmtContinueStmt);
4484
4485 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4486 // and cast exprs.
4487 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4488 // FIXME: What we're doing here is modifying the type-specifier that
4489 // precedes the first Decl. In the future the DeclGroup should have
4490 // a separate type-specifier that we can rewrite.
4491 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4492
4493 // Blocks rewrite rules.
4494 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4495 DI != DE; ++DI) {
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00004496 Decl *SD = *DI;
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004497 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffd896f4b2008-12-11 21:05:33 +00004498 if (isTopLevelBlockPointerType(ND->getType()))
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004499 RewriteBlockPointerDecl(ND);
4500 else if (ND->getType()->isFunctionPointerType())
4501 CheckFunctionPointerDecl(ND->getType(), ND);
4502 }
4503 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroffd896f4b2008-12-11 21:05:33 +00004504 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004505 RewriteBlockPointerDecl(TD);
4506 else if (TD->getUnderlyingType()->isFunctionPointerType())
4507 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4508 }
4509 }
4510 }
4511
4512 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4513 RewriteObjCQualifiedInterfaceTypes(CE);
4514
4515 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4516 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4517 assert(!Stmts.empty() && "Statement stack is empty");
4518 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4519 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4520 && "Statement stack mismatch");
4521 Stmts.pop_back();
4522 }
4523 // Handle blocks rewriting.
4524 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4525 if (BDRE->isByRef())
Steve Naroff450d2fc2009-04-29 16:37:50 +00004526 return RewriteBlockDeclRefExpr(BDRE);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004527 }
4528 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff85eb17b2008-10-30 10:07:53 +00004529 if (CE->getCallee()->getType()->isBlockPointerType()) {
4530 Stmt *BlockCall = SynthesizeBlockCall(CE);
4531 ReplaceStmt(S, BlockCall);
4532 return BlockCall;
4533 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004534 }
Steve Naroff7f1412d2008-11-03 23:29:32 +00004535 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004536 RewriteCastExpr(CE);
4537 }
4538#if 0
4539 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00004540 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004541 // Get the new text.
4542 std::string SStr;
4543 llvm::raw_string_ostream Buf(SStr);
Eli Friedman011a7362009-05-30 05:19:26 +00004544 Replacement->printPretty(Buf, *Context);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004545 const std::string &Str = Buf.str();
4546
4547 printf("CAST = %s\n", &Str[0]);
4548 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4549 delete S;
4550 return Replacement;
4551 }
4552#endif
4553 // Return this stmt unmodified.
4554 return S;
4555}
4556
4557/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4558/// main file of the input.
4559void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4560 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffee8d4972008-12-17 00:20:22 +00004561 if (FD->isOverloadedOperator())
4562 return;
4563
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004564 // Since function prototypes don't have ParmDecl's, we check the function
4565 // prototype. This enables us to rewrite function declarations and
4566 // definitions using the same code.
Douglas Gregor4fa58902009-02-26 23:50:07 +00004567 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004568
Sebastian Redlbc9ef252009-04-26 20:35:05 +00004569 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argiris Kirtzidisccb9efe2009-06-30 02:35:26 +00004570 if (CompoundStmt *Body = FD->getCompoundBody()) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004571 CurFunctionDef = FD;
Steve Naroff0e948412008-12-04 16:24:46 +00004572 CollectPropertySetters(Body);
Steve Narofffbed6802008-12-08 16:43:47 +00004573 CurrentBody = Body;
Ted Kremenek30916072009-03-12 18:33:24 +00004574 Body =
4575 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4576 FD->setBody(Body);
Steve Narofffbed6802008-12-08 16:43:47 +00004577 CurrentBody = 0;
4578 if (PropParentMap) {
4579 delete PropParentMap;
4580 PropParentMap = 0;
4581 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004582 // This synthesizes and inserts the block "impl" struct, invoke function,
4583 // and any copy/dispose helper functions.
4584 InsertBlockLiteralsWithinFunction(FD);
4585 CurFunctionDef = 0;
4586 }
4587 return;
4588 }
4589 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argiris Kirtzidisccb9efe2009-06-30 02:35:26 +00004590 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004591 CurMethodDef = MD;
Steve Naroff0e948412008-12-04 16:24:46 +00004592 CollectPropertySetters(Body);
Steve Narofffbed6802008-12-08 16:43:47 +00004593 CurrentBody = Body;
Ted Kremenek30916072009-03-12 18:33:24 +00004594 Body =
4595 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4596 MD->setBody(Body);
Steve Narofffbed6802008-12-08 16:43:47 +00004597 CurrentBody = 0;
4598 if (PropParentMap) {
4599 delete PropParentMap;
4600 PropParentMap = 0;
4601 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004602 InsertBlockLiteralsWithinMethod(MD);
4603 CurMethodDef = 0;
4604 }
4605 }
4606 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
4607 ClassImplementation.push_back(CI);
4608 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4609 CategoryImplementation.push_back(CI);
4610 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4611 RewriteForwardClassDecl(CD);
4612 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4613 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroffd896f4b2008-12-11 21:05:33 +00004614 if (isTopLevelBlockPointerType(VD->getType()))
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004615 RewriteBlockPointerDecl(VD);
Steve Naroff80c54752008-10-29 18:15:37 +00004616 else if (VD->getType()->isFunctionPointerType()) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004617 CheckFunctionPointerDecl(VD->getType(), VD);
4618 if (VD->getInit()) {
Steve Naroff7f1412d2008-11-03 23:29:32 +00004619 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004620 RewriteCastExpr(CE);
4621 }
4622 }
4623 }
Steve Naroff80c54752008-10-29 18:15:37 +00004624 if (VD->getInit()) {
4625 GlobalVarDecl = VD;
Steve Naroff0e948412008-12-04 16:24:46 +00004626 CollectPropertySetters(VD->getInit());
Steve Narofffbed6802008-12-08 16:43:47 +00004627 CurrentBody = VD->getInit();
Steve Naroff80c54752008-10-29 18:15:37 +00004628 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Narofffbed6802008-12-08 16:43:47 +00004629 CurrentBody = 0;
4630 if (PropParentMap) {
4631 delete PropParentMap;
4632 PropParentMap = 0;
4633 }
Douglas Gregor24afd4a2008-11-17 14:58:09 +00004634 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattnerd120b9e2008-11-24 03:54:41 +00004635 VD->getNameAsCString());
Steve Naroff80c54752008-10-29 18:15:37 +00004636 GlobalVarDecl = 0;
4637
4638 // This is needed for blocks.
Steve Naroff7f1412d2008-11-03 23:29:32 +00004639 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff80c54752008-10-29 18:15:37 +00004640 RewriteCastExpr(CE);
4641 }
4642 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004643 return;
4644 }
4645 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroffd896f4b2008-12-11 21:05:33 +00004646 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004647 RewriteBlockPointerDecl(TD);
4648 else if (TD->getUnderlyingType()->isFunctionPointerType())
4649 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4650 return;
4651 }
4652 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
4653 if (RD->isDefinition()) {
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00004654 for (RecordDecl::field_iterator i = RD->field_begin(),
4655 e = RD->field_end(); i != e; ++i) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004656 FieldDecl *FD = *i;
Steve Naroffd896f4b2008-12-11 21:05:33 +00004657 if (isTopLevelBlockPointerType(FD->getType()))
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004658 RewriteBlockPointerDecl(FD);
4659 }
4660 }
4661 return;
4662 }
4663 // Nothing yet.
4664}
4665
Chris Lattner2a594d02009-03-28 04:11:33 +00004666void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004667 // Get the top-level buffer that this corresponds to.
4668
4669 // Rewrite tabs if we care.
4670 //RewriteTabs();
4671
4672 if (Diags.hasErrorOccurred())
4673 return;
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004674
4675 RewriteInclude();
4676
Steve Naroff450d2fc2009-04-29 16:37:50 +00004677 // Here's a great place to add any extra declarations that may be needed.
4678 // Write out meta data for each @protocol(<expr>).
4679 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
4680 E = ProtocolExprDecls.end(); I != E; ++I)
4681 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
4682
Chris Lattnerf4f776a2009-01-17 06:22:33 +00004683 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004684 Preamble.c_str(), Preamble.size(), false);
Steve Naroff901d8fd2008-11-14 14:10:01 +00004685 if (ClassImplementation.size() || CategoryImplementation.size())
4686 RewriteImplementations();
Steve Naroff450d2fc2009-04-29 16:37:50 +00004687
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004688 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4689 // we are done.
4690 if (const RewriteBuffer *RewriteBuf =
4691 Rewrite.getRewriteBufferFor(MainFileID)) {
4692 //printf("Changed:\n");
4693 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4694 } else {
4695 fprintf(stderr, "No changes\n");
4696 }
Steve Naroff21658f62008-11-13 20:07:04 +00004697
Steve Naroff450d2fc2009-04-29 16:37:50 +00004698 if (ClassImplementation.size() || CategoryImplementation.size() ||
4699 ProtocolExprDecls.size()) {
Steve Naroff901d8fd2008-11-14 14:10:01 +00004700 // Rewrite Objective-c meta data*
4701 std::string ResultStr;
4702 SynthesizeMetaDataIntoBuffer(ResultStr);
4703 // Emit metadata.
4704 *OutFile << ResultStr;
4705 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004706 OutFile->flush();
4707}
4708