blob: de45e1a2bea722f249c853978b3cce6fa1b0820f [file] [log] [blame]
Steve Naroffb29b4272008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattner77cd2a02007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-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 Lattner77cd2a02007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Eli Friedman39d7c4d2009-05-18 22:50:54 +000014#include "clang/Frontend/ASTConsumers.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Steve Naroff8599e7a2008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner07506182007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner26de4652007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000023#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000024#include "llvm/ADT/SmallPtrSet.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000025#include "llvm/ADT/OwningPtr.h"
Chris Lattner26de4652007-12-02 01:13:47 +000026#include "llvm/Support/MemoryBuffer.h"
Dan Gohman63e2dcc2008-05-21 20:19:16 +000027#include "llvm/Support/Streams.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000028#include "llvm/Support/raw_ostream.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000029using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000030using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000031
Chris Lattner77cd2a02007-10-11 00:43:27 +000032namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000033 class RewriteObjC : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000034 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000035 Diagnostic &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000036 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000037 unsigned RewriteFailedDiag;
Steve Naroff8c565152008-12-05 17:03:39 +000038 unsigned TryFinallyContainsReturnDiag;
39
Chris Lattner01c57482007-10-17 22:35:30 +000040 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000041 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000042 TranslationUnitDecl *TUDecl;
Chris Lattner2b2453a2009-01-17 06:22:33 +000043 FileID MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000044 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000045 SourceLocation LastIncLoc;
Steve Naroffba92b2e2008-03-27 22:29:16 +000046
Ted Kremeneka526c5c2008-01-07 19:49:32 +000047 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
48 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
49 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +000050 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000051 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
52 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000053 llvm::SmallVector<Stmt *, 32> Stmts;
54 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroff621edce2009-04-29 16:37:50 +000055 // Remember all the @protocol(<expr>) expressions.
56 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Steve Naroffebf2b562007-10-23 23:50:29 +000057
Steve Naroffd82a9ab2008-03-15 00:55:56 +000058 unsigned NumObjCStringLiterals;
59
Steve Naroffebf2b562007-10-23 23:50:29 +000060 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000061 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000062 FunctionDecl *MsgSendStretFunctionDecl;
63 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000064 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000065 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000066 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000067 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000068 FunctionDecl *CFStringFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000069 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000070
Steve Naroffbeaf2992007-11-03 11:27:19 +000071 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000072 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000073 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000074
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000075 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000076 int BcLabelCount;
77
Steve Naroff874e2322007-11-15 10:28:18 +000078 // Needed for super.
Steve Naroff54055232008-10-27 17:20:55 +000079 ObjCMethodDecl *CurMethodDef;
Steve Naroff874e2322007-11-15 10:28:18 +000080 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +000081 RecordDecl *ConstantStringDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000082
Steve Naroff621edce2009-04-29 16:37:50 +000083 TypeDecl *ProtocolTypeDecl;
84 QualType getProtocolType();
85
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +000086 // Needed for header files being rewritten
87 bool IsHeader;
88
Steve Naroffa7b402d2008-03-28 22:26:09 +000089 std::string InFileName;
Eli Friedman66d6f042009-05-18 22:20:00 +000090 llvm::raw_ostream* OutFile;
Eli Friedmanc6d656e2009-05-18 22:39:16 +000091
92 bool SilenceRewriteMacroWarning;
93
Steve Naroffba92b2e2008-03-27 22:29:16 +000094 std::string Preamble;
Steve Naroff54055232008-10-27 17:20:55 +000095
96 // Block expressions.
97 llvm::SmallVector<BlockExpr *, 32> Blocks;
98 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
99 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Steve Naroffba92b2e2008-03-27 22:29:16 +0000100
Steve Naroff54055232008-10-27 17:20:55 +0000101 // Block related declarations.
102 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
103 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
104 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
105
106 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
107
Steve Naroffc77a6362008-12-04 16:24:46 +0000108 // This maps a property to it's assignment statement.
109 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Naroff8599e7a2008-12-08 16:43:47 +0000110 // This maps a property to it's synthesied message expression.
111 // This allows us to rewrite chained getters (e.g. o.a.b.c).
112 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
113
Steve Naroff4c3580e2008-12-04 23:50:32 +0000114 // This maps an original source AST to it's rewritten form. This allows
115 // us to avoid rewriting the same node twice (which is very uncommon).
116 // This is needed to support some of the exotic property rewriting.
117 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000118
Steve Naroff54055232008-10-27 17:20:55 +0000119 FunctionDecl *CurFunctionDef;
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000120 VarDecl *GlobalVarDecl;
121
Steve Naroffb619d952008-12-09 12:56:34 +0000122 bool DisableReplaceStmt;
123
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000124 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000125 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000126 virtual void Initialize(ASTContext &context);
127
Chris Lattnerf04da132007-10-24 17:06:59 +0000128 // Top Level Driver code.
Chris Lattner682bf922009-03-29 16:50:03 +0000129 virtual void HandleTopLevelDecl(DeclGroupRef D) {
130 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
131 HandleTopLevelSingleDecl(*I);
132 }
133 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000134 void HandleDeclInMainFile(Decl *D);
Eli Friedman66d6f042009-05-18 22:20:00 +0000135 RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000136 Diagnostic &D, const LangOptions &LOpts,
137 bool silenceMacroWarn);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000138
139 ~RewriteObjC() {}
140
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000141 virtual void HandleTranslationUnit(ASTContext &C);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000142
143 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000144 Stmt *ReplacingStmt = ReplacedNodes[Old];
145
146 if (ReplacingStmt)
147 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000148
Steve Naroffb619d952008-12-09 12:56:34 +0000149 if (DisableReplaceStmt)
150 return; // Used when rewriting the assignment of a property setter.
151
Steve Naroff4c3580e2008-12-04 23:50:32 +0000152 // If replacement succeeded or warning disabled return with no warning.
153 if (!Rewrite.ReplaceStmt(Old, New)) {
154 ReplacedNodes[Old] = New;
155 return;
156 }
157 if (SilenceRewriteMacroWarning)
158 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000159 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
160 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000161 }
Steve Naroffb619d952008-12-09 12:56:34 +0000162
163 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
164 // Measaure the old text.
165 int Size = Rewrite.getRangeSize(SrcRange);
166 if (Size == -1) {
167 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
168 << Old->getSourceRange();
169 return;
170 }
171 // Get the new text.
172 std::string SStr;
173 llvm::raw_string_ostream S(SStr);
Chris Lattnere4f21422009-06-30 01:26:17 +0000174 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroffb619d952008-12-09 12:56:34 +0000175 const std::string &Str = S.str();
176
177 // If replacement succeeded or warning disabled return with no warning.
178 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, &Str[0], Str.size())) {
179 ReplacedNodes[Old] = New;
180 return;
181 }
182 if (SilenceRewriteMacroWarning)
183 return;
184 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
185 << Old->getSourceRange();
186 }
187
Steve Naroffba92b2e2008-03-27 22:29:16 +0000188 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
189 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000190 // If insertion succeeded or warning disabled return with no warning.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000191 if (!Rewrite.InsertText(Loc, StrData, StrLen, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000192 SilenceRewriteMacroWarning)
193 return;
194
195 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
196 }
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000197
Chris Lattneraadaf782008-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 Lattnerf04da132007-10-24 17:06:59 +0000205
Chris Lattneraadaf782008-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.
209 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
210 SilenceRewriteMacroWarning)
211 return;
212
213 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
214 }
215
Chris Lattnerf04da132007-10-24 17:06:59 +0000216 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000217 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000218 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000219 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000220 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffa0876e82008-12-02 17:36:43 +0000221 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
222 ObjCImplementationDecl *IMD,
223 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000224 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000225 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000226 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
227 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
228 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
229 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
230 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000231 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000232 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000233 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff4f95b752008-07-29 18:15:38 +0000234 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000235 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000236 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000237 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000238 QualType getConstantStringStructType();
Steve Naroffbaf58c32008-05-31 14:15:04 +0000239 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Chris Lattner311ff022007-10-16 22:36:42 +0000240
Chris Lattnerf04da132007-10-24 17:06:59 +0000241 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000242 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroffc77a6362008-12-04 16:24:46 +0000243 void CollectPropertySetters(Stmt *S);
244
Steve Naroff8599e7a2008-12-08 16:43:47 +0000245 Stmt *CurrentBody;
246 ParentMap *PropParentMap; // created lazily.
247
Chris Lattnere64b7772007-10-24 16:57:36 +0000248 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000249 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroffc77a6362008-12-04 16:24:46 +0000250 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Steve Naroffb619d952008-12-09 12:56:34 +0000251 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
252 SourceRange SrcRange);
Steve Naroffb42f8412007-11-05 14:50:49 +0000253 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000254 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000255 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000256 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroff8c565152008-12-05 17:03:39 +0000257 void WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000258 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000259 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000260 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
261 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
262 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000263 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
264 SourceLocation OrigEnd);
Steve Naroff934f2762007-10-24 22:48:43 +0000265 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
266 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000267 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000268 Stmt *RewriteBreakStmt(BreakStmt *S);
269 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000270 void SynthCountByEnumWithState(std::string &buf);
271
Steve Naroff09b266e2007-10-30 23:14:51 +0000272 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000273 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000274 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000275 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000276 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000277 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000278 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000279 void SynthSelGetUidFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000280 void SynthSuperContructorFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000281
Chris Lattnerf04da132007-10-24 17:06:59 +0000282 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000283 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000284 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000285
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000286 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000287 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000288
Douglas Gregor653f1b12009-04-23 01:02:12 +0000289 template<typename MethodIterator>
290 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
291 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000292 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000293 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000294 const char *ClassName,
295 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000296
Steve Naroff621edce2009-04-29 16:37:50 +0000297 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
298 const char *prefix,
299 const char *ClassName,
300 std::string &Result);
301 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
302 const char *prefix,
303 const char *ClassName,
304 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000305 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000306 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000307 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
308 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000309 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000310 void RewriteImplementations();
311 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Steve Naroff54055232008-10-27 17:20:55 +0000312
313 // Block rewriting.
Douglas Gregor72564e72009-02-26 23:50:07 +0000314 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff54055232008-10-27 17:20:55 +0000315 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
316
317 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
318 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
319
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000320 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000321 void RewriteBlockCall(CallExpr *Exp);
322 void RewriteBlockPointerDecl(NamedDecl *VD);
Steve Naroff621edce2009-04-29 16:37:50 +0000323 Stmt *RewriteBlockDeclRefExpr(BlockDeclRefExpr *VD);
Steve Naroff54055232008-10-27 17:20:55 +0000324 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
325
326 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
327 const char *funcName, std::string Tag);
328 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
329 const char *funcName, std::string Tag);
330 std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
331 bool hasCopyDisposeHelpers);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +0000332 Stmt *SynthesizeBlockCall(CallExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000333 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
334 const char *FunName);
335
336 void CollectBlockDeclRefInfo(BlockExpr *Exp);
337 void GetBlockCallExprs(Stmt *S);
338 void GetBlockDeclRefExprs(Stmt *S);
339
340 // We avoid calling Type::isBlockPointerType(), since it operates on the
341 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000342 bool isTopLevelBlockPointerType(QualType T) {
343 return isa<BlockPointerType>(T);
344 }
Steve Naroff54055232008-10-27 17:20:55 +0000345
346 // FIXME: This predicate seems like it would be useful to add to ASTContext.
347 bool isObjCType(QualType T) {
348 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
349 return false;
350
351 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
352
353 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
354 OCT == Context->getCanonicalType(Context->getObjCClassType()))
355 return true;
356
Ted Kremenek1a1a6e22009-07-16 19:58:26 +0000357 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Steve Naroff54055232008-10-27 17:20:55 +0000358 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000359 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff54055232008-10-27 17:20:55 +0000360 return true;
361 }
362 return false;
363 }
364 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000365 void GetExtentOfArgList(const char *Name, const char *&LParen,
366 const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000367 void RewriteCastExpr(CStyleCastExpr *CE);
Steve Narofffa15fd92008-10-28 20:29:00 +0000368
369 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000370 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Steve Naroff621edce2009-04-29 16:37:50 +0000371
372 void QuoteDoublequotes(std::string &From, std::string &To) {
373 for(unsigned i = 0; i < From.length(); i++) {
374 if (From[i] == '"')
375 To += "\\\"";
376 else
377 To += From[i];
378 }
379 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000380 };
381}
382
Douglas Gregor72564e72009-02-26 23:50:07 +0000383void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
Steve Naroff54055232008-10-27 17:20:55 +0000384 NamedDecl *D) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000385 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
386 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000387 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000388 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000389 // All the args are checked/rewritten. Don't call twice!
390 RewriteBlockPointerDecl(D);
391 break;
392 }
393 }
394}
395
396void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek1a1a6e22009-07-16 19:58:26 +0000397 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000398 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000399 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000400}
401
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000402static bool IsHeaderFile(const std::string &Filename) {
403 std::string::size_type DotPos = Filename.rfind('.');
404
405 if (DotPos == std::string::npos) {
406 // no file extension
407 return false;
408 }
409
410 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
411 // C header: .h
412 // C++ header: .hh or .H;
413 return Ext == "h" || Ext == "hh" || Ext == "H";
414}
415
Eli Friedman66d6f042009-05-18 22:20:00 +0000416RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000417 Diagnostic &D, const LangOptions &LOpts,
418 bool silenceMacroWarn)
419 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
420 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000421 IsHeader = IsHeaderFile(inFile);
Steve Naroffa7b402d2008-03-28 22:26:09 +0000422 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
423 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff8c565152008-12-05 17:03:39 +0000424 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000425 "rewriter doesn't support user-specified control flow semantics "
426 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000427}
428
Eli Friedmanbce831b2009-05-18 22:29:17 +0000429ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
430 llvm::raw_ostream* OS,
431 Diagnostic &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000432 const LangOptions &LOpts,
433 bool SilenceRewriteMacroWarning) {
434 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000435}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000436
Steve Naroffb29b4272008-04-14 22:03:09 +0000437void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000438 Context = &context;
439 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000440 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000441 MsgSendFunctionDecl = 0;
442 MsgSendSuperFunctionDecl = 0;
443 MsgSendStretFunctionDecl = 0;
444 MsgSendSuperStretFunctionDecl = 0;
445 MsgSendFpretFunctionDecl = 0;
446 GetClassFunctionDecl = 0;
447 GetMetaClassFunctionDecl = 0;
448 SelGetUidFunctionDecl = 0;
449 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000450 ConstantStringClassReference = 0;
451 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000452 CurMethodDef = 0;
453 CurFunctionDef = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000454 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000455 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000456 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000457 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000458 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000459 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000460 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000461 PropParentMap = 0;
462 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000463 DisableReplaceStmt = false;
464
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000465 // Get the ID and start/end of the main file.
466 MainFileID = SM->getMainFileID();
467 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
468 MainFileStart = MainBuf->getBufferStart();
469 MainFileEnd = MainBuf->getBufferEnd();
Steve Naroffba92b2e2008-03-27 22:29:16 +0000470
Chris Lattner2c78b872009-04-14 23:22:57 +0000471 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000472
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000473 // declaring objc_selector outside the parameter list removes a silly
474 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000475 if (IsHeader)
Steve Naroff62c26322009-02-03 20:39:18 +0000476 Preamble = "#pragma once\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000477 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff46a98a72008-12-23 20:11:22 +0000478 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000479 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000480 if (LangOpts.Microsoft) {
481 // Add a constructor for creating temporary objects.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000482 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
483 ": ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000484 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000485 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000486 Preamble += "};\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000487 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
488 Preamble += "typedef struct objc_object Protocol;\n";
489 Preamble += "#define _REWRITER_typedef_Protocol\n";
490 Preamble += "#endif\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000491 if (LangOpts.Microsoft) {
492 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
493 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
494 } else
495 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
496 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000497 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000498 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000499 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000500 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000501 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000502 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000503 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000504 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000505 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000506 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000507 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000508 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000509 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000510 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
511 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
512 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
513 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
514 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000515 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000516 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000517 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
518 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
519 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000520 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
521 Preamble += "struct __objcFastEnumerationState {\n\t";
522 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000523 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000524 Preamble += "unsigned long *mutationsPtr;\n\t";
525 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000526 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000527 Preamble += "#define __FASTENUMERATIONSTATE\n";
528 Preamble += "#endif\n";
529 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
530 Preamble += "struct __NSConstantStringImpl {\n";
531 Preamble += " int *isa;\n";
532 Preamble += " int flags;\n";
533 Preamble += " char *str;\n";
534 Preamble += " long length;\n";
535 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000536 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
537 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
538 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000539 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000540 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000541 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
542 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000543 // Blocks preamble.
544 Preamble += "#ifndef BLOCK_IMPL\n";
545 Preamble += "#define BLOCK_IMPL\n";
546 Preamble += "struct __block_impl {\n";
547 Preamble += " void *isa;\n";
548 Preamble += " int Flags;\n";
549 Preamble += " int Size;\n";
550 Preamble += " void *FuncPtr;\n";
551 Preamble += "};\n";
Steve Naroff5bc60d02008-12-16 15:50:30 +0000552 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
553 Preamble += "__OBJC_RW_STATICIMPORT void _Block_object_assign(void *, const void *, const int);\n";
554 Preamble += "__OBJC_RW_STATICIMPORT void _Block_object_dispose(const void *, const int);\n";
555 Preamble += "__OBJC_RW_STATICIMPORT void *_NSConcreteGlobalBlock[32];\n";
556 Preamble += "__OBJC_RW_STATICIMPORT void *_NSConcreteStackBlock[32];\n";
Steve Naroff54055232008-10-27 17:20:55 +0000557 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000558 if (LangOpts.Microsoft) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000559 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
560 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000561 Preamble += "#define __attribute__(X)\n";
562 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000563}
564
565
Chris Lattnerf04da132007-10-24 17:06:59 +0000566//===----------------------------------------------------------------------===//
567// Top Level Driver Code
568//===----------------------------------------------------------------------===//
569
Chris Lattner682bf922009-03-29 16:50:03 +0000570void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000571 // Two cases: either the decl could be in the main file, or it could be in a
572 // #included file. If the former, rewrite it now. If the later, check to see
573 // if we rewrote the #include/#import.
574 SourceLocation Loc = D->getLocation();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000575 Loc = SM->getInstantiationLoc(Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000576
577 // If this is for a builtin, ignore it.
578 if (Loc.isInvalid()) return;
579
Steve Naroffebf2b562007-10-23 23:50:29 +0000580 // Look for built-in declarations that we need to refer during the rewrite.
581 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000582 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000583 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000584 // declared in <Foundation/NSString.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +0000585 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000586 ConstantStringClassReference = FVD;
587 return;
588 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000589 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000590 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000591 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000592 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000593 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000594 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000595 } else if (ObjCForwardProtocolDecl *FP =
596 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000597 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000598 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
599 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000600 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
601 DIEnd = LSD->decls_end();
Douglas Gregord0434102009-01-09 00:49:46 +0000602 DI != DIEnd; ++DI)
Chris Lattner682bf922009-03-29 16:50:03 +0000603 HandleTopLevelSingleDecl(*DI);
Steve Naroffebf2b562007-10-23 23:50:29 +0000604 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000605 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000606 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000607 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000608}
609
Chris Lattnerf04da132007-10-24 17:06:59 +0000610//===----------------------------------------------------------------------===//
611// Syntactic (non-AST) Rewriting Code
612//===----------------------------------------------------------------------===//
613
Steve Naroffb29b4272008-04-14 22:03:09 +0000614void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000615 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000616 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
617 const char *MainBufStart = MainBuf.first;
618 const char *MainBufEnd = MainBuf.second;
619 size_t ImportLen = strlen("import");
620 size_t IncludeLen = strlen("include");
621
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000622 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000623 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
624 if (*BufPtr == '#') {
625 if (++BufPtr == MainBufEnd)
626 return;
627 while (*BufPtr == ' ' || *BufPtr == '\t')
628 if (++BufPtr == MainBufEnd)
629 return;
630 if (!strncmp(BufPtr, "import", ImportLen)) {
631 // replace import with include
632 SourceLocation ImportLoc =
633 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000634 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000635 BufPtr += ImportLen;
636 }
637 }
638 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000639}
640
Steve Naroffb29b4272008-04-14 22:03:09 +0000641void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000642 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
643 const char *MainBufStart = MainBuf.first;
644 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000645
Chris Lattnerf04da132007-10-24 17:06:59 +0000646 // Loop over the whole file, looking for tabs.
647 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
648 if (*BufPtr != '\t')
649 continue;
650
651 // Okay, we found a tab. This tab will turn into at least one character,
652 // but it depends on which 'virtual column' it is in. Compute that now.
653 unsigned VCol = 0;
654 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
655 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
656 ++VCol;
657
658 // Okay, now that we know the virtual column, we know how many spaces to
659 // insert. We assume 8-character tab-stops.
660 unsigned Spaces = 8-(VCol & 7);
661
662 // Get the location of the tab.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000663 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
664 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattnerf04da132007-10-24 17:06:59 +0000665
666 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000667 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000668 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000669}
670
Steve Naroffeb0646c2008-12-02 15:48:25 +0000671static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
672 ObjCIvarDecl *OID) {
673 std::string S;
674 S = "((struct ";
675 S += ClassDecl->getIdentifier()->getName();
676 S += "_IMPL *)self)->";
677 S += OID->getNameAsCString();
678 return S;
679}
680
Steve Naroffa0876e82008-12-02 17:36:43 +0000681void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
682 ObjCImplementationDecl *IMD,
683 ObjCCategoryImplDecl *CID) {
Steve Naroffd40910b2008-12-01 20:33:01 +0000684 SourceLocation startLoc = PID->getLocStart();
685 InsertText(startLoc, "// ", 3);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000686 const char *startBuf = SM->getCharacterData(startLoc);
687 assert((*startBuf == '@') && "bogus @synthesize location");
688 const char *semiBuf = strchr(startBuf, ';');
689 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000690 SourceLocation onePastSemiLoc =
691 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000692
693 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
694 return; // FIXME: is this correct?
695
696 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000697 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000698 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000699 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000700
701 if (!OID)
702 return;
703
704 std::string Getr;
705 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
706 Getr += "{ ";
707 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroff3539cdb2008-12-02 17:54:50 +0000708 // FIXME: deal with code generation implications for various property
709 // attributes (copy, retain, nonatomic).
710 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000711 Getr += "return " + getIvarAccessString(ClassDecl, OID);
712 Getr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000713 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroffeb0646c2008-12-02 15:48:25 +0000714 if (PD->isReadOnly())
715 return;
716
717 // Generate the 'setter' function.
718 std::string Setr;
719 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000720 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000721 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff3539cdb2008-12-02 17:54:50 +0000722 // FIXME: deal with code generation implications for various property
723 // attributes (copy, retain, nonatomic).
Steve Naroff15f081d2008-12-03 00:56:33 +0000724 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000725 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Steve Narofff4312dc2008-12-11 19:29:16 +0000726 Setr += PD->getNameAsCString();
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000727 Setr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000728 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffd40910b2008-12-01 20:33:01 +0000729}
Chris Lattner8a12c272007-10-11 18:38:32 +0000730
Steve Naroffb29b4272008-04-14 22:03:09 +0000731void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000732 // Get the start location and compute the semi location.
733 SourceLocation startLoc = ClassDecl->getLocation();
734 const char *startBuf = SM->getCharacterData(startLoc);
735 const char *semiPtr = strchr(startBuf, ';');
736
737 // Translate to typedef's that forward reference structs with the same name
738 // as the class. As a convenience, we include the original declaration
739 // as a comment.
740 std::string typedefString;
741 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000742 typedefString.append(startBuf, semiPtr-startBuf+1);
743 typedefString += "\n";
Chris Lattner67956052009-02-20 18:04:31 +0000744 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
745 I != E; ++I) {
746 ObjCInterfaceDecl *ForwardDecl = *I;
Steve Naroff32174822007-11-09 12:50:28 +0000747 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000748 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000749 typedefString += "\n";
750 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000751 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000752 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000753 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000754 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000755 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000756 }
757
758 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000759 ReplaceText(startLoc, semiPtr-startBuf+1,
760 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000761}
762
Steve Naroffb29b4272008-04-14 22:03:09 +0000763void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000764 SourceLocation LocStart = Method->getLocStart();
765 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000766
Chris Lattner30fc9332009-02-04 01:06:56 +0000767 if (SM->getInstantiationLineNumber(LocEnd) >
768 SM->getInstantiationLineNumber(LocStart)) {
Steve Naroff94ac21e2008-10-21 13:37:27 +0000769 InsertText(LocStart, "#if 0\n", 6);
770 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000771 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000772 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000773 }
774}
775
Steve Naroff6327e0d2009-01-11 01:06:09 +0000776void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000777{
Steve Naroff6327e0d2009-01-11 01:06:09 +0000778 SourceLocation Loc = prop->getLocation();
779
780 ReplaceText(Loc, 0, "// ", 3);
781
782 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000783}
784
Steve Naroffb29b4272008-04-14 22:03:09 +0000785void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000786 SourceLocation LocStart = CatDecl->getLocStart();
787
788 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000789 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000790
Douglas Gregor6ab35242009-04-09 21:40:53 +0000791 for (ObjCCategoryDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000792 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000793 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000794 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000795 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000796 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000797 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000798 RewriteMethodDeclaration(*I);
799
Steve Naroff423cb562007-10-30 13:30:57 +0000800 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000801 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000802}
803
Steve Naroffb29b4272008-04-14 22:03:09 +0000804void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000805 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000806
Steve Naroff752d6ef2007-10-30 16:42:30 +0000807 SourceLocation LocStart = PDecl->getLocStart();
808
809 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000810 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000811
Douglas Gregor6ab35242009-04-09 21:40:53 +0000812 for (ObjCProtocolDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000813 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000814 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000815 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000816 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000817 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000818 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000819 RewriteMethodDeclaration(*I);
820
Steve Naroff752d6ef2007-10-30 16:42:30 +0000821 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000822 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000823 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000824
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000825 // Must comment out @optional/@required
826 const char *startBuf = SM->getCharacterData(LocStart);
827 const char *endBuf = SM->getCharacterData(LocEnd);
828 for (const char *p = startBuf; p < endBuf; p++) {
829 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
830 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000831 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000832 ReplaceText(OptionalLoc, strlen("@optional"),
833 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000834
835 }
836 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
837 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000838 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000839 ReplaceText(OptionalLoc, strlen("@required"),
840 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000841
842 }
843 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000844}
845
Steve Naroffb29b4272008-04-14 22:03:09 +0000846void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000847 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000848 if (LocStart.isInvalid())
849 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000850 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000851 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000852}
853
Steve Naroffb29b4272008-04-14 22:03:09 +0000854void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000855 std::string &ResultStr) {
Steve Naroffced80a82008-10-30 12:09:33 +0000856 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroff76e429d2008-07-16 14:40:40 +0000857 const FunctionType *FPRetType = 0;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000858 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000859 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000860 ResultStr += "id";
Steve Narofff4312dc2008-12-11 19:29:16 +0000861 else if (OMD->getResultType()->isFunctionPointerType() ||
862 OMD->getResultType()->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +0000863 // needs special handling, since pointer-to-functions have special
864 // syntax (where a decaration models use).
865 QualType retType = OMD->getResultType();
Steve Narofff4312dc2008-12-11 19:29:16 +0000866 QualType PointeeTy;
Ted Kremenek1a1a6e22009-07-16 19:58:26 +0000867 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +0000868 PointeeTy = PT->getPointeeType();
Ted Kremenek1a1a6e22009-07-16 19:58:26 +0000869 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +0000870 PointeeTy = BPT->getPointeeType();
871 if ((FPRetType = PointeeTy->getAsFunctionType())) {
872 ResultStr += FPRetType->getResultType().getAsString();
873 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +0000874 }
875 } else
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000876 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000877 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000878
879 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000880 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000881
Douglas Gregorf8d49f62009-01-09 17:18:27 +0000882 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000883 NameStr += "_I_";
884 else
885 NameStr += "_C_";
886
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000887 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000888 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000889
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000890 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +0000891 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000892 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000893 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000894 }
Steve Naroff563b8282008-04-04 22:23:44 +0000895 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +0000896 {
897 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000898 int len = selString.size();
899 for (int i = 0; i < len; i++)
900 if (selString[i] == ':')
901 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000902 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000903 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000904 // Remember this name for metadata emission
905 MethodInternalNames[OMD] = NameStr;
906 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000907
908 // Rewrite arguments
909 ResultStr += "(";
910
911 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +0000912 if (OMD->isInstanceMethod()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000913 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000914 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000915 if (!LangOpts.Microsoft) {
916 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
917 ResultStr += "struct ";
918 }
919 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000920 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000921 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000922 }
923 else
Steve Naroff621edce2009-04-29 16:37:50 +0000924 ResultStr += Context->getObjCClassType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000925
926 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000927 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000928 ResultStr += " _cmd";
929
930 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +0000931 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
932 E = OMD->param_end(); PI != E; ++PI) {
933 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000934 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +0000935 if (PDecl->getType()->isObjCQualifiedIdType()) {
936 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000937 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +0000938 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000939 std::string Name = PDecl->getNameAsString();
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000940 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroffc8ad87b2008-10-30 14:45:29 +0000941 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Ted Kremenek1a1a6e22009-07-16 19:58:26 +0000942 const BlockPointerType *BPT = PDecl->getType()->getAs<BlockPointerType>();
Douglas Gregord249e1d1f2009-05-29 20:38:28 +0000943 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name,
944 Context->PrintingPolicy);
Steve Naroffc8ad87b2008-10-30 14:45:29 +0000945 } else
Douglas Gregord249e1d1f2009-05-29 20:38:28 +0000946 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroff543409e2008-04-18 21:13:19 +0000947 ResultStr += Name;
948 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000949 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000950 if (OMD->isVariadic())
951 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000952 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000953
Steve Naroff76e429d2008-07-16 14:40:40 +0000954 if (FPRetType) {
955 ResultStr += ")"; // close the precedence "scope" for "*".
956
957 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +0000958 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +0000959 ResultStr += "(";
960 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
961 if (i) ResultStr += ", ";
962 std::string ParamStr = FT->getArgType(i).getAsString();
963 ResultStr += ParamStr;
964 }
965 if (FT->isVariadic()) {
966 if (FT->getNumArgs()) ResultStr += ", ";
967 ResultStr += "...";
968 }
969 ResultStr += ")";
970 } else {
971 ResultStr += "()";
972 }
973 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000974}
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000975void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000976 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
977 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000978
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000979 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000980 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000981 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000982 InsertText(CID->getLocStart(), "// ", 3);
Steve Narofface66252008-11-13 20:07:04 +0000983
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000984 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000985 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
986 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +0000987 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000988 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000989 ObjCMethodDecl *OMD = *I;
990 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000991 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000992 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +0000993
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000994 const char *startBuf = SM->getCharacterData(LocStart);
995 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000996 ReplaceText(LocStart, endBuf-startBuf,
997 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000998 }
999
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001000 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001001 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1002 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001003 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001004 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001005 ObjCMethodDecl *OMD = *I;
1006 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001007 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001008 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001009
1010 const char *startBuf = SM->getCharacterData(LocStart);
1011 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +00001012 ReplaceText(LocStart, endBuf-startBuf,
1013 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001014 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001015 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001016 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1017 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001018 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001019 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001020 }
1021
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001022 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001023 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001024 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001025 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001026}
1027
Steve Naroffb29b4272008-04-14 22:03:09 +00001028void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001029 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001030 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001031 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001032 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001033 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001034 ResultStr += "\n";
1035 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001036 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001037 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001038 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001039 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001040 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001041 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001042 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001043 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001044 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +00001045
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001046 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
1047 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001048 RewriteProperty(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001049 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001050 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001051 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001052 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001053 for (ObjCInterfaceDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001054 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001055 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001056 RewriteMethodDeclaration(*I);
1057
Steve Naroff2feac5e2007-10-30 03:43:13 +00001058 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +00001059 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +00001060}
1061
Steve Naroffb619d952008-12-09 12:56:34 +00001062Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1063 SourceRange SrcRange) {
Steve Naroffc77a6362008-12-04 16:24:46 +00001064 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1065 // This allows us to reuse all the fun and games in SynthMessageExpr().
1066 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1067 ObjCMessageExpr *MsgExpr;
1068 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1069 llvm::SmallVector<Expr *, 1> ExprVec;
1070 ExprVec.push_back(newStmt);
1071
Steve Naroff8599e7a2008-12-08 16:43:47 +00001072 Stmt *Receiver = PropRefExpr->getBase();
1073 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1074 if (PRE && PropGetters[PRE]) {
1075 // This allows us to handle chain/nested property getters.
1076 Receiver = PropGetters[PRE];
1077 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00001078 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
Steve Naroffc77a6362008-12-04 16:24:46 +00001079 PDecl->getSetterName(), PDecl->getType(),
1080 PDecl->getSetterMethodDecl(),
1081 SourceLocation(), SourceLocation(),
1082 &ExprVec[0], 1);
1083 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
1084
1085 // Now do the actual rewrite.
Steve Naroffb619d952008-12-09 12:56:34 +00001086 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffe58ee0c2008-12-10 14:53:27 +00001087 //delete BinOp;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001088 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1089 // to things that stay around.
1090 Context->Deallocate(MsgExpr);
Steve Naroffc77a6362008-12-04 16:24:46 +00001091 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001092}
1093
Steve Naroffc77a6362008-12-04 16:24:46 +00001094Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Naroff15f081d2008-12-03 00:56:33 +00001095 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1096 // This allows us to reuse all the fun and games in SynthMessageExpr().
1097 ObjCMessageExpr *MsgExpr;
1098 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1099
Steve Naroff8599e7a2008-12-08 16:43:47 +00001100 Stmt *Receiver = PropRefExpr->getBase();
1101
1102 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1103 if (PRE && PropGetters[PRE]) {
1104 // This allows us to handle chain/nested property getters.
1105 Receiver = PropGetters[PRE];
1106 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00001107 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
Steve Naroff15f081d2008-12-03 00:56:33 +00001108 PDecl->getGetterName(), PDecl->getType(),
1109 PDecl->getGetterMethodDecl(),
1110 SourceLocation(), SourceLocation(),
1111 0, 0);
1112
Steve Naroff4c3580e2008-12-04 23:50:32 +00001113 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001114
1115 if (!PropParentMap)
1116 PropParentMap = new ParentMap(CurrentBody);
1117
1118 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1119 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1120 // We stash away the ReplacingStmt since actually doing the
1121 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1122 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001123 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1124 // to things that stay around.
1125 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001126 return PropRefExpr; // return the original...
1127 } else {
1128 ReplaceStmt(PropRefExpr, ReplacingStmt);
Ted Kremenek8189cde2009-02-07 01:47:29 +00001129 // delete PropRefExpr; elsewhere...
1130 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1131 // to things that stay around.
1132 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001133 return ReplacingStmt;
1134 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001135}
1136
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001137Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
1138 SourceLocation OrigStart) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001139 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff54055232008-10-27 17:20:55 +00001140 if (CurMethodDef) {
Ted Kremenek1a1a6e22009-07-16 19:58:26 +00001141 if (const PointerType *pType = IV->getBase()->getType()->getAs<PointerType>()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001142 ObjCInterfaceType *iFaceDecl =
1143 dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Narofff0757612008-05-08 17:52:16 +00001144 // lookup which class implements the instance variable.
1145 ObjCInterfaceDecl *clsDeclared = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001146 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001147 clsDeclared);
Steve Narofff0757612008-05-08 17:52:16 +00001148 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1149
1150 // Synthesize an explicit cast to gain access to the ivar.
1151 std::string RecName = clsDeclared->getIdentifier()->getName();
1152 RecName += "_IMPL";
1153 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001154 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001155 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001156 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1157 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Ted Kremenek8189cde2009-02-07 01:47:29 +00001158 CastExpr *castExpr = new (Context) CStyleCastExpr(castT, IV->getBase(),
1159 castT,SourceLocation(),
1160 SourceLocation());
Steve Narofff0757612008-05-08 17:52:16 +00001161 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001162 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1163 IV->getBase()->getLocEnd(),
1164 castExpr);
Steve Narofff0757612008-05-08 17:52:16 +00001165 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001166 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001167 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1168 IV->getLocation(),
1169 D->getType());
Steve Narofff0757612008-05-08 17:52:16 +00001170 ReplaceStmt(IV, ME);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001171 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001172 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001173 }
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001174
1175 ReplaceStmt(IV->getBase(), PE);
1176 // Cannot delete IV->getBase(), since PE points to it.
1177 // Replace the old base with the cast. This is important when doing
1178 // embedded rewrites. For example, [newInv->_container addObject:0].
1179 IV->setBase(PE);
1180 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001181 }
Steve Naroff84472a82008-04-18 21:55:08 +00001182 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001183 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
1184
1185 // Explicit ivar refs need to have a cast inserted.
1186 // FIXME: consider sharing some of this code with the code above.
Ted Kremenek1a1a6e22009-07-16 19:58:26 +00001187 if (const PointerType *pType = IV->getBase()->getType()->getAs<PointerType>()) {
Steve Narofff0757612008-05-08 17:52:16 +00001188 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001189 // lookup which class implements the instance variable.
1190 ObjCInterfaceDecl *clsDeclared = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001191 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001192 clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001193 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1194
1195 // Synthesize an explicit cast to gain access to the ivar.
1196 std::string RecName = clsDeclared->getIdentifier()->getName();
1197 RecName += "_IMPL";
1198 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001199 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001200 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001201 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1202 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Ted Kremenek8189cde2009-02-07 01:47:29 +00001203 CastExpr *castExpr = new (Context) CStyleCastExpr(castT, IV->getBase(),
1204 castT, SourceLocation(),
1205 SourceLocation());
Steve Naroff9f525972008-05-06 23:20:07 +00001206 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001207 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner8d366162008-05-28 16:38:23 +00001208 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +00001209 ReplaceStmt(IV->getBase(), PE);
1210 // Cannot delete IV->getBase(), since PE points to it.
1211 // Replace the old base with the cast. This is important when doing
1212 // embedded rewrites. For example, [newInv->_container addObject:0].
1213 IV->setBase(PE);
1214 return IV;
1215 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001216 }
Steve Naroff84472a82008-04-18 21:55:08 +00001217 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001218}
1219
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001220/// SynthCountByEnumWithState - To print:
1221/// ((unsigned int (*)
1222/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1223/// (void *)objc_msgSend)((id)l_collection,
1224/// sel_registerName(
1225/// "countByEnumeratingWithState:objects:count:"),
1226/// &enumState,
1227/// (id *)items, (unsigned int)16)
1228///
Steve Naroffb29b4272008-04-14 22:03:09 +00001229void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001230 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1231 "id *, unsigned int))(void *)objc_msgSend)";
1232 buf += "\n\t\t";
1233 buf += "((id)l_collection,\n\t\t";
1234 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1235 buf += "\n\t\t";
1236 buf += "&enumState, "
1237 "(id *)items, (unsigned int)16)";
1238}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001239
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001240/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1241/// statement to exit to its outer synthesized loop.
1242///
Steve Naroffb29b4272008-04-14 22:03:09 +00001243Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001244 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1245 return S;
1246 // replace break with goto __break_label
1247 std::string buf;
1248
1249 SourceLocation startLoc = S->getLocStart();
1250 buf = "goto __break_label_";
1251 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001252 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001253
1254 return 0;
1255}
1256
1257/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1258/// statement to continue with its inner synthesized loop.
1259///
Steve Naroffb29b4272008-04-14 22:03:09 +00001260Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001261 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1262 return S;
1263 // replace continue with goto __continue_label
1264 std::string buf;
1265
1266 SourceLocation startLoc = S->getLocStart();
1267 buf = "goto __continue_label_";
1268 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001269 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001270
1271 return 0;
1272}
1273
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001274/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001275/// It rewrites:
1276/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001277
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001278/// Into:
1279/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001280/// type elem;
1281/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001282/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001283/// id l_collection = (id)collection;
1284/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1285/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001286/// if (limit) {
1287/// unsigned long startMutations = *enumState.mutationsPtr;
1288/// do {
1289/// unsigned long counter = 0;
1290/// do {
1291/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001292/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001293/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001294/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001295/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001296/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001297/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1298/// objects:items count:16]);
1299/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001300/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001301/// }
1302/// else
1303/// elem = nil;
1304/// }
1305///
Steve Naroffb29b4272008-04-14 22:03:09 +00001306Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001307 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001308 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1309 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1310 "ObjCForCollectionStmt Statement stack mismatch");
1311 assert(!ObjCBcLabelNo.empty() &&
1312 "ObjCForCollectionStmt - Label No stack empty");
1313
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001314 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001315 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001316 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001317 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001318 std::string buf;
1319 buf = "\n{\n\t";
1320 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1321 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001322 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001323 QualType ElementType = cast<ValueDecl>(D)->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001324 elementTypeAsString = ElementType.getAsString();
1325 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001326 buf += " ";
Chris Lattner8ec03f52008-11-24 03:54:41 +00001327 elementName = D->getNameAsCString();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001328 buf += elementName;
1329 buf += ";\n\t";
1330 }
Chris Lattner06767512008-04-08 05:52:18 +00001331 else {
1332 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001333 elementName = DR->getDecl()->getNameAsCString();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001334 elementTypeAsString
1335 = cast<ValueDecl>(DR->getDecl())->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001336 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001337
1338 // struct __objcFastEnumerationState enumState = { 0 };
1339 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1340 // id items[16];
1341 buf += "id items[16];\n\t";
1342 // id l_collection = (id)
1343 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001344 // Find start location of 'collection' the hard way!
1345 const char *startCollectionBuf = startBuf;
1346 startCollectionBuf += 3; // skip 'for'
1347 startCollectionBuf = strchr(startCollectionBuf, '(');
1348 startCollectionBuf++; // skip '('
1349 // find 'in' and skip it.
1350 while (*startCollectionBuf != ' ' ||
1351 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1352 (*(startCollectionBuf+3) != ' ' &&
1353 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1354 startCollectionBuf++;
1355 startCollectionBuf += 3;
1356
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001357 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001358 ReplaceText(startLoc, startCollectionBuf - startBuf,
1359 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001360 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001361 SourceLocation rightParenLoc = S->getRParenLoc();
1362 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1363 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001364 buf = ";\n\t";
1365
1366 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1367 // objects:items count:16];
1368 // which is synthesized into:
1369 // unsigned int limit =
1370 // ((unsigned int (*)
1371 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1372 // (void *)objc_msgSend)((id)l_collection,
1373 // sel_registerName(
1374 // "countByEnumeratingWithState:objects:count:"),
1375 // (struct __objcFastEnumerationState *)&state,
1376 // (id *)items, (unsigned int)16);
1377 buf += "unsigned long limit =\n\t\t";
1378 SynthCountByEnumWithState(buf);
1379 buf += ";\n\t";
1380 /// if (limit) {
1381 /// unsigned long startMutations = *enumState.mutationsPtr;
1382 /// do {
1383 /// unsigned long counter = 0;
1384 /// do {
1385 /// if (startMutations != *enumState.mutationsPtr)
1386 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001387 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001388 buf += "if (limit) {\n\t";
1389 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1390 buf += "do {\n\t\t";
1391 buf += "unsigned long counter = 0;\n\t\t";
1392 buf += "do {\n\t\t\t";
1393 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1394 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1395 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001396 buf += " = (";
1397 buf += elementTypeAsString;
1398 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001399 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001400 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001401
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001402 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001403 /// } while (counter < limit);
1404 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1405 /// objects:items count:16]);
1406 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001407 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001408 /// }
1409 /// else
1410 /// elem = nil;
1411 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001412 ///
1413 buf = ";\n\t";
1414 buf += "__continue_label_";
1415 buf += utostr(ObjCBcLabelNo.back());
1416 buf += ": ;";
1417 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001418 buf += "} while (counter < limit);\n\t";
1419 buf += "} while (limit = ";
1420 SynthCountByEnumWithState(buf);
1421 buf += ");\n\t";
1422 buf += elementName;
Steve Naroff5605fdf2008-12-17 14:24:39 +00001423 buf += " = ((id)0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001424 buf += "__break_label_";
1425 buf += utostr(ObjCBcLabelNo.back());
1426 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001427 buf += "}\n\t";
1428 buf += "else\n\t\t";
1429 buf += elementName;
Steve Naroff5605fdf2008-12-17 14:24:39 +00001430 buf += " = ((id)0);\n";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001431 buf += "}\n";
Steve Naroff600e4e82008-07-21 18:26:02 +00001432
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001433 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001434 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001435 if (isa<CompoundStmt>(S->getBody())) {
1436 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1437 InsertText(endBodyLoc, buf.c_str(), buf.size());
1438 } else {
1439 /* Need to treat single statements specially. For example:
1440 *
1441 * for (A *a in b) if (stuff()) break;
1442 * for (A *a in b) xxxyy;
1443 *
1444 * The following code simply scans ahead to the semi to find the actual end.
1445 */
1446 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1447 const char *semiBuf = strchr(stmtBuf, ';');
1448 assert(semiBuf && "Can't find ';'");
1449 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1450 InsertText(endBodyLoc, buf.c_str(), buf.size());
1451 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001452 Stmts.pop_back();
1453 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001454 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001455}
1456
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001457/// RewriteObjCSynchronizedStmt -
1458/// This routine rewrites @synchronized(expr) stmt;
1459/// into:
1460/// objc_sync_enter(expr);
1461/// @try stmt @finally { objc_sync_exit(expr); }
1462///
Steve Naroffb29b4272008-04-14 22:03:09 +00001463Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001464 // Get the start location and compute the semi location.
1465 SourceLocation startLoc = S->getLocStart();
1466 const char *startBuf = SM->getCharacterData(startLoc);
1467
1468 assert((*startBuf == '@') && "bogus @synchronized location");
1469
1470 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001471 buf = "objc_sync_enter((id)";
1472 const char *lparenBuf = startBuf;
1473 while (*lparenBuf != '(') lparenBuf++;
1474 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Steve Naroffc7089f12008-08-19 13:04:19 +00001475 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1476 // the sync expression is typically a message expression that's already
1477 // been rewritten! (which implies the SourceLocation's are invalid).
1478 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001479 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001480 while (*endBuf != ')') endBuf--;
1481 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001482 buf = ");\n";
1483 // declare a new scope with two variables, _stack and _rethrow.
1484 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1485 buf += "int buf[18/*32-bit i386*/];\n";
1486 buf += "char *pointers[4];} _stack;\n";
1487 buf += "id volatile _rethrow = 0;\n";
1488 buf += "objc_exception_try_enter(&_stack);\n";
1489 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001490 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001491 startLoc = S->getSynchBody()->getLocEnd();
1492 startBuf = SM->getCharacterData(startLoc);
1493
Steve Naroffc7089f12008-08-19 13:04:19 +00001494 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001495 SourceLocation lastCurlyLoc = startLoc;
1496 buf = "}\nelse {\n";
1497 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001498 buf += "}\n";
1499 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001500 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb2a39452008-07-16 19:47:39 +00001501 buf += " objc_sync_exit(";
Ted Kremenek8189cde2009-02-07 01:47:29 +00001502 Expr *syncExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
1503 S->getSynchExpr(),
1504 Context->getObjCIdType(),
1505 SourceLocation(),
1506 SourceLocation());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001507 std::string syncExprBufS;
1508 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001509 syncExpr->printPretty(syncExprBuf, *Context, 0,
1510 PrintingPolicy(LangOpts));
Steve Naroffb2a39452008-07-16 19:47:39 +00001511 buf += syncExprBuf.str();
1512 buf += ");\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001513 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1514 buf += "}\n";
1515 buf += "}";
1516
Chris Lattneraadaf782008-01-31 19:51:04 +00001517 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001518 return 0;
1519}
1520
Steve Naroff8c565152008-12-05 17:03:39 +00001521void RewriteObjC::WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S) {
1522 // Perform a bottom up traversal of all children.
1523 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1524 CI != E; ++CI)
1525 if (*CI)
1526 WarnAboutReturnGotoContinueOrBreakStmts(*CI);
1527
1528 if (isa<ReturnStmt>(S) || isa<ContinueStmt>(S) ||
1529 isa<BreakStmt>(S) || isa<GotoStmt>(S)) {
1530 Diags.Report(Context->getFullLoc(S->getLocStart()),
1531 TryFinallyContainsReturnDiag);
1532 }
1533 return;
1534}
1535
Steve Naroffb29b4272008-04-14 22:03:09 +00001536Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001537 // Get the start location and compute the semi location.
1538 SourceLocation startLoc = S->getLocStart();
1539 const char *startBuf = SM->getCharacterData(startLoc);
1540
1541 assert((*startBuf == '@') && "bogus @try location");
1542
1543 std::string buf;
1544 // declare a new scope with two variables, _stack and _rethrow.
1545 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1546 buf += "int buf[18/*32-bit i386*/];\n";
1547 buf += "char *pointers[4];} _stack;\n";
1548 buf += "id volatile _rethrow = 0;\n";
1549 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001550 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001551
Chris Lattneraadaf782008-01-31 19:51:04 +00001552 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001553
1554 startLoc = S->getTryBody()->getLocEnd();
1555 startBuf = SM->getCharacterData(startLoc);
1556
1557 assert((*startBuf == '}') && "bogus @try block");
Steve Naroffc9ba1722008-07-16 15:31:30 +00001558
Steve Naroff75730982007-11-07 04:08:17 +00001559 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001560 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1561 if (catchList) {
1562 startLoc = startLoc.getFileLocWithOffset(1);
1563 buf = " /* @catch begin */ else {\n";
1564 buf += " id _caught = objc_exception_extract(&_stack);\n";
1565 buf += " objc_exception_try_enter (&_stack);\n";
1566 buf += " if (_setjmp(_stack.buf))\n";
1567 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1568 buf += " else { /* @catch continue */";
1569
1570 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001571 } else { /* no catch list */
1572 buf = "}\nelse {\n";
1573 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1574 buf += "}";
1575 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffc9ba1722008-07-16 15:31:30 +00001576 }
Steve Naroff75730982007-11-07 04:08:17 +00001577 bool sawIdTypedCatch = false;
1578 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001579 while (catchList) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00001580 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001581
1582 if (catchList == S->getCatchStmts())
1583 buf = "if ("; // we are generating code for the first catch clause
1584 else
1585 buf = "else if (";
1586 startLoc = catchList->getLocStart();
1587 startBuf = SM->getCharacterData(startLoc);
1588
1589 assert((*startBuf == '@') && "bogus @catch location");
1590
1591 const char *lParenLoc = strchr(startBuf, '(');
1592
Steve Naroffbe4b3332008-02-01 22:08:12 +00001593 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001594 // Now rewrite the body...
1595 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001596 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1597 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001598 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1599 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001600 assert((*bodyBuf == '{') && "bogus @catch body location");
1601
1602 buf += "1) { id _tmp = _caught;";
1603 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1604 buf.c_str(), buf.size());
Steve Naroff7ba138a2009-03-03 19:52:17 +00001605 } else if (catchDecl) {
1606 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001607 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001608 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001609 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001610 sawIdTypedCatch = true;
Ted Kremenek1a1a6e22009-07-16 19:58:26 +00001611 } else if (const PointerType *pType = t->getAs<PointerType>()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001612 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001613
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001614 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001615 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001616 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001617 buf += cls->getDecl()->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001618 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001619 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001620 }
1621 }
1622 // Now rewrite the body...
1623 lastCatchBody = catchList->getCatchBody();
1624 SourceLocation rParenLoc = catchList->getRParenLoc();
1625 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1626 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1627 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1628 assert((*rParenBuf == ')') && "bogus @catch paren location");
1629 assert((*bodyBuf == '{') && "bogus @catch body location");
1630
1631 buf = " = _caught;";
1632 // Here we replace ") {" with "= _caught;" (which initializes and
1633 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001634 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff7ba138a2009-03-03 19:52:17 +00001635 } else {
Steve Naroff75730982007-11-07 04:08:17 +00001636 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001637 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001638 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001639 catchList = catchList->getNextCatchStmt();
1640 }
1641 // Complete the catch list...
1642 if (lastCatchBody) {
1643 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001644 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1645 "bogus @catch body location");
Steve Naroff75730982007-11-07 04:08:17 +00001646
Steve Naroff378f47a2008-09-11 15:29:03 +00001647 // Insert the last (implicit) else clause *before* the right curly brace.
1648 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1649 buf = "} /* last catch end */\n";
1650 buf += "else {\n";
1651 buf += " _rethrow = _caught;\n";
1652 buf += " objc_exception_try_exit(&_stack);\n";
1653 buf += "} } /* @catch end */\n";
1654 if (!S->getFinallyStmt())
1655 buf += "}\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001656 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001657
1658 // Set lastCurlyLoc
1659 lastCurlyLoc = lastCatchBody->getLocEnd();
1660 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001661 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001662 startLoc = finalStmt->getLocStart();
1663 startBuf = SM->getCharacterData(startLoc);
1664 assert((*startBuf == '@') && "bogus @finally start");
1665
1666 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001667 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001668
1669 Stmt *body = finalStmt->getFinallyBody();
1670 SourceLocation startLoc = body->getLocStart();
1671 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001672 assert(*SM->getCharacterData(startLoc) == '{' &&
1673 "bogus @finally body location");
1674 assert(*SM->getCharacterData(endLoc) == '}' &&
1675 "bogus @finally body location");
Steve Naroff75730982007-11-07 04:08:17 +00001676
1677 startLoc = startLoc.getFileLocWithOffset(1);
1678 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001679 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001680 endLoc = endLoc.getFileLocWithOffset(-1);
1681 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001682 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001683
1684 // Set lastCurlyLoc
1685 lastCurlyLoc = body->getLocEnd();
Steve Naroff8c565152008-12-05 17:03:39 +00001686
1687 // Now check for any return/continue/go statements within the @try.
1688 WarnAboutReturnGotoContinueOrBreakStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00001689 } else { /* no finally clause - make sure we synthesize an implicit one */
1690 buf = "{ /* implicit finally clause */\n";
1691 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1692 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1693 buf += "}";
1694 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001695 }
1696 // Now emit the final closing curly brace...
1697 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1698 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001699 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001700 return 0;
1701}
1702
Steve Naroffb29b4272008-04-14 22:03:09 +00001703Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001704 return 0;
1705}
1706
Steve Naroffb29b4272008-04-14 22:03:09 +00001707Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001708 return 0;
1709}
1710
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001711// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001712// the throw expression is typically a message expression that's already
1713// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001714Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001715 // Get the start location and compute the semi location.
1716 SourceLocation startLoc = S->getLocStart();
1717 const char *startBuf = SM->getCharacterData(startLoc);
1718
1719 assert((*startBuf == '@') && "bogus @throw location");
1720
1721 std::string buf;
1722 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001723 if (S->getThrowExpr())
1724 buf = "objc_exception_throw(";
1725 else // add an implicit argument
1726 buf = "objc_exception_throw(_caught";
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001727
1728 // handle "@ throw" correctly.
1729 const char *wBuf = strchr(startBuf, 'w');
1730 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1731 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1732
Steve Naroff2bd03922007-11-07 15:32:26 +00001733 const char *semiBuf = strchr(startBuf, ';');
1734 assert((*semiBuf == ';') && "@throw: can't find ';'");
1735 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1736 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001737 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001738 return 0;
1739}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001740
Steve Naroffb29b4272008-04-14 22:03:09 +00001741Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001742 // Create a new string expression.
1743 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001744 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001745 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattner2085fd62009-02-18 06:40:38 +00001746 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
1747 StrEncoding.length(), false,StrType,
1748 SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001749 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001750
Chris Lattner07506182007-11-30 22:53:43 +00001751 // Replace this subexpr in the parent.
Steve Naroff4c3580e2008-12-04 23:50:32 +00001752 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00001753 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001754}
1755
Steve Naroffb29b4272008-04-14 22:03:09 +00001756Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00001757 if (!SelGetUidFunctionDecl)
1758 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00001759 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1760 // Create a call to sel_registerName("selName").
1761 llvm::SmallVector<Expr*, 8> SelExprs;
1762 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00001763 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00001764 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00001765 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00001766 false, argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00001767 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1768 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001769 ReplaceStmt(Exp, SelExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001770 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00001771 return SelExp;
1772}
1773
Steve Naroffb29b4272008-04-14 22:03:09 +00001774CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001775 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001776 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001777 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001778
1779 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001780 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001781
1782 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001783 QualType pToFunc = Context->getPointerType(msgSendType);
Ted Kremenek8189cde2009-02-07 01:47:29 +00001784 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc, DRE,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001785 /*isLvalue=*/false);
Steve Naroffebf2b562007-10-23 23:50:29 +00001786
1787 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001788
Ted Kremenek668bf912009-02-09 20:51:47 +00001789 return new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
1790 SourceLocation());
Steve Naroff934f2762007-10-24 22:48:43 +00001791}
1792
Steve Naroffd5255f52007-11-01 13:24:47 +00001793static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1794 const char *&startRef, const char *&endRef) {
1795 while (startBuf < endBuf) {
1796 if (*startBuf == '<')
1797 startRef = startBuf; // mark the start.
1798 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001799 if (startRef && *startRef == '<') {
1800 endRef = startBuf; // mark the end.
1801 return true;
1802 }
1803 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001804 }
1805 startBuf++;
1806 }
1807 return false;
1808}
1809
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001810static void scanToNextArgument(const char *&argRef) {
1811 int angle = 0;
1812 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1813 if (*argRef == '<')
1814 angle++;
1815 else if (*argRef == '>')
1816 angle--;
1817 argRef++;
1818 }
1819 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1820}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001821
Steve Naroffb29b4272008-04-14 22:03:09 +00001822bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001823
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001824 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001825 return true;
1826
Ted Kremenek1a1a6e22009-07-16 19:58:26 +00001827 if (const PointerType *pType = T->getAs<PointerType>()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001828 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001829 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001830 return true; // we have "Class <Protocol> *".
1831 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001832 return false;
1833}
1834
Steve Naroff4f95b752008-07-29 18:15:38 +00001835void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1836 QualType Type = E->getType();
1837 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00001838 SourceLocation Loc, EndLoc;
1839
1840 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1841 Loc = ECE->getLParenLoc();
1842 EndLoc = ECE->getRParenLoc();
1843 } else {
1844 Loc = E->getLocStart();
1845 EndLoc = E->getLocEnd();
1846 }
1847 // This will defend against trying to rewrite synthesized expressions.
1848 if (Loc.isInvalid() || EndLoc.isInvalid())
1849 return;
1850
Steve Naroff4f95b752008-07-29 18:15:38 +00001851 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00001852 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00001853 const char *startRef = 0, *endRef = 0;
1854 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1855 // Get the locations of the startRef, endRef.
1856 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1857 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1858 // Comment out the protocol references.
1859 InsertText(LessLoc, "/*", 2);
1860 InsertText(GreaterLoc, "*/", 2);
1861 }
1862 }
1863}
1864
Steve Naroffb29b4272008-04-14 22:03:09 +00001865void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001866 SourceLocation Loc;
1867 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00001868 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001869 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1870 Loc = VD->getLocation();
1871 Type = VD->getType();
1872 }
1873 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1874 Loc = FD->getLocation();
1875 // Check for ObjC 'id' and class types that have been adorned with protocol
1876 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1877 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1878 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00001879 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001880 if (!proto)
1881 return;
1882 Type = proto->getResultType();
1883 }
1884 else
1885 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001886
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001887 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001888 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001889
1890 const char *endBuf = SM->getCharacterData(Loc);
1891 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00001892 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001893 startBuf--; // scan backward (from the decl location) for return type.
1894 const char *startRef = 0, *endRef = 0;
1895 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1896 // Get the locations of the startRef, endRef.
1897 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1898 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1899 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001900 InsertText(LessLoc, "/*", 2);
1901 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001902 }
1903 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001904 if (!proto)
1905 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001906 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001907 const char *startBuf = SM->getCharacterData(Loc);
1908 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001909 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1910 if (needToScanForQualifiers(proto->getArgType(i))) {
1911 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001912
Steve Naroffd5255f52007-11-01 13:24:47 +00001913 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001914 // scan forward (from the decl location) for argument types.
1915 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001916 const char *startRef = 0, *endRef = 0;
1917 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1918 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001919 SourceLocation LessLoc =
1920 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1921 SourceLocation GreaterLoc =
1922 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001923 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001924 InsertText(LessLoc, "/*", 2);
1925 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001926 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001927 startBuf = ++endBuf;
1928 }
1929 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00001930 // If the function name is derived from a macro expansion, then the
1931 // argument buffer will not follow the name. Need to speak with Chris.
1932 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001933 startBuf++; // scan forward (from the decl location) for argument types.
1934 startBuf++;
1935 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001936 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001937}
1938
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001939// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00001940void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001941 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1942 llvm::SmallVector<QualType, 16> ArgTys;
1943 ArgTys.push_back(Context->getPointerType(
1944 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001945 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001946 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001947 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001948 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001949 SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001950 SelGetUidIdent, getFuncType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001951 FunctionDecl::Extern, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001952}
1953
Steve Naroffb29b4272008-04-14 22:03:09 +00001954void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001955 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00001956 if (FD->getIdentifier() &&
1957 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001958 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001959 return;
1960 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001961 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001962}
1963
Steve Naroffc0a123c2008-03-11 17:37:02 +00001964// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00001965void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00001966 if (SuperContructorFunctionDecl)
1967 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00001968 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroffc0a123c2008-03-11 17:37:02 +00001969 llvm::SmallVector<QualType, 16> ArgTys;
1970 QualType argT = Context->getObjCIdType();
1971 assert(!argT.isNull() && "Can't find 'id' type");
1972 ArgTys.push_back(argT);
1973 ArgTys.push_back(argT);
1974 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1975 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001976 false, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001977 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001978 SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00001979 msgSendIdent, msgSendType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001980 FunctionDecl::Extern, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00001981}
1982
Steve Naroff09b266e2007-10-30 23:14:51 +00001983// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001984void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001985 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1986 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001987 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001988 assert(!argT.isNull() && "Can't find 'id' type");
1989 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001990 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001991 assert(!argT.isNull() && "Can't find 'SEL' type");
1992 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001993 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001994 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001995 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001996 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001997 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001998 msgSendIdent, msgSendType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001999 FunctionDecl::Extern, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002000}
2001
Steve Naroff874e2322007-11-15 10:28:18 +00002002// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002003void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002004 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2005 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002006 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002007 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002008 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002009 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2010 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2011 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002012 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002013 assert(!argT.isNull() && "Can't find 'SEL' type");
2014 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002015 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00002016 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002017 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002018 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002019 SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00002020 msgSendIdent, msgSendType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002021 FunctionDecl::Extern, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002022}
2023
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002024// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002025void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002026 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2027 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002028 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002029 assert(!argT.isNull() && "Can't find 'id' type");
2030 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002031 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002032 assert(!argT.isNull() && "Can't find 'SEL' type");
2033 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002034 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002035 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002036 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002037 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002038 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002039 msgSendIdent, msgSendType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002040 FunctionDecl::Extern, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002041}
2042
2043// SynthMsgSendSuperStretFunctionDecl -
2044// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002045void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002046 IdentifierInfo *msgSendIdent =
2047 &Context->Idents.get("objc_msgSendSuper_stret");
2048 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002049 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002050 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002051 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002052 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2053 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2054 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002055 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002056 assert(!argT.isNull() && "Can't find 'SEL' type");
2057 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002058 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002059 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002060 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002061 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnera98e58d2008-03-15 21:24:04 +00002062 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002063 msgSendIdent, msgSendType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002064 FunctionDecl::Extern, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002065}
2066
Steve Naroff1284db82008-05-08 22:02:18 +00002067// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002068void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002069 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2070 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002071 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002072 assert(!argT.isNull() && "Can't find 'id' type");
2073 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002074 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002075 assert(!argT.isNull() && "Can't find 'SEL' type");
2076 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00002077 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002078 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002079 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002080 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002081 SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002082 msgSendIdent, msgSendType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002083 FunctionDecl::Extern, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002084}
2085
Steve Naroff09b266e2007-10-30 23:14:51 +00002086// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002087void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002088 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2089 llvm::SmallVector<QualType, 16> ArgTys;
2090 ArgTys.push_back(Context->getPointerType(
2091 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002092 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002093 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002094 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002095 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002096 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002097 getClassIdent, getClassType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002098 FunctionDecl::Extern, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002099}
2100
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002101// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002102void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002103 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2104 llvm::SmallVector<QualType, 16> ArgTys;
2105 ArgTys.push_back(Context->getPointerType(
2106 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002107 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002108 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002109 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002110 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002111 SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002112 getClassIdent, getClassType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002113 FunctionDecl::Extern, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002114}
2115
Steve Naroffb29b4272008-04-14 22:03:09 +00002116Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002117 QualType strType = getConstantStringStructType();
2118
2119 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002120
2121 std::string tmpName = InFileName;
2122 unsigned i;
2123 for (i=0; i < tmpName.length(); i++) {
2124 char c = tmpName.at(i);
2125 // replace any non alphanumeric characters with '_'.
2126 if (!isalpha(c) && (c < '0' || c > '9'))
2127 tmpName[i] = '_';
2128 }
2129 S += tmpName;
2130 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002131 S += utostr(NumObjCStringLiterals++);
2132
Steve Naroffba92b2e2008-03-27 22:29:16 +00002133 Preamble += "static __NSConstantStringImpl " + S;
2134 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2135 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002136 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002137 std::string prettyBufS;
2138 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002139 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2140 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002141 Preamble += prettyBuf.str();
2142 Preamble += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00002143 // The minus 2 removes the begin/end double quotes.
Steve Naroffba92b2e2008-03-27 22:29:16 +00002144 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002145
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002146 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff248a7532008-04-15 22:42:06 +00002147 &Context->Idents.get(S.c_str()), strType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002148 VarDecl::Static);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002149 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2150 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002151 Context->getPointerType(DRE->getType()),
2152 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002153 // cast to NSConstantString *
Ted Kremenek8189cde2009-02-07 01:47:29 +00002154 CastExpr *cast = new (Context) CStyleCastExpr(Exp->getType(), Unop,
Steve Naroffb2f9e512008-11-03 23:29:32 +00002155 Exp->getType(), SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002156 ReplaceStmt(Exp, cast);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002157 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002158 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002159}
2160
Steve Naroffb29b4272008-04-14 22:03:09 +00002161ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002162 // check if we are sending a message to 'super'
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002163 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002164
Douglas Gregorcd9b46e2008-11-04 14:56:14 +00002165 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
Steve Naroff14108da2009-07-10 23:34:53 +00002166 const ObjCObjectPointerType *OPT =
2167 Super->getType()->getAsObjCObjectPointerType();
2168 assert(OPT);
2169 const ObjCInterfaceType *IT = OPT->getInterfaceType();
Chris Lattner0d17f6f2008-06-21 18:04:54 +00002170 return IT->getDecl();
2171 }
2172 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00002173}
2174
2175// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002176QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002177 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002178 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002179 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002180 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002181 QualType FieldTypes[2];
2182
2183 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002184 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002185 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002186 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002187
Steve Naroff874e2322007-11-15 10:28:18 +00002188 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002189 for (unsigned i = 0; i < 2; ++i) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002190 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002191 SourceLocation(), 0,
2192 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002193 /*Mutable=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002194 }
Steve Naroff874e2322007-11-15 10:28:18 +00002195
Douglas Gregor44b43212008-12-11 16:49:14 +00002196 SuperStructDecl->completeDefinition(*Context);
Steve Naroff874e2322007-11-15 10:28:18 +00002197 }
2198 return Context->getTagDeclType(SuperStructDecl);
2199}
2200
Steve Naroffb29b4272008-04-14 22:03:09 +00002201QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002202 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002203 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002204 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002205 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002206 QualType FieldTypes[4];
2207
2208 // struct objc_object *receiver;
2209 FieldTypes[0] = Context->getObjCIdType();
2210 // int flags;
2211 FieldTypes[1] = Context->IntTy;
2212 // char *str;
2213 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2214 // long length;
2215 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002216
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002217 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002218 for (unsigned i = 0; i < 4; ++i) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002219 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
Douglas Gregor44b43212008-12-11 16:49:14 +00002220 ConstantStringDecl,
2221 SourceLocation(), 0,
2222 FieldTypes[i],
2223 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002224 /*Mutable=*/true));
Douglas Gregor44b43212008-12-11 16:49:14 +00002225 }
2226
2227 ConstantStringDecl->completeDefinition(*Context);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002228 }
2229 return Context->getTagDeclType(ConstantStringDecl);
2230}
2231
Steve Naroffb29b4272008-04-14 22:03:09 +00002232Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002233 if (!SelGetUidFunctionDecl)
2234 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002235 if (!MsgSendFunctionDecl)
2236 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002237 if (!MsgSendSuperFunctionDecl)
2238 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002239 if (!MsgSendStretFunctionDecl)
2240 SynthMsgSendStretFunctionDecl();
2241 if (!MsgSendSuperStretFunctionDecl)
2242 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002243 if (!MsgSendFpretFunctionDecl)
2244 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002245 if (!GetClassFunctionDecl)
2246 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002247 if (!GetMetaClassFunctionDecl)
2248 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002249
Steve Naroff874e2322007-11-15 10:28:18 +00002250 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002251 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2252 // May need to use objc_msgSend_stret() as well.
2253 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002254 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2255 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00002256 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002257 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002258 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002259 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002260 }
Steve Naroff874e2322007-11-15 10:28:18 +00002261
Steve Naroff934f2762007-10-24 22:48:43 +00002262 // Synthesize a call to objc_msgSend().
2263 llvm::SmallVector<Expr*, 8> MsgExprs;
2264 IdentifierInfo *clsName = Exp->getClassName();
2265
2266 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2267 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002268 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2269 // the 'super' idiom within a class method.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002270 if (!strcmp(clsName->getName(), "super")) {
2271 MsgSendFlavor = MsgSendSuperFunctionDecl;
2272 if (MsgSendStretFlavor)
2273 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2274 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2275
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002276 ObjCInterfaceDecl *SuperDecl =
Steve Naroff54055232008-10-27 17:20:55 +00002277 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002278
2279 llvm::SmallVector<Expr*, 4> InitExprs;
2280
2281 // set the receiver to self, the first argument to all methods.
Steve Naroff621edce2009-04-29 16:37:50 +00002282 InitExprs.push_back(
2283 new (Context) CStyleCastExpr(Context->getObjCIdType(),
2284 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2285 Context->getObjCIdType(),
2286 SourceLocation()),
2287 Context->getObjCIdType(),
2288 SourceLocation(), SourceLocation())); // set the 'receiver'.
2289
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002290 llvm::SmallVector<Expr*, 8> ClsExprs;
2291 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002292 ClsExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002293 SuperDecl->getIdentifier()->getName(),
2294 SuperDecl->getIdentifier()->getLength(),
Chris Lattner726e1682009-02-18 05:49:11 +00002295 false, argType, SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002296 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2297 &ClsExprs[0],
2298 ClsExprs.size());
2299 // To turn off a warning, type-cast to 'id'
Douglas Gregor49badde2008-10-27 19:41:14 +00002300 InitExprs.push_back( // set 'super class', using objc_getClass().
Ted Kremenek8189cde2009-02-07 01:47:29 +00002301 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002302 Cls, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002303 SourceLocation(), SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002304 // struct objc_super
2305 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002306 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002307
Steve Naroff23f41272008-03-11 18:14:26 +00002308 if (LangOpts.Microsoft) {
2309 SynthSuperContructorFunctionDecl();
2310 // Simulate a contructor call...
Ted Kremenek8189cde2009-02-07 01:47:29 +00002311 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff23f41272008-03-11 18:14:26 +00002312 superType, SourceLocation());
Ted Kremenek668bf912009-02-09 20:51:47 +00002313 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2314 InitExprs.size(),
2315 superType, SourceLocation());
Steve Naroff46a98a72008-12-23 20:11:22 +00002316 // The code for super is a little tricky to prevent collision with
2317 // the structure definition in the header. The rewriter has it's own
2318 // internal definition (__rw_objc_super) that is uses. This is why
2319 // we need the cast below. For example:
2320 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2321 //
Ted Kremenek8189cde2009-02-07 01:47:29 +00002322 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Steve Naroff46a98a72008-12-23 20:11:22 +00002323 Context->getPointerType(SuperRep->getType()),
2324 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00002325 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Steve Naroff46a98a72008-12-23 20:11:22 +00002326 SuperRep, Context->getPointerType(superType),
2327 SourceLocation(), SourceLocation());
Steve Naroff23f41272008-03-11 18:14:26 +00002328 } else {
2329 // (struct objc_super) { <exprs from above> }
Ted Kremenek8189cde2009-02-07 01:47:29 +00002330 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
Steve Naroff23f41272008-03-11 18:14:26 +00002331 &InitExprs[0], InitExprs.size(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002332 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00002333 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE,
Chris Lattner418f6c72008-10-26 23:43:26 +00002334 false);
Steve Naroff46a98a72008-12-23 20:11:22 +00002335 // struct objc_super *
Ted Kremenek8189cde2009-02-07 01:47:29 +00002336 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Steve Naroff46a98a72008-12-23 20:11:22 +00002337 Context->getPointerType(SuperRep->getType()),
2338 SourceLocation());
Steve Naroff23f41272008-03-11 18:14:26 +00002339 }
Steve Naroff46a98a72008-12-23 20:11:22 +00002340 MsgExprs.push_back(SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002341 } else {
2342 llvm::SmallVector<Expr*, 8> ClsExprs;
2343 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002344 ClsExprs.push_back(StringLiteral::Create(*Context,
2345 clsName->getName(),
2346 clsName->getLength(),
2347 false, argType,
2348 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002349 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2350 &ClsExprs[0],
2351 ClsExprs.size());
2352 MsgExprs.push_back(Cls);
2353 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002354 } else { // instance message.
2355 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002356
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002357 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002358 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002359 if (MsgSendStretFlavor)
2360 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002361 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2362
2363 llvm::SmallVector<Expr*, 4> InitExprs;
2364
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002365 InitExprs.push_back(
Ted Kremenek8189cde2009-02-07 01:47:29 +00002366 new (Context) CStyleCastExpr(Context->getObjCIdType(),
2367 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002368 Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002369 SourceLocation()),
2370 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002371 SourceLocation(), SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00002372
2373 llvm::SmallVector<Expr*, 8> ClsExprs;
2374 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002375 ClsExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002376 SuperDecl->getIdentifier()->getName(),
2377 SuperDecl->getIdentifier()->getLength(),
Chris Lattner726e1682009-02-18 05:49:11 +00002378 false, argType, SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002379 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002380 &ClsExprs[0],
2381 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002382 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002383 InitExprs.push_back(
Douglas Gregor49badde2008-10-27 19:41:14 +00002384 // set 'super class', using objc_getClass().
Ted Kremenek8189cde2009-02-07 01:47:29 +00002385 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002386 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002387 // struct objc_super
2388 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002389 Expr *SuperRep;
2390
2391 if (LangOpts.Microsoft) {
2392 SynthSuperContructorFunctionDecl();
2393 // Simulate a contructor call...
Ted Kremenek8189cde2009-02-07 01:47:29 +00002394 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroffc0a123c2008-03-11 17:37:02 +00002395 superType, SourceLocation());
Ted Kremenek668bf912009-02-09 20:51:47 +00002396 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2397 InitExprs.size(),
2398 superType, SourceLocation());
Steve Naroff46a98a72008-12-23 20:11:22 +00002399 // The code for super is a little tricky to prevent collision with
2400 // the structure definition in the header. The rewriter has it's own
2401 // internal definition (__rw_objc_super) that is uses. This is why
2402 // we need the cast below. For example:
2403 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2404 //
Ted Kremenek8189cde2009-02-07 01:47:29 +00002405 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Steve Naroff46a98a72008-12-23 20:11:22 +00002406 Context->getPointerType(SuperRep->getType()),
2407 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00002408 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Steve Naroff46a98a72008-12-23 20:11:22 +00002409 SuperRep, Context->getPointerType(superType),
2410 SourceLocation(), SourceLocation());
Steve Naroffc0a123c2008-03-11 17:37:02 +00002411 } else {
2412 // (struct objc_super) { <exprs from above> }
Ted Kremenek8189cde2009-02-07 01:47:29 +00002413 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00002414 &InitExprs[0], InitExprs.size(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002415 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00002416 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002417 }
Steve Naroff46a98a72008-12-23 20:11:22 +00002418 MsgExprs.push_back(SuperRep);
Steve Naroff874e2322007-11-15 10:28:18 +00002419 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002420 // Remove all type-casts because it may contain objc-style types; e.g.
2421 // Foo<Proto> *.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002422 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002423 recExpr = CE->getSubExpr();
Ted Kremenek8189cde2009-02-07 01:47:29 +00002424 recExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(), recExpr,
Douglas Gregor49badde2008-10-27 19:41:14 +00002425 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002426 SourceLocation(), SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002427 MsgExprs.push_back(recExpr);
2428 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002429 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002430 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002431 llvm::SmallVector<Expr*, 8> SelExprs;
2432 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002433 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002434 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002435 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00002436 false, argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00002437 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2438 &SelExprs[0], SelExprs.size());
2439 MsgExprs.push_back(SelExp);
2440
2441 // Now push any user supplied arguments.
2442 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002443 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002444 // Make all implicit casts explicit...ICE comes in handy:-)
2445 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2446 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002447 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002448 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002449 : ICE->getType();
Ted Kremenek8189cde2009-02-07 01:47:29 +00002450 userExpr = new (Context) CStyleCastExpr(type, userExpr, type, SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002451 }
2452 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002453 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002454 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002455 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002456 userExpr = CE->getSubExpr();
Ted Kremenek8189cde2009-02-07 01:47:29 +00002457 userExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002458 userExpr, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002459 SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002460 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002461 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002462 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00002463 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2464 // out the argument in the original expression (since we aren't deleting
2465 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2466 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00002467 }
Steve Naroffab972d32007-11-04 22:37:50 +00002468 // Generate the funky cast.
2469 CastExpr *cast;
2470 llvm::SmallVector<QualType, 8> ArgTypes;
2471 QualType returnType;
2472
2473 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002474 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2475 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2476 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002477 ArgTypes.push_back(Context->getObjCIdType());
2478 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00002479 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002480 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00002481 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2482 E = OMD->param_end(); PI != E; ++PI) {
2483 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002484 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00002485 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002486 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00002487 if (isTopLevelBlockPointerType(t)) {
Ted Kremenek1a1a6e22009-07-16 19:58:26 +00002488 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroffa206b062008-10-29 14:49:46 +00002489 t = Context->getPointerType(BPT->getPointeeType());
2490 }
Steve Naroff352336b2007-11-05 14:36:37 +00002491 ArgTypes.push_back(t);
2492 }
Chris Lattner89951a82009-02-20 18:43:26 +00002493 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2494 ? Context->getObjCIdType() : OMD->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002495 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002496 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002497 }
2498 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002499 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002500
2501 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002502 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002503 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002504
2505 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2506 // If we don't do this cast, we get the following bizarre warning/note:
2507 // xx.m:13: warning: function called through a non-compatible type
2508 // xx.m:13: note: if this code is reached, the program will abort
Ted Kremenek8189cde2009-02-07 01:47:29 +00002509 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy), DRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002510 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002511 SourceLocation(), SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002512
Steve Naroffab972d32007-11-04 22:37:50 +00002513 // Now do the "normal" pointer to function cast.
2514 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002515 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002516 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002517 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroffab972d32007-11-04 22:37:50 +00002518 castType = Context->getPointerType(castType);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002519 cast = new (Context) CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002520
2521 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002522 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Steve Naroffab972d32007-11-04 22:37:50 +00002523
2524 const FunctionType *FT = msgSendType->getAsFunctionType();
Ted Kremenek668bf912009-02-09 20:51:47 +00002525 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2526 MsgExprs.size(),
2527 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002528 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002529 if (MsgSendStretFlavor) {
2530 // We have the method which returns a struct/union. Must also generate
2531 // call to objc_msgSend_stret and hang both varieties on a conditional
2532 // expression which dictate which one to envoke depending on size of
2533 // method's return type.
2534
2535 // Create a reference to the objc_msgSend_stret() declaration.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002536 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002537 SourceLocation());
2538 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Ted Kremenek8189cde2009-02-07 01:47:29 +00002539 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy), STDRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002540 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002541 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002542 // Now do the "normal" pointer to function cast.
2543 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002544 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002545 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002546 castType = Context->getPointerType(castType);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002547 cast = new (Context) CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002548
2549 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002550 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002551
2552 FT = msgSendType->getAsFunctionType();
Ted Kremenek668bf912009-02-09 20:51:47 +00002553 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2554 MsgExprs.size(),
2555 FT->getResultType(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002556
2557 // Build sizeof(returnType)
Douglas Gregorba498172009-03-13 21:01:28 +00002558 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
2559 returnType,
Sebastian Redl05189992008-11-11 17:56:53 +00002560 Context->getSizeType(),
2561 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002562 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2563 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2564 // For X86 it is more complicated and some kind of target specific routine
2565 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002566 unsigned IntSize =
2567 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Ted Kremenek8189cde2009-02-07 01:47:29 +00002568 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002569 Context->IntTy,
2570 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00002571 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002572 BinaryOperator::LE,
2573 Context->IntTy,
2574 SourceLocation());
2575 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2576 ConditionalOperator *CondExpr =
Ted Kremenek8189cde2009-02-07 01:47:29 +00002577 new (Context) ConditionalOperator(lessThanExpr, CE, STCE, returnType);
2578 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002579 }
Steve Naroff621edce2009-04-29 16:37:50 +00002580 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002581 return ReplacingStmt;
2582}
2583
Steve Naroffb29b4272008-04-14 22:03:09 +00002584Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002585 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff80c28552008-10-27 20:54:44 +00002586
Steve Naroff934f2762007-10-24 22:48:43 +00002587 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002588 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002589
Steve Naroff4c3580e2008-12-04 23:50:32 +00002590 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002591 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002592}
2593
Steve Naroff621edce2009-04-29 16:37:50 +00002594// typedef struct objc_object Protocol;
2595QualType RewriteObjC::getProtocolType() {
2596 if (!ProtocolTypeDecl) {
2597 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
2598 SourceLocation(),
2599 &Context->Idents.get("Protocol"),
2600 Context->getObjCIdType());
2601 }
2602 return Context->getTypeDeclType(ProtocolTypeDecl);
2603}
2604
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002605/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00002606/// a synthesized/forward data reference (to the protocol's metadata).
2607/// The forward references (and metadata) are generated in
2608/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00002609Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00002610 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
2611 IdentifierInfo *ID = &Context->Idents.get(Name);
2612 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2613 ID, QualType()/*UNUSED*/, VarDecl::Extern);
2614 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
2615 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
2616 Context->getPointerType(DRE->getType()),
2617 SourceLocation());
2618 CastExpr *castExpr = new (Context) CStyleCastExpr(DerefExpr->getType(), DerefExpr,
2619 DerefExpr->getType(),
2620 SourceLocation(), SourceLocation());
2621 ReplaceStmt(Exp, castExpr);
2622 ProtocolExprDecls.insert(Exp->getProtocol());
2623 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
2624 return castExpr;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002625
2626}
2627
Steve Naroffbaf58c32008-05-31 14:15:04 +00002628bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2629 const char *endBuf) {
2630 while (startBuf < endBuf) {
2631 if (*startBuf == '#') {
2632 // Skip whitespace.
2633 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2634 ;
2635 if (!strncmp(startBuf, "if", strlen("if")) ||
2636 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2637 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2638 !strncmp(startBuf, "define", strlen("define")) ||
2639 !strncmp(startBuf, "undef", strlen("undef")) ||
2640 !strncmp(startBuf, "else", strlen("else")) ||
2641 !strncmp(startBuf, "elif", strlen("elif")) ||
2642 !strncmp(startBuf, "endif", strlen("endif")) ||
2643 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2644 !strncmp(startBuf, "include", strlen("include")) ||
2645 !strncmp(startBuf, "import", strlen("import")) ||
2646 !strncmp(startBuf, "include_next", strlen("include_next")))
2647 return true;
2648 }
2649 startBuf++;
2650 }
2651 return false;
2652}
2653
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002654/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002655/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002656void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002657 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002658 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Chris Lattner8ec03f52008-11-24 03:54:41 +00002659 assert(CDecl->getNameAsCString() &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002660 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002661 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002662 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002663 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002664 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002665 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002666 SourceLocation LocStart = CDecl->getLocStart();
2667 SourceLocation LocEnd = CDecl->getLocEnd();
2668
2669 const char *startBuf = SM->getCharacterData(LocStart);
2670 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002671
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002672 // If no ivars and no root or if its root, directly or indirectly,
2673 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002674 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2675 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00002676 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Chris Lattneraadaf782008-01-31 19:51:04 +00002677 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002678 return;
2679 }
2680
2681 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002682 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002683 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002684 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002685 if (LangOpts.Microsoft)
2686 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002687
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002688 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002689 const char *cursor = strchr(startBuf, '{');
2690 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002691 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00002692 // If the buffer contains preprocessor directives, we do more fine-grained
2693 // rewrites. This is intended to fix code that looks like (which occurs in
2694 // NSURL.h, for example):
2695 //
2696 // #ifdef XYZ
2697 // @interface Foo : NSObject
2698 // #else
2699 // @interface FooBar : NSObject
2700 // #endif
2701 // {
2702 // int i;
2703 // }
2704 // @end
2705 //
2706 // This clause is segregated to avoid breaking the common case.
2707 if (BufferContainsPPDirectives(startBuf, cursor)) {
2708 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2709 CDecl->getClassLoc();
2710 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00002711 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002712
Chris Lattnercafeb352009-02-20 18:18:36 +00002713 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00002714 // advance to the end of the referenced protocols.
2715 while (endHeader < cursor && *endHeader != '>') endHeader++;
2716 endHeader++;
2717 }
2718 // rewrite the original header
2719 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2720 } else {
2721 // rewrite the original header *without* disturbing the '{'
2722 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2723 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002724 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002725 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002726 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002727 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002728 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002729 Result += "_IVARS;\n";
Steve Narofffea763e82007-11-14 19:25:57 +00002730
2731 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002732 SourceLocation OnePastCurly =
2733 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2734 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002735 }
2736 cursor++; // past '{'
2737
2738 // Now comment out any visibility specifiers.
2739 while (cursor < endBuf) {
2740 if (*cursor == '@') {
2741 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002742 // Skip whitespace.
2743 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2744 /*scan*/;
2745
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002746 // FIXME: presence of @public, etc. inside comment results in
2747 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002748 if (!strncmp(cursor, "public", strlen("public")) ||
2749 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002750 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002751 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002752 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002753 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002754 // FIXME: If there are cases where '<' is used in ivar declaration part
2755 // of user code, then scan the ivar list and use needToScanForQualifiers
2756 // for type checking.
2757 else if (*cursor == '<') {
2758 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002759 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002760 cursor = strchr(cursor, '>');
2761 cursor++;
2762 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002763 InsertText(atLoc, " */", 3);
Steve Naroffced80a82008-10-30 12:09:33 +00002764 } else if (*cursor == '^') { // rewrite block specifier.
2765 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2766 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002767 }
Steve Narofffea763e82007-11-14 19:25:57 +00002768 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002769 }
Steve Narofffea763e82007-11-14 19:25:57 +00002770 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002771 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002772 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00002773 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00002774 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002775 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002776 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002777 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002778 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002779 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002780 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002781 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002782 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002783 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002784}
2785
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002786// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002787/// class methods.
Douglas Gregor653f1b12009-04-23 01:02:12 +00002788template<typename MethodIterator>
2789void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
2790 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002791 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002792 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002793 const char *ClassName,
2794 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002795 if (MethodBegin == MethodEnd) return;
2796
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002797 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002798 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002799 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002800 SEL _cmd;
2801 char *method_types;
2802 void *_imp;
2803 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002804 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002805 Result += "\nstruct _objc_method {\n";
2806 Result += "\tSEL _cmd;\n";
2807 Result += "\tchar *method_types;\n";
2808 Result += "\tvoid *_imp;\n";
2809 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002810
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002811 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002812 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002813
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002814 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002815
2816 /* struct {
2817 struct _objc_method_list *next_method;
2818 int method_count;
2819 struct _objc_method method_list[];
2820 }
2821 */
Douglas Gregor653f1b12009-04-23 01:02:12 +00002822 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroff946a6932008-03-11 00:12:29 +00002823 Result += "\nstatic struct {\n";
2824 Result += "\tstruct _objc_method_list *next_method;\n";
2825 Result += "\tint method_count;\n";
2826 Result += "\tstruct _objc_method method_list[";
Douglas Gregor653f1b12009-04-23 01:02:12 +00002827 Result += utostr(NumMethods);
Steve Naroff946a6932008-03-11 00:12:29 +00002828 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002829 Result += prefix;
2830 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2831 Result += "_METHODS_";
2832 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002833 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002834 Result += IsInstanceMethod ? "inst" : "cls";
2835 Result += "_meth\")))= ";
Douglas Gregor653f1b12009-04-23 01:02:12 +00002836 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002837
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002838 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002839 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002840 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002841 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002842 Result += "\", \"";
2843 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002844 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002845 Result += MethodInternalNames[*MethodBegin];
2846 Result += "}\n";
2847 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2848 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002849 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002850 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002851 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002852 Result += "\", \"";
2853 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002854 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002855 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002856 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002857 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002858 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002859}
2860
Steve Naroff621edce2009-04-29 16:37:50 +00002861/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00002862void RewriteObjC::
Steve Naroff621edce2009-04-29 16:37:50 +00002863RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
2864 const char *ClassName, std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002865 static bool objc_protocol_methods = false;
Steve Naroff621edce2009-04-29 16:37:50 +00002866
2867 // Output struct protocol_methods holder of method selector and type.
2868 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2869 /* struct protocol_methods {
2870 SEL _cmd;
2871 char *method_types;
2872 }
2873 */
2874 Result += "\nstruct _protocol_methods {\n";
2875 Result += "\tstruct objc_selector *_cmd;\n";
2876 Result += "\tchar *method_types;\n";
2877 Result += "};\n";
2878
2879 objc_protocol_methods = true;
2880 }
2881 // Do not synthesize the protocol more than once.
2882 if (ObjCSynthesizedProtocols.count(PDecl))
2883 return;
2884
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002885 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2886 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
2887 PDecl->instmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00002888 /* struct _objc_protocol_method_list {
2889 int protocol_method_count;
2890 struct protocol_methods protocols[];
2891 }
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002892 */
Steve Naroff621edce2009-04-29 16:37:50 +00002893 Result += "\nstatic struct {\n";
2894 Result += "\tint protocol_method_count;\n";
2895 Result += "\tstruct _protocol_methods protocol_methods[";
2896 Result += utostr(NumMethods);
2897 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
2898 Result += PDecl->getNameAsString();
2899 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2900 "{\n\t" + utostr(NumMethods) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002901
Steve Naroff621edce2009-04-29 16:37:50 +00002902 // Output instance methods declared in this protocol.
2903 for (ObjCProtocolDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002904 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00002905 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002906 if (I == PDecl->instmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00002907 Result += "\t ,{{(struct objc_selector *)\"";
2908 else
2909 Result += "\t ,{(struct objc_selector *)\"";
2910 Result += (*I)->getSelector().getAsString().c_str();
2911 std::string MethodTypeString;
2912 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2913 Result += "\", \"";
2914 Result += MethodTypeString;
2915 Result += "\"}\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002916 }
Steve Naroff621edce2009-04-29 16:37:50 +00002917 Result += "\t }\n};\n";
2918 }
2919
2920 // Output class methods declared in this protocol.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002921 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
2922 PDecl->classmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00002923 if (NumMethods > 0) {
2924 /* struct _objc_protocol_method_list {
2925 int protocol_method_count;
2926 struct protocol_methods protocols[];
2927 }
2928 */
2929 Result += "\nstatic struct {\n";
2930 Result += "\tint protocol_method_count;\n";
2931 Result += "\tstruct _protocol_methods protocol_methods[";
2932 Result += utostr(NumMethods);
2933 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
2934 Result += PDecl->getNameAsString();
2935 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2936 "{\n\t";
2937 Result += utostr(NumMethods);
2938 Result += "\n";
2939
2940 // Output instance methods declared in this protocol.
2941 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002942 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00002943 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002944 if (I == PDecl->classmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00002945 Result += "\t ,{{(struct objc_selector *)\"";
2946 else
2947 Result += "\t ,{(struct objc_selector *)\"";
2948 Result += (*I)->getSelector().getAsString().c_str();
2949 std::string MethodTypeString;
2950 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2951 Result += "\", \"";
2952 Result += MethodTypeString;
2953 Result += "\"}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002954 }
Steve Naroff621edce2009-04-29 16:37:50 +00002955 Result += "\t }\n};\n";
2956 }
2957
2958 // Output:
2959 /* struct _objc_protocol {
2960 // Objective-C 1.0 extensions
2961 struct _objc_protocol_extension *isa;
2962 char *protocol_name;
2963 struct _objc_protocol **protocol_list;
2964 struct _objc_protocol_method_list *instance_methods;
2965 struct _objc_protocol_method_list *class_methods;
2966 };
2967 */
2968 static bool objc_protocol = false;
2969 if (!objc_protocol) {
2970 Result += "\nstruct _objc_protocol {\n";
2971 Result += "\tstruct _objc_protocol_extension *isa;\n";
2972 Result += "\tchar *protocol_name;\n";
2973 Result += "\tstruct _objc_protocol **protocol_list;\n";
2974 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2975 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002976 Result += "};\n";
2977
Steve Naroff621edce2009-04-29 16:37:50 +00002978 objc_protocol = true;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002979 }
Steve Naroff621edce2009-04-29 16:37:50 +00002980
2981 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2982 Result += PDecl->getNameAsString();
2983 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2984 "{\n\t0, \"";
2985 Result += PDecl->getNameAsString();
2986 Result += "\", 0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002987 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00002988 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
2989 Result += PDecl->getNameAsString();
2990 Result += ", ";
2991 }
2992 else
2993 Result += "0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002994 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00002995 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
2996 Result += PDecl->getNameAsString();
2997 Result += "\n";
2998 }
2999 else
3000 Result += "0\n";
3001 Result += "};\n";
3002
3003 // Mark this protocol as having been generated.
3004 if (!ObjCSynthesizedProtocols.insert(PDecl))
3005 assert(false && "protocol already synthesized");
3006
3007}
3008
3009void RewriteObjC::
3010RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3011 const char *prefix, const char *ClassName,
3012 std::string &Result) {
3013 if (Protocols.empty()) return;
3014
3015 for (unsigned i = 0; i != Protocols.size(); i++)
3016 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3017
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003018 // Output the top lovel protocol meta-data for the class.
3019 /* struct _objc_protocol_list {
3020 struct _objc_protocol_list *next;
3021 int protocol_count;
3022 struct _objc_protocol *class_protocols[];
3023 }
3024 */
3025 Result += "\nstatic struct {\n";
3026 Result += "\tstruct _objc_protocol_list *next;\n";
3027 Result += "\tint protocol_count;\n";
3028 Result += "\tstruct _objc_protocol *class_protocols[";
3029 Result += utostr(Protocols.size());
3030 Result += "];\n} _OBJC_";
3031 Result += prefix;
3032 Result += "_PROTOCOLS_";
3033 Result += ClassName;
3034 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3035 "{\n\t0, ";
3036 Result += utostr(Protocols.size());
3037 Result += "\n";
3038
3039 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003040 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003041 Result += " \n";
3042
3043 for (unsigned i = 1; i != Protocols.size(); i++) {
3044 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003045 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003046 Result += "\n";
3047 }
3048 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003049}
3050
Steve Naroff621edce2009-04-29 16:37:50 +00003051
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003052/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003053/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003054void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003055 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003056 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003057 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003058 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003059 for (CDecl = ClassDecl->getCategoryList(); CDecl;
3060 CDecl = CDecl->getNextClassCategory())
3061 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3062 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003063
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003064 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003065 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003066 FullCategoryName += IDecl->getNameAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003067
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003068 // Build _objc_method_list for class's instance methods if needed
Douglas Gregor653f1b12009-04-23 01:02:12 +00003069 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003070 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003071
3072 // If any of our property implementations have associated getters or
3073 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003074 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3075 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003076 Prop != PropEnd; ++Prop) {
3077 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3078 continue;
3079 if (!(*Prop)->getPropertyIvarDecl())
3080 continue;
3081 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3082 if (!PD)
3083 continue;
3084 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3085 InstanceMethods.push_back(Getter);
3086 if (PD->isReadOnly())
3087 continue;
3088 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3089 InstanceMethods.push_back(Setter);
3090 }
3091 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003092 true, "CATEGORY_", FullCategoryName.c_str(),
3093 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003094
3095 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003096 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003097 false, "CATEGORY_", FullCategoryName.c_str(),
3098 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003099
3100 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003101 // Null CDecl is case of a category implementation with no category interface
3102 if (CDecl)
Steve Naroff621edce2009-04-29 16:37:50 +00003103 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3104 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003105 /* struct _objc_category {
3106 char *category_name;
3107 char *class_name;
3108 struct _objc_method_list *instance_methods;
3109 struct _objc_method_list *class_methods;
3110 struct _objc_protocol_list *protocols;
3111 // Objective-C 1.0 extensions
3112 uint32_t size; // sizeof (struct _objc_category)
3113 struct _objc_property_list *instance_properties; // category's own
3114 // @property decl.
3115 };
3116 */
3117
3118 static bool objc_category = false;
3119 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003120 Result += "\nstruct _objc_category {\n";
3121 Result += "\tchar *category_name;\n";
3122 Result += "\tchar *class_name;\n";
3123 Result += "\tstruct _objc_method_list *instance_methods;\n";
3124 Result += "\tstruct _objc_method_list *class_methods;\n";
3125 Result += "\tstruct _objc_protocol_list *protocols;\n";
3126 Result += "\tunsigned int size;\n";
3127 Result += "\tstruct _objc_property_list *instance_properties;\n";
3128 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003129 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003130 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003131 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3132 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003133 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003134 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003135 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003136 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003137 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003138
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003139 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003140 Result += "\t, (struct _objc_method_list *)"
3141 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3142 Result += FullCategoryName;
3143 Result += "\n";
3144 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003145 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003146 Result += "\t, 0\n";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003147 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003148 Result += "\t, (struct _objc_method_list *)"
3149 "&_OBJC_CATEGORY_CLASS_METHODS_";
3150 Result += FullCategoryName;
3151 Result += "\n";
3152 }
3153 else
3154 Result += "\t, 0\n";
3155
Chris Lattnercafeb352009-02-20 18:18:36 +00003156 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003157 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
3158 Result += FullCategoryName;
3159 Result += "\n";
3160 }
3161 else
3162 Result += "\t, 0\n";
3163 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003164}
3165
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003166/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3167/// ivar offset.
Steve Naroffb29b4272008-04-14 22:03:09 +00003168void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003169 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003170 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003171 if (ivar->isBitField()) {
3172 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3173 // place all bitfields at offset 0.
3174 Result += "0";
3175 } else {
3176 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003177 Result += IDecl->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003178 if (LangOpts.Microsoft)
3179 Result += "_IMPL";
3180 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003181 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003182 Result += ")";
3183 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003184}
3185
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003186//===----------------------------------------------------------------------===//
3187// Meta Data Emission
3188//===----------------------------------------------------------------------===//
3189
Steve Naroffb29b4272008-04-14 22:03:09 +00003190void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003191 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003192 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003193
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003194 // Explictly declared @interface's are already synthesized.
Steve Naroff33feeb02009-04-20 20:09:33 +00003195 if (CDecl->isImplicitInterfaceDecl()) {
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003196 // FIXME: Implementation of a class with no @interface (legacy) doese not
3197 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003198 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003199 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003200
Chris Lattnerbe6df082007-12-12 07:56:42 +00003201 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003202 unsigned NumIvars = !IDecl->ivar_empty()
3203 ? IDecl->ivar_size()
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003204 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003205 if (NumIvars > 0) {
3206 static bool objc_ivar = false;
3207 if (!objc_ivar) {
3208 /* struct _objc_ivar {
3209 char *ivar_name;
3210 char *ivar_type;
3211 int ivar_offset;
3212 };
3213 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003214 Result += "\nstruct _objc_ivar {\n";
3215 Result += "\tchar *ivar_name;\n";
3216 Result += "\tchar *ivar_type;\n";
3217 Result += "\tint ivar_offset;\n";
3218 Result += "};\n";
3219
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003220 objc_ivar = true;
3221 }
3222
Steve Naroff946a6932008-03-11 00:12:29 +00003223 /* struct {
3224 int ivar_count;
3225 struct _objc_ivar ivar_list[nIvars];
3226 };
3227 */
3228 Result += "\nstatic struct {\n";
3229 Result += "\tint ivar_count;\n";
3230 Result += "\tstruct _objc_ivar ivar_list[";
3231 Result += utostr(NumIvars);
3232 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003233 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003234 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003235 "{\n\t";
3236 Result += utostr(NumIvars);
3237 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003238
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003239 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003240 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003241 if (!IDecl->ivar_empty()) {
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003242 for (ObjCImplementationDecl::ivar_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003243 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003244 IV != IVEnd; ++IV)
3245 IVars.push_back(*IV);
3246 IVI = IVars.begin();
3247 IVE = IVars.end();
Chris Lattnerbe6df082007-12-12 07:56:42 +00003248 } else {
3249 IVI = CDecl->ivar_begin();
3250 IVE = CDecl->ivar_end();
3251 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003252 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003253 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003254 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003255 std::string TmpString, StrEncoding;
3256 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3257 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003258 Result += StrEncoding;
3259 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003260 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003261 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003262 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003263 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003264 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003265 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003266 std::string TmpString, StrEncoding;
3267 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3268 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003269 Result += StrEncoding;
3270 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003271 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003272 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003273 }
3274
3275 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003276 }
3277
3278 // Build _objc_method_list for class's instance methods if needed
Douglas Gregor653f1b12009-04-23 01:02:12 +00003279 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003280 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003281
3282 // If any of our property implementations have associated getters or
3283 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003284 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3285 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003286 Prop != PropEnd; ++Prop) {
3287 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3288 continue;
3289 if (!(*Prop)->getPropertyIvarDecl())
3290 continue;
3291 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3292 if (!PD)
3293 continue;
3294 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3295 InstanceMethods.push_back(Getter);
3296 if (PD->isReadOnly())
3297 continue;
3298 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3299 InstanceMethods.push_back(Setter);
3300 }
3301 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003302 true, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003303
3304 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003305 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003306 false, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003307
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003308 // Protocols referenced in class declaration?
Steve Naroff621edce2009-04-29 16:37:50 +00003309 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3310 "CLASS", CDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003311
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003312 // Declaration of class/meta-class metadata
3313 /* struct _objc_class {
3314 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003315 const char *super_class_name;
3316 char *name;
3317 long version;
3318 long info;
3319 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003320 struct _objc_ivar_list *ivars;
3321 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003322 struct objc_cache *cache;
3323 struct objc_protocol_list *protocols;
3324 const char *ivar_layout;
3325 struct _objc_class_ext *ext;
3326 };
3327 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003328 static bool objc_class = false;
3329 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003330 Result += "\nstruct _objc_class {\n";
3331 Result += "\tstruct _objc_class *isa;\n";
3332 Result += "\tconst char *super_class_name;\n";
3333 Result += "\tchar *name;\n";
3334 Result += "\tlong version;\n";
3335 Result += "\tlong info;\n";
3336 Result += "\tlong instance_size;\n";
3337 Result += "\tstruct _objc_ivar_list *ivars;\n";
3338 Result += "\tstruct _objc_method_list *methods;\n";
3339 Result += "\tstruct objc_cache *cache;\n";
3340 Result += "\tstruct _objc_protocol_list *protocols;\n";
3341 Result += "\tconst char *ivar_layout;\n";
3342 Result += "\tstruct _objc_class_ext *ext;\n";
3343 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003344 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003345 }
3346
3347 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003348 ObjCInterfaceDecl *RootClass = 0;
3349 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003350 while (SuperClass) {
3351 RootClass = SuperClass;
3352 SuperClass = SuperClass->getSuperClass();
3353 }
3354 SuperClass = CDecl->getSuperClass();
3355
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003356 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003357 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003358 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003359 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003360 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003361 Result += "\"";
3362
3363 if (SuperClass) {
3364 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003365 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003366 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003367 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003368 Result += "\"";
3369 }
3370 else {
3371 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003372 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003373 Result += "\"";
3374 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003375 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003376 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003377 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003378 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff23f41272008-03-11 18:14:26 +00003379 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003380 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003381 Result += "\n";
3382 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003383 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003384 Result += ", 0\n";
Chris Lattnercafeb352009-02-20 18:18:36 +00003385 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003386 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003387 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003388 Result += ",0,0\n";
3389 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003390 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003391 Result += "\t,0,0,0,0\n";
3392 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003393
3394 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003395 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003396 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003397 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003398 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003399 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003400 if (SuperClass) {
3401 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003402 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003403 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003404 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003405 Result += "\"";
3406 }
3407 else {
3408 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003409 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003410 Result += "\"";
3411 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003412 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003413 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003414 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003415 Result += ",0";
3416 else {
3417 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003418 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003419 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003420 if (LangOpts.Microsoft)
3421 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003422 Result += ")";
3423 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003424 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003425 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003426 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003427 Result += "\n\t";
3428 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003429 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003430 Result += ",0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003431 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroff946a6932008-03-11 00:12:29 +00003432 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003433 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003434 Result += ", 0\n\t";
3435 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003436 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003437 Result += ",0,0";
Chris Lattnercafeb352009-02-20 18:18:36 +00003438 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003439 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003440 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003441 Result += ", 0,0\n";
3442 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003443 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003444 Result += ",0,0,0\n";
3445 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003446}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003447
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003448/// RewriteImplementations - This routine rewrites all method implementations
3449/// and emits meta-data.
3450
Steve Narofface66252008-11-13 20:07:04 +00003451void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003452 int ClsDefCount = ClassImplementation.size();
3453 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003454
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003455 // Rewrite implemented methods
3456 for (int i = 0; i < ClsDefCount; i++)
3457 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003458
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003459 for (int i = 0; i < CatDefCount; i++)
3460 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003461}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003462
Steve Narofface66252008-11-13 20:07:04 +00003463void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3464 int ClsDefCount = ClassImplementation.size();
3465 int CatDefCount = CategoryImplementation.size();
3466
Steve Naroff5df5b762008-05-07 21:23:49 +00003467 // This is needed for determining instance variable offsets.
Steve Naroffa11440b2008-08-05 18:47:23 +00003468 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003469 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003470 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003471 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003472
3473 // For each implemented category, write out all its meta data.
3474 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003475 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroff621edce2009-04-29 16:37:50 +00003476
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003477 // Write objc_symtab metadata
3478 /*
3479 struct _objc_symtab
3480 {
3481 long sel_ref_cnt;
3482 SEL *refs;
3483 short cls_def_cnt;
3484 short cat_def_cnt;
3485 void *defs[cls_def_cnt + cat_def_cnt];
3486 };
3487 */
3488
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003489 Result += "\nstruct _objc_symtab {\n";
3490 Result += "\tlong sel_ref_cnt;\n";
3491 Result += "\tSEL *refs;\n";
3492 Result += "\tshort cls_def_cnt;\n";
3493 Result += "\tshort cat_def_cnt;\n";
3494 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3495 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003496
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003497 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003498 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003499 Result += "\t0, 0, " + utostr(ClsDefCount)
3500 + ", " + utostr(CatDefCount) + "\n";
3501 for (int i = 0; i < ClsDefCount; i++) {
3502 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003503 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003504 Result += "\n";
3505 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003506
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003507 for (int i = 0; i < CatDefCount; i++) {
3508 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003509 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003510 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003511 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003512 Result += "\n";
3513 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003514
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003515 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003516
3517 // Write objc_module metadata
3518
3519 /*
3520 struct _objc_module {
3521 long version;
3522 long size;
3523 const char *name;
3524 struct _objc_symtab *symtab;
3525 }
3526 */
3527
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003528 Result += "\nstruct _objc_module {\n";
3529 Result += "\tlong version;\n";
3530 Result += "\tlong size;\n";
3531 Result += "\tconst char *name;\n";
3532 Result += "\tstruct _objc_symtab *symtab;\n";
3533 Result += "};\n\n";
3534 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003535 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003536 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3537 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003538 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003539
3540 if (LangOpts.Microsoft) {
Steve Naroff621edce2009-04-29 16:37:50 +00003541 if (ProtocolExprDecls.size()) {
3542 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
3543 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
3544 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
3545 E = ProtocolExprDecls.end(); I != E; ++I) {
3546 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
3547 Result += (*I)->getNameAsString();
3548 Result += " = &_OBJC_PROTOCOL_";
3549 Result += (*I)->getNameAsString();
3550 Result += ";\n";
3551 }
3552 Result += "#pragma data_seg(pop)\n\n";
3553 }
Steve Naroff4f943c22008-03-10 20:43:59 +00003554 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003555 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003556 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3557 Result += "&_OBJC_MODULES;\n";
3558 Result += "#pragma data_seg(pop)\n\n";
3559 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003560}
Chris Lattner311ff022007-10-16 22:36:42 +00003561
Steve Naroff54055232008-10-27 17:20:55 +00003562std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3563 const char *funcName,
3564 std::string Tag) {
3565 const FunctionType *AFT = CE->getFunctionType();
3566 QualType RT = AFT->getResultType();
3567 std::string StructRef = "struct " + Tag;
3568 std::string S = "static " + RT.getAsString() + " __" +
3569 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003570
Steve Naroff54055232008-10-27 17:20:55 +00003571 BlockDecl *BD = CE->getBlockDecl();
3572
Douglas Gregor72564e72009-02-26 23:50:07 +00003573 if (isa<FunctionNoProtoType>(AFT)) {
Steve Naroffdf8570d2009-02-02 17:19:26 +00003574 // No user-supplied arguments. Still need to pass in a pointer to the
3575 // block (to reference imported block decl refs).
3576 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00003577 } else if (BD->param_empty()) {
3578 S += "(" + StructRef + " *__cself)";
3579 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003580 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00003581 assert(FT && "SynthesizeBlockFunc: No function proto");
3582 S += '(';
3583 // first add the implicit argument.
3584 S += StructRef + " *__cself, ";
3585 std::string ParamStr;
3586 for (BlockDecl::param_iterator AI = BD->param_begin(),
3587 E = BD->param_end(); AI != E; ++AI) {
3588 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003589 ParamStr = (*AI)->getNameAsString();
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00003590 (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00003591 S += ParamStr;
3592 }
3593 if (FT->isVariadic()) {
3594 if (!BD->param_empty()) S += ", ";
3595 S += "...";
3596 }
3597 S += ')';
3598 }
3599 S += " {\n";
3600
3601 // Create local declarations to avoid rewriting all closure decl ref exprs.
3602 // First, emit a declaration for all "by ref" decls.
3603 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3604 E = BlockByRefDecls.end(); I != E; ++I) {
3605 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003606 std::string Name = (*I)->getNameAsString();
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00003607 Context->getPointerType((*I)->getType()).getAsStringInternal(Name,
3608 Context->PrintingPolicy);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003609 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Steve Naroff54055232008-10-27 17:20:55 +00003610 }
3611 // Next, emit a declaration for all "by copy" declarations.
3612 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3613 E = BlockByCopyDecls.end(); I != E; ++I) {
3614 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003615 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003616 // Handle nested closure invocation. For example:
3617 //
3618 // void (^myImportedClosure)(void);
3619 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3620 //
3621 // void (^anotherClosure)(void);
3622 // anotherClosure = ^(void) {
3623 // myImportedClosure(); // import and invoke the closure
3624 // };
3625 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003626 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003627 S += "struct __block_impl *";
3628 else
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00003629 (*I)->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003630 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff54055232008-10-27 17:20:55 +00003631 }
3632 std::string RewrittenStr = RewrittenBlockExprs[CE];
3633 const char *cstr = RewrittenStr.c_str();
3634 while (*cstr++ != '{') ;
3635 S += cstr;
3636 S += "\n";
3637 return S;
3638}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003639
Steve Naroff54055232008-10-27 17:20:55 +00003640std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3641 const char *funcName,
3642 std::string Tag) {
3643 std::string StructRef = "struct " + Tag;
3644 std::string S = "static void __";
3645
3646 S += funcName;
3647 S += "_block_copy_" + utostr(i);
3648 S += "(" + StructRef;
3649 S += "*dst, " + StructRef;
3650 S += "*src) {";
3651 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3652 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00003653 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003654 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00003655 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003656 S += (*I)->getNameAsString();
Steve Naroff5bc60d02008-12-16 15:50:30 +00003657 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);}";
Steve Naroff54055232008-10-27 17:20:55 +00003658 }
3659 S += "\nstatic void __";
3660 S += funcName;
3661 S += "_block_dispose_" + utostr(i);
3662 S += "(" + StructRef;
3663 S += "*src) {";
3664 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3665 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00003666 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003667 S += (*I)->getNameAsString();
Steve Naroff5bc60d02008-12-16 15:50:30 +00003668 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003669 }
3670 S += "}\n";
3671 return S;
3672}
3673
3674std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3675 bool hasCopyDisposeHelpers) {
Steve Naroffced80a82008-10-30 12:09:33 +00003676 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003677 std::string Constructor = " " + Tag;
3678
3679 S += " {\n struct __block_impl impl;\n";
3680
3681 if (hasCopyDisposeHelpers)
3682 S += " void *copy;\n void *dispose;\n";
3683
3684 Constructor += "(void *fp";
3685
3686 if (hasCopyDisposeHelpers)
3687 Constructor += ", void *copyHelp, void *disposeHelp";
3688
3689 if (BlockDeclRefs.size()) {
3690 // Output all "by copy" declarations.
3691 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3692 E = BlockByCopyDecls.end(); I != E; ++I) {
3693 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003694 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003695 std::string ArgName = "_" + FieldName;
3696 // Handle nested closure invocation. For example:
3697 //
3698 // void (^myImportedBlock)(void);
3699 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3700 //
3701 // void (^anotherBlock)(void);
3702 // anotherBlock = ^(void) {
3703 // myImportedBlock(); // import and invoke the closure
3704 // };
3705 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003706 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003707 S += "struct __block_impl *";
3708 Constructor += ", void *" + ArgName;
3709 } else {
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00003710 (*I)->getType().getAsStringInternal(FieldName, Context->PrintingPolicy);
3711 (*I)->getType().getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00003712 Constructor += ", " + ArgName;
3713 }
3714 S += FieldName + ";\n";
3715 }
3716 // Output all "by ref" declarations.
3717 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3718 E = BlockByRefDecls.end(); I != E; ++I) {
3719 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003720 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003721 std::string ArgName = "_" + FieldName;
3722 // Handle nested closure invocation. For example:
3723 //
3724 // void (^myImportedBlock)(void);
3725 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3726 //
3727 // void (^anotherBlock)(void);
3728 // anotherBlock = ^(void) {
3729 // myImportedBlock(); // import and invoke the closure
3730 // };
3731 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003732 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003733 S += "struct __block_impl *";
3734 Constructor += ", void *" + ArgName;
3735 } else {
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00003736 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName,
3737 Context->PrintingPolicy);
3738 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName,
3739 Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00003740 Constructor += ", " + ArgName;
3741 }
3742 S += FieldName + "; // by ref\n";
3743 }
3744 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00003745 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003746 if (GlobalVarDecl)
3747 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3748 else
3749 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3750 Constructor += " impl.Size = sizeof(";
Steve Naroff54055232008-10-27 17:20:55 +00003751 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3752
3753 if (hasCopyDisposeHelpers)
3754 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3755
3756 // Initialize all "by copy" arguments.
3757 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3758 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003759 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003760 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003761 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003762 Constructor += Name + " = (struct __block_impl *)_";
3763 else
3764 Constructor += Name + " = _";
3765 Constructor += Name + ";\n";
3766 }
3767 // Initialize all "by ref" arguments.
3768 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3769 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003770 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003771 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003772 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003773 Constructor += Name + " = (struct __block_impl *)_";
3774 else
3775 Constructor += Name + " = _";
3776 Constructor += Name + ";\n";
3777 }
3778 } else {
3779 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00003780 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003781 if (GlobalVarDecl)
3782 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3783 else
3784 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3785 Constructor += " impl.Size = sizeof(";
Steve Naroff54055232008-10-27 17:20:55 +00003786 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3787 if (hasCopyDisposeHelpers)
3788 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3789 }
3790 Constructor += " ";
3791 Constructor += "}\n";
3792 S += Constructor;
3793 S += "};\n";
3794 return S;
3795}
3796
3797void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3798 const char *FunName) {
3799 // Insert closures that were part of the function.
3800 for (unsigned i = 0; i < Blocks.size(); i++) {
3801
3802 CollectBlockDeclRefInfo(Blocks[i]);
3803
3804 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3805
3806 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
3807 ImportedBlockDecls.size() > 0);
3808
3809 InsertText(FunLocStart, CI.c_str(), CI.size());
3810
3811 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
3812
3813 InsertText(FunLocStart, CF.c_str(), CF.size());
3814
3815 if (ImportedBlockDecls.size()) {
3816 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3817 InsertText(FunLocStart, HF.c_str(), HF.size());
3818 }
3819
3820 BlockDeclRefs.clear();
3821 BlockByRefDecls.clear();
3822 BlockByCopyDecls.clear();
3823 BlockCallExprs.clear();
3824 ImportedBlockDecls.clear();
3825 }
3826 Blocks.clear();
3827 RewrittenBlockExprs.clear();
3828}
3829
3830void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3831 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner8ec03f52008-11-24 03:54:41 +00003832 const char *FuncName = FD->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003833
3834 SynthesizeBlockLiterals(FunLocStart, FuncName);
3835}
3836
3837void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00003838 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3839 //SourceLocation FunLocStart = MD->getLocStart();
3840 // FIXME: This hack works around a bug in Rewrite.InsertText().
3841 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattner077bf5e2008-11-24 03:33:13 +00003842 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003843 // Convert colons to underscores.
3844 std::string::size_type loc = 0;
3845 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3846 FuncName.replace(loc, 1, "_");
3847
3848 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3849}
3850
3851void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3852 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3853 CI != E; ++CI)
3854 if (*CI) {
3855 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3856 GetBlockDeclRefExprs(CBE->getBody());
3857 else
3858 GetBlockDeclRefExprs(*CI);
3859 }
3860 // Handle specific things.
3861 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3862 // FIXME: Handle enums.
3863 if (!isa<FunctionDecl>(CDRE->getDecl()))
3864 BlockDeclRefs.push_back(CDRE);
3865 return;
3866}
3867
3868void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3869 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3870 CI != E; ++CI)
3871 if (*CI) {
3872 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3873 GetBlockCallExprs(CBE->getBody());
3874 else
3875 GetBlockCallExprs(*CI);
3876 }
3877
3878 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
3879 if (CE->getCallee()->getType()->isBlockPointerType()) {
3880 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
3881 }
3882 }
3883 return;
3884}
3885
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003886Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00003887 // Navigate to relevant type information.
3888 const char *closureName = 0;
3889 const BlockPointerType *CPT = 0;
3890
3891 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003892 closureName = DRE->getDecl()->getNameAsCString();
Ted Kremenek1a1a6e22009-07-16 19:58:26 +00003893 CPT = DRE->getType()->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00003894 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003895 closureName = CDRE->getDecl()->getNameAsCString();
Ted Kremenek1a1a6e22009-07-16 19:58:26 +00003896 CPT = CDRE->getType()->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00003897 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003898 closureName = MExpr->getMemberDecl()->getNameAsCString();
Ted Kremenek1a1a6e22009-07-16 19:58:26 +00003899 CPT = MExpr->getType()->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00003900 } else {
3901 assert(1 && "RewriteBlockClass: Bad type");
3902 }
3903 assert(CPT && "RewriteBlockClass: Bad type");
3904 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
3905 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00003906 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00003907 // FTP will be null for closures that don't take arguments.
3908
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003909 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
3910 SourceLocation(),
3911 &Context->Idents.get("__block_impl"));
3912 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00003913
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003914 // Generate a funky cast.
3915 llvm::SmallVector<QualType, 8> ArgTypes;
3916
3917 // Push the block argument type.
3918 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00003919 if (FTP) {
Douglas Gregor72564e72009-02-26 23:50:07 +00003920 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003921 E = FTP->arg_type_end(); I && (I != E); ++I) {
3922 QualType t = *I;
3923 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003924 if (isTopLevelBlockPointerType(t)) {
Ted Kremenek1a1a6e22009-07-16 19:58:26 +00003925 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003926 t = Context->getPointerType(BPT->getPointeeType());
3927 }
3928 ArgTypes.push_back(t);
3929 }
Steve Naroff54055232008-10-27 17:20:55 +00003930 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003931 // Now do the pointer to function cast.
3932 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
3933 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
3934
3935 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Steve Naroff54055232008-10-27 17:20:55 +00003936
Ted Kremenek8189cde2009-02-07 01:47:29 +00003937 CastExpr *BlkCast = new (Context) CStyleCastExpr(PtrBlock, Exp->getCallee(),
3938 PtrBlock, SourceLocation(),
3939 SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003940 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003941 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3942 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003943 //PE->dump();
Steve Naroff54055232008-10-27 17:20:55 +00003944
Douglas Gregor44b43212008-12-11 16:49:14 +00003945 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3946 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003947 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek8189cde2009-02-07 01:47:29 +00003948 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
3949 FD->getType());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003950
Ted Kremenek8189cde2009-02-07 01:47:29 +00003951 CastExpr *FunkCast = new (Context) CStyleCastExpr(PtrToFuncCastType, ME,
3952 PtrToFuncCastType,
3953 SourceLocation(),
3954 SourceLocation());
3955 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003956
3957 llvm::SmallVector<Expr*, 8> BlkExprs;
3958 // Add the implicit argument.
3959 BlkExprs.push_back(BlkCast);
3960 // Add the user arguments.
Steve Naroff54055232008-10-27 17:20:55 +00003961 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3962 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003963 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00003964 }
Ted Kremenek668bf912009-02-09 20:51:47 +00003965 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
3966 BlkExprs.size(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00003967 Exp->getType(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003968 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00003969}
3970
3971void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003972 Stmt *BlockCall = SynthesizeBlockCall(Exp);
3973 ReplaceStmt(Exp, BlockCall);
Steve Naroff54055232008-10-27 17:20:55 +00003974}
3975
Steve Naroff621edce2009-04-29 16:37:50 +00003976// We need to return the rewritten expression to handle cases where the
3977// BlockDeclRefExpr is embedded in another expression being rewritten.
3978// For example:
3979//
3980// int main() {
3981// __block Foo *f;
3982// __block int i;
3983//
3984// void (^myblock)() = ^() {
3985// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
3986// i = 77;
3987// };
3988//}
3989Stmt *RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
Steve Naroff54055232008-10-27 17:20:55 +00003990 // FIXME: Add more elaborate code generation required by the ABI.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003991 Expr *DerefExpr = new (Context) UnaryOperator(BDRE, UnaryOperator::Deref,
Steve Naroffdf8570d2009-02-02 17:19:26 +00003992 Context->getPointerType(BDRE->getType()),
3993 SourceLocation());
3994 // Need parens to enforce precedence.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003995 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), DerefExpr);
Steve Naroffdf8570d2009-02-02 17:19:26 +00003996 ReplaceStmt(BDRE, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00003997 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00003998}
3999
Steve Naroffb2f9e512008-11-03 23:29:32 +00004000void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4001 SourceLocation LocStart = CE->getLParenLoc();
4002 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00004003
4004 // Need to avoid trying to rewrite synthesized casts.
4005 if (LocStart.isInvalid())
4006 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00004007 // Need to avoid trying to rewrite casts contained in macros.
4008 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4009 return;
Steve Narofffa15fd92008-10-28 20:29:00 +00004010
Steve Naroff54055232008-10-27 17:20:55 +00004011 const char *startBuf = SM->getCharacterData(LocStart);
4012 const char *endBuf = SM->getCharacterData(LocEnd);
4013
4014 // advance the location to startArgList.
4015 const char *argPtr = startBuf;
4016
4017 while (*argPtr++ && (argPtr < endBuf)) {
4018 switch (*argPtr) {
4019 case '^':
4020 // Replace the '^' with '*'.
4021 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
4022 ReplaceText(LocStart, 1, "*", 1);
4023 break;
4024 }
4025 }
4026 return;
4027}
4028
4029void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4030 SourceLocation DeclLoc = FD->getLocation();
4031 unsigned parenCount = 0;
4032
4033 // We have 1 or more arguments that have closure pointers.
4034 const char *startBuf = SM->getCharacterData(DeclLoc);
4035 const char *startArgList = strchr(startBuf, '(');
4036
4037 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4038
4039 parenCount++;
4040 // advance the location to startArgList.
4041 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4042 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4043
4044 const char *argPtr = startArgList;
4045
4046 while (*argPtr++ && parenCount) {
4047 switch (*argPtr) {
4048 case '^':
4049 // Replace the '^' with '*'.
4050 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
4051 ReplaceText(DeclLoc, 1, "*", 1);
4052 break;
4053 case '(':
4054 parenCount++;
4055 break;
4056 case ')':
4057 parenCount--;
4058 break;
4059 }
4060 }
4061 return;
4062}
4063
4064bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004065 const FunctionProtoType *FTP;
Ted Kremenek1a1a6e22009-07-16 19:58:26 +00004066 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004067 if (PT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004068 FTP = PT->getPointeeType()->getAsFunctionProtoType();
Steve Naroff54055232008-10-27 17:20:55 +00004069 } else {
Ted Kremenek1a1a6e22009-07-16 19:58:26 +00004070 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004071 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
Douglas Gregor72564e72009-02-26 23:50:07 +00004072 FTP = BPT->getPointeeType()->getAsFunctionProtoType();
Steve Naroff54055232008-10-27 17:20:55 +00004073 }
4074 if (FTP) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004075 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004076 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004077 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004078 return true;
4079 }
4080 return false;
4081}
4082
Ted Kremenek8189cde2009-02-07 01:47:29 +00004083void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4084 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004085 const char *argPtr = strchr(Name, '(');
4086 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4087
4088 LParen = argPtr; // output the start.
4089 argPtr++; // skip past the left paren.
4090 unsigned parenCount = 1;
4091
4092 while (*argPtr && parenCount) {
4093 switch (*argPtr) {
4094 case '(': parenCount++; break;
4095 case ')': parenCount--; break;
4096 default: break;
4097 }
4098 if (parenCount) argPtr++;
4099 }
4100 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4101 RParen = argPtr; // output the end
4102}
4103
4104void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4105 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4106 RewriteBlockPointerFunctionArgs(FD);
4107 return;
4108 }
4109 // Handle Variables and Typedefs.
4110 SourceLocation DeclLoc = ND->getLocation();
4111 QualType DeclT;
4112 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4113 DeclT = VD->getType();
4114 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4115 DeclT = TDD->getUnderlyingType();
4116 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4117 DeclT = FD->getType();
4118 else
4119 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
4120
4121 const char *startBuf = SM->getCharacterData(DeclLoc);
4122 const char *endBuf = startBuf;
4123 // scan backward (from the decl location) for the end of the previous decl.
4124 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4125 startBuf--;
4126
4127 // *startBuf != '^' if we are dealing with a pointer to function that
4128 // may take block argument types (which will be handled below).
4129 if (*startBuf == '^') {
4130 // Replace the '^' with '*', computing a negative offset.
4131 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4132 ReplaceText(DeclLoc, 1, "*", 1);
4133 }
4134 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4135 // Replace the '^' with '*' for arguments.
4136 DeclLoc = ND->getLocation();
4137 startBuf = SM->getCharacterData(DeclLoc);
4138 const char *argListBegin, *argListEnd;
4139 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4140 while (argListBegin < argListEnd) {
4141 if (*argListBegin == '^') {
4142 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
4143 ReplaceText(CaretLoc, 1, "*", 1);
4144 }
4145 argListBegin++;
4146 }
4147 }
4148 return;
4149}
4150
4151void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4152 // Add initializers for any closure decl refs.
4153 GetBlockDeclRefExprs(Exp->getBody());
4154 if (BlockDeclRefs.size()) {
4155 // Unique all "by copy" declarations.
4156 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4157 if (!BlockDeclRefs[i]->isByRef())
4158 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
4159 // Unique all "by ref" declarations.
4160 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4161 if (BlockDeclRefs[i]->isByRef()) {
4162 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
4163 }
4164 // Find any imported blocks...they will need special attention.
4165 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Steve Naroff47a24222008-12-11 20:51:38 +00004166 if (BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroff00072682008-11-13 17:40:07 +00004167 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff54055232008-10-27 17:20:55 +00004168 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4169 }
4170 }
4171}
4172
Steve Narofffa15fd92008-10-28 20:29:00 +00004173FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4174 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00004175 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Steve Narofffa15fd92008-10-28 20:29:00 +00004176 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Douglas Gregor2224f842009-02-25 16:33:18 +00004177 ID, FType, FunctionDecl::Extern, false,
4178 false);
Steve Narofffa15fd92008-10-28 20:29:00 +00004179}
4180
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004181Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004182 Blocks.push_back(Exp);
4183
4184 CollectBlockDeclRefInfo(Exp);
4185 std::string FuncName;
4186
4187 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00004188 FuncName = CurFunctionDef->getNameAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00004189 else if (CurMethodDef) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00004190 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00004191 // Convert colons to underscores.
4192 std::string::size_type loc = 0;
4193 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4194 FuncName.replace(loc, 1, "_");
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004195 } else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004196 FuncName = std::string(GlobalVarDecl->getNameAsString());
Steve Narofffa15fd92008-10-28 20:29:00 +00004197
4198 std::string BlockNumber = utostr(Blocks.size()-1);
4199
4200 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4201 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4202
4203 // Get a pointer to the function type so we can cast appropriately.
4204 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4205
4206 FunctionDecl *FD;
4207 Expr *NewRep;
4208
4209 // Simulate a contructor call...
4210 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004211 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004212
4213 llvm::SmallVector<Expr*, 4> InitExprs;
4214
Steve Narofffdc03722008-10-29 21:23:59 +00004215 // Initialize the block function.
Steve Narofffa15fd92008-10-28 20:29:00 +00004216 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004217 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4218 SourceLocation());
4219 CastExpr *castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4220 Context->VoidPtrTy, SourceLocation(),
4221 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004222 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00004223
4224 if (ImportedBlockDecls.size()) {
4225 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00004226 FD = SynthBlockInitFunctionDecl(Buf.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004227 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4228 castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4229 Context->VoidPtrTy, SourceLocation(),
4230 SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00004231 InitExprs.push_back(castExpr);
4232
Steve Narofffa15fd92008-10-28 20:29:00 +00004233 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00004234 FD = SynthBlockInitFunctionDecl(Buf.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004235 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4236 castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4237 Context->VoidPtrTy, SourceLocation(),
4238 SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00004239 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00004240 }
4241 // Add initializers for any closure decl refs.
4242 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00004243 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00004244 // Output all "by copy" declarations.
4245 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4246 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004247 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00004248 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner8ec03f52008-11-24 03:54:41 +00004249 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004250 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004251 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004252 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004253 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4254 Exp = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4255 Context->VoidPtrTy, SourceLocation(),
4256 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004257 } else {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004258 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004259 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004260 }
Steve Narofffdc03722008-10-29 21:23:59 +00004261 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004262 }
4263 // Output all "by ref" declarations.
4264 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4265 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004266 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004267 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4268 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Steve Narofffdc03722008-10-29 21:23:59 +00004269 Context->getPointerType(Exp->getType()),
4270 SourceLocation());
Steve Naroff707b0fe2008-11-14 21:36:12 +00004271 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004272 }
4273 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004274 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4275 FType, SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004276 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Steve Narofffa15fd92008-10-28 20:29:00 +00004277 Context->getPointerType(NewRep->getType()),
4278 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004279 NewRep = new (Context) CStyleCastExpr(FType, NewRep, FType, SourceLocation(),
4280 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004281 BlockDeclRefs.clear();
4282 BlockByRefDecls.clear();
4283 BlockByCopyDecls.clear();
4284 ImportedBlockDecls.clear();
4285 return NewRep;
4286}
4287
4288//===----------------------------------------------------------------------===//
4289// Function Body / Expression rewriting
4290//===----------------------------------------------------------------------===//
4291
Steve Naroffc77a6362008-12-04 16:24:46 +00004292// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4293// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4294// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4295// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4296// Since the rewriter isn't capable of rewriting rewritten code, it's important
4297// we get this right.
4298void RewriteObjC::CollectPropertySetters(Stmt *S) {
4299 // Perform a bottom up traversal of all children.
4300 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4301 CI != E; ++CI)
4302 if (*CI)
4303 CollectPropertySetters(*CI);
4304
4305 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4306 if (BinOp->isAssignmentOp()) {
4307 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4308 PropSetters[PRE] = BinOp;
4309 }
4310 }
4311}
4312
Steve Narofffa15fd92008-10-28 20:29:00 +00004313Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4314 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4315 isa<DoStmt>(S) || isa<ForStmt>(S))
4316 Stmts.push_back(S);
4317 else if (isa<ObjCForCollectionStmt>(S)) {
4318 Stmts.push_back(S);
4319 ObjCBcLabelNo.push_back(++BcLabelCount);
4320 }
4321
4322 SourceRange OrigStmtRange = S->getSourceRange();
4323
4324 // Perform a bottom up rewrite of all children.
4325 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4326 CI != E; ++CI)
4327 if (*CI) {
4328 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
4329 if (newStmt)
4330 *CI = newStmt;
4331 }
4332
4333 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4334 // Rewrite the block body in place.
4335 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4336
4337 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004338 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
4339 RewrittenBlockExprs[BE] = Str;
Steve Narofffa15fd92008-10-28 20:29:00 +00004340
4341 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4342 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004343 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00004344 return blockTranscribed;
4345 }
4346 // Handle specific things.
4347 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4348 return RewriteAtEncode(AtEncode);
4349
4350 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4351 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4352
Steve Naroffc77a6362008-12-04 16:24:46 +00004353 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4354 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4355 if (BinOp) {
4356 // Because the rewriter doesn't allow us to rewrite rewritten code,
4357 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00004358 DisableReplaceStmt = true;
4359 // Save the source range. Even if we disable the replacement, the
4360 // rewritten node will have been inserted into the tree. If the synthesized
4361 // node is at the 'end', the rewriter will fail. Consider this:
4362 // self.errorHandler = handler ? handler :
4363 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4364 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00004365 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroffb619d952008-12-09 12:56:34 +00004366 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00004367 //
4368 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4369 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4370 // to see the original expression). Consider this example:
4371 //
4372 // Foo *obj1, *obj2;
4373 //
4374 // obj1.i = [obj2 rrrr];
4375 //
4376 // 'BinOp' for the previous expression looks like:
4377 //
4378 // (BinaryOperator 0x231ccf0 'int' '='
4379 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4380 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4381 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4382 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4383 //
4384 // 'newStmt' represents the rewritten message expression. For example:
4385 //
4386 // (CallExpr 0x231d300 'id':'struct objc_object *'
4387 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4388 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4389 // (CStyleCastExpr 0x231d220 'void *'
4390 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4391 //
4392 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4393 // can be used as the setter argument. ReplaceStmt() will still 'see'
4394 // the original RHS (since we haven't altered BinOp).
4395 //
4396 // This implies the Rewrite* routines can no longer delete the original
4397 // node. As a result, we now leak the original AST nodes.
4398 //
Steve Naroffb619d952008-12-09 12:56:34 +00004399 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00004400 } else {
4401 return RewritePropertyGetter(PropRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00004402 }
4403 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004404 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4405 return RewriteAtSelector(AtSelector);
4406
4407 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4408 return RewriteObjCStringLiteral(AtString);
4409
4410 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00004411#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00004412 // Before we rewrite it, put the original message expression in a comment.
4413 SourceLocation startLoc = MessExpr->getLocStart();
4414 SourceLocation endLoc = MessExpr->getLocEnd();
4415
4416 const char *startBuf = SM->getCharacterData(startLoc);
4417 const char *endBuf = SM->getCharacterData(endLoc);
4418
4419 std::string messString;
4420 messString += "// ";
4421 messString.append(startBuf, endBuf-startBuf+1);
4422 messString += "\n";
4423
4424 // FIXME: Missing definition of
4425 // InsertText(clang::SourceLocation, char const*, unsigned int).
4426 // InsertText(startLoc, messString.c_str(), messString.size());
4427 // Tried this, but it didn't work either...
4428 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00004429#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00004430 return RewriteMessageExpr(MessExpr);
4431 }
4432
4433 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4434 return RewriteObjCTryStmt(StmtTry);
4435
4436 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4437 return RewriteObjCSynchronizedStmt(StmtTry);
4438
4439 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4440 return RewriteObjCThrowStmt(StmtThrow);
4441
4442 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4443 return RewriteObjCProtocolExpr(ProtocolExp);
4444
4445 if (ObjCForCollectionStmt *StmtForCollection =
4446 dyn_cast<ObjCForCollectionStmt>(S))
4447 return RewriteObjCForCollectionStmt(StmtForCollection,
4448 OrigStmtRange.getEnd());
4449 if (BreakStmt *StmtBreakStmt =
4450 dyn_cast<BreakStmt>(S))
4451 return RewriteBreakStmt(StmtBreakStmt);
4452 if (ContinueStmt *StmtContinueStmt =
4453 dyn_cast<ContinueStmt>(S))
4454 return RewriteContinueStmt(StmtContinueStmt);
4455
4456 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4457 // and cast exprs.
4458 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4459 // FIXME: What we're doing here is modifying the type-specifier that
4460 // precedes the first Decl. In the future the DeclGroup should have
4461 // a separate type-specifier that we can rewrite.
4462 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4463
4464 // Blocks rewrite rules.
4465 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4466 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004467 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00004468 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004469 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004470 RewriteBlockPointerDecl(ND);
4471 else if (ND->getType()->isFunctionPointerType())
4472 CheckFunctionPointerDecl(ND->getType(), ND);
4473 }
4474 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004475 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004476 RewriteBlockPointerDecl(TD);
4477 else if (TD->getUnderlyingType()->isFunctionPointerType())
4478 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4479 }
4480 }
4481 }
4482
4483 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4484 RewriteObjCQualifiedInterfaceTypes(CE);
4485
4486 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4487 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4488 assert(!Stmts.empty() && "Statement stack is empty");
4489 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4490 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4491 && "Statement stack mismatch");
4492 Stmts.pop_back();
4493 }
4494 // Handle blocks rewriting.
4495 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4496 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00004497 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00004498 }
4499 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004500 if (CE->getCallee()->getType()->isBlockPointerType()) {
4501 Stmt *BlockCall = SynthesizeBlockCall(CE);
4502 ReplaceStmt(S, BlockCall);
4503 return BlockCall;
4504 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004505 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00004506 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004507 RewriteCastExpr(CE);
4508 }
4509#if 0
4510 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00004511 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004512 // Get the new text.
4513 std::string SStr;
4514 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00004515 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00004516 const std::string &Str = Buf.str();
4517
4518 printf("CAST = %s\n", &Str[0]);
4519 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4520 delete S;
4521 return Replacement;
4522 }
4523#endif
4524 // Return this stmt unmodified.
4525 return S;
4526}
4527
4528/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4529/// main file of the input.
4530void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4531 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00004532 if (FD->isOverloadedOperator())
4533 return;
4534
Steve Narofffa15fd92008-10-28 20:29:00 +00004535 // Since function prototypes don't have ParmDecl's, we check the function
4536 // prototype. This enables us to rewrite function declarations and
4537 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00004538 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00004539
Sebastian Redld3a413d2009-04-26 20:35:05 +00004540 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00004541 if (CompoundStmt *Body = FD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004542 CurFunctionDef = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004543 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00004544 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00004545 Body =
4546 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4547 FD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00004548 CurrentBody = 0;
4549 if (PropParentMap) {
4550 delete PropParentMap;
4551 PropParentMap = 0;
4552 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004553 // This synthesizes and inserts the block "impl" struct, invoke function,
4554 // and any copy/dispose helper functions.
4555 InsertBlockLiteralsWithinFunction(FD);
4556 CurFunctionDef = 0;
4557 }
4558 return;
4559 }
4560 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00004561 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004562 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004563 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00004564 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00004565 Body =
4566 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4567 MD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00004568 CurrentBody = 0;
4569 if (PropParentMap) {
4570 delete PropParentMap;
4571 PropParentMap = 0;
4572 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004573 InsertBlockLiteralsWithinMethod(MD);
4574 CurMethodDef = 0;
4575 }
4576 }
4577 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
4578 ClassImplementation.push_back(CI);
4579 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4580 CategoryImplementation.push_back(CI);
4581 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4582 RewriteForwardClassDecl(CD);
4583 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4584 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004585 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004586 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004587 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004588 CheckFunctionPointerDecl(VD->getType(), VD);
4589 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00004590 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004591 RewriteCastExpr(CE);
4592 }
4593 }
4594 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004595 if (VD->getInit()) {
4596 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004597 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00004598 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004599 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00004600 CurrentBody = 0;
4601 if (PropParentMap) {
4602 delete PropParentMap;
4603 PropParentMap = 0;
4604 }
Douglas Gregor2e1cd422008-11-17 14:58:09 +00004605 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00004606 VD->getNameAsCString());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004607 GlobalVarDecl = 0;
4608
4609 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00004610 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004611 RewriteCastExpr(CE);
4612 }
4613 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004614 return;
4615 }
4616 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004617 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004618 RewriteBlockPointerDecl(TD);
4619 else if (TD->getUnderlyingType()->isFunctionPointerType())
4620 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4621 return;
4622 }
4623 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
4624 if (RD->isDefinition()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004625 for (RecordDecl::field_iterator i = RD->field_begin(),
4626 e = RD->field_end(); i != e; ++i) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004627 FieldDecl *FD = *i;
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004628 if (isTopLevelBlockPointerType(FD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004629 RewriteBlockPointerDecl(FD);
4630 }
4631 }
4632 return;
4633 }
4634 // Nothing yet.
4635}
4636
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00004637void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004638 // Get the top-level buffer that this corresponds to.
4639
4640 // Rewrite tabs if we care.
4641 //RewriteTabs();
4642
4643 if (Diags.hasErrorOccurred())
4644 return;
Steve Narofffa15fd92008-10-28 20:29:00 +00004645
4646 RewriteInclude();
4647
Steve Naroff621edce2009-04-29 16:37:50 +00004648 // Here's a great place to add any extra declarations that may be needed.
4649 // Write out meta data for each @protocol(<expr>).
4650 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
4651 E = ProtocolExprDecls.end(); I != E; ++I)
4652 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
4653
Chris Lattner2b2453a2009-01-17 06:22:33 +00004654 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Narofffa15fd92008-10-28 20:29:00 +00004655 Preamble.c_str(), Preamble.size(), false);
Steve Naroff0aab7962008-11-14 14:10:01 +00004656 if (ClassImplementation.size() || CategoryImplementation.size())
4657 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00004658
Steve Narofffa15fd92008-10-28 20:29:00 +00004659 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4660 // we are done.
4661 if (const RewriteBuffer *RewriteBuf =
4662 Rewrite.getRewriteBufferFor(MainFileID)) {
4663 //printf("Changed:\n");
4664 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4665 } else {
4666 fprintf(stderr, "No changes\n");
4667 }
Steve Narofface66252008-11-13 20:07:04 +00004668
Steve Naroff621edce2009-04-29 16:37:50 +00004669 if (ClassImplementation.size() || CategoryImplementation.size() ||
4670 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00004671 // Rewrite Objective-c meta data*
4672 std::string ResultStr;
4673 SynthesizeMetaDataIntoBuffer(ResultStr);
4674 // Emit metadata.
4675 *OutFile << ResultStr;
4676 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004677 OutFile->flush();
4678}
4679