blob: 86f3037326511f3d31ab400557592d1ea7a5c6ef [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"
Steve Naroff0113c9d2008-01-28 21:34:52 +000027#include "llvm/Support/CommandLine.h"
Dan Gohman63e2dcc2008-05-21 20:19:16 +000028#include "llvm/Support/Streams.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000029#include "llvm/Support/raw_ostream.h"
Chris Lattnerc68ab772008-03-22 00:08:40 +000030#include "llvm/System/Path.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000031using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000032using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000033
Chris Lattner77cd2a02007-10-11 00:43:27 +000034namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000035 class RewriteObjC : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000036 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000037 Diagnostic &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000038 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000039 unsigned RewriteFailedDiag;
Steve Naroff8c565152008-12-05 17:03:39 +000040 unsigned TryFinallyContainsReturnDiag;
41
Chris Lattner01c57482007-10-17 22:35:30 +000042 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000043 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000044 TranslationUnitDecl *TUDecl;
Chris Lattner2b2453a2009-01-17 06:22:33 +000045 FileID MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000046 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000047 SourceLocation LastIncLoc;
Steve Naroffba92b2e2008-03-27 22:29:16 +000048
Ted Kremeneka526c5c2008-01-07 19:49:32 +000049 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
50 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
51 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +000052 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000053 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
54 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000055 llvm::SmallVector<Stmt *, 32> Stmts;
56 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroff621edce2009-04-29 16:37:50 +000057 // Remember all the @protocol(<expr>) expressions.
58 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Steve Naroffebf2b562007-10-23 23:50:29 +000059
Steve Naroffd82a9ab2008-03-15 00:55:56 +000060 unsigned NumObjCStringLiterals;
61
Steve Naroffebf2b562007-10-23 23:50:29 +000062 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000063 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000064 FunctionDecl *MsgSendStretFunctionDecl;
65 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000066 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000067 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000068 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000069 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000070 FunctionDecl *CFStringFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000071 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000072
Steve Naroffbeaf2992007-11-03 11:27:19 +000073 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000074 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000075 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000076
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000077 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000078 int BcLabelCount;
79
Steve Naroff874e2322007-11-15 10:28:18 +000080 // Needed for super.
Steve Naroff54055232008-10-27 17:20:55 +000081 ObjCMethodDecl *CurMethodDef;
Steve Naroff874e2322007-11-15 10:28:18 +000082 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +000083 RecordDecl *ConstantStringDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000084
Steve Naroff621edce2009-04-29 16:37:50 +000085 TypeDecl *ProtocolTypeDecl;
86 QualType getProtocolType();
87
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +000088 // Needed for header files being rewritten
89 bool IsHeader;
90
Steve Naroffa7b402d2008-03-28 22:26:09 +000091 std::string InFileName;
Eli Friedman66d6f042009-05-18 22:20:00 +000092 llvm::raw_ostream* OutFile;
Eli Friedmanc6d656e2009-05-18 22:39:16 +000093
94 bool SilenceRewriteMacroWarning;
95
Steve Naroffba92b2e2008-03-27 22:29:16 +000096 std::string Preamble;
Steve Naroff54055232008-10-27 17:20:55 +000097
98 // Block expressions.
99 llvm::SmallVector<BlockExpr *, 32> Blocks;
100 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
101 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Steve Naroffba92b2e2008-03-27 22:29:16 +0000102
Steve Naroff54055232008-10-27 17:20:55 +0000103 // Block related declarations.
104 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
105 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
106 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
107
108 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
109
Steve Naroffc77a6362008-12-04 16:24:46 +0000110 // This maps a property to it's assignment statement.
111 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Naroff8599e7a2008-12-08 16:43:47 +0000112 // This maps a property to it's synthesied message expression.
113 // This allows us to rewrite chained getters (e.g. o.a.b.c).
114 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
115
Steve Naroff4c3580e2008-12-04 23:50:32 +0000116 // This maps an original source AST to it's rewritten form. This allows
117 // us to avoid rewriting the same node twice (which is very uncommon).
118 // This is needed to support some of the exotic property rewriting.
119 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000120
Steve Naroff54055232008-10-27 17:20:55 +0000121 FunctionDecl *CurFunctionDef;
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000122 VarDecl *GlobalVarDecl;
123
Steve Naroffb619d952008-12-09 12:56:34 +0000124 bool DisableReplaceStmt;
125
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000126 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000127 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000128 virtual void Initialize(ASTContext &context);
129
Chris Lattnerf04da132007-10-24 17:06:59 +0000130 // Top Level Driver code.
Chris Lattner682bf922009-03-29 16:50:03 +0000131 virtual void HandleTopLevelDecl(DeclGroupRef D) {
132 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
133 HandleTopLevelSingleDecl(*I);
134 }
135 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000136 void HandleDeclInMainFile(Decl *D);
Eli Friedman66d6f042009-05-18 22:20:00 +0000137 RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000138 Diagnostic &D, const LangOptions &LOpts,
139 bool silenceMacroWarn);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000140
141 ~RewriteObjC() {}
142
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000143 virtual void HandleTranslationUnit(ASTContext &C);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000144
145 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000146 Stmt *ReplacingStmt = ReplacedNodes[Old];
147
148 if (ReplacingStmt)
149 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000150
Steve Naroffb619d952008-12-09 12:56:34 +0000151 if (DisableReplaceStmt)
152 return; // Used when rewriting the assignment of a property setter.
153
Steve Naroff4c3580e2008-12-04 23:50:32 +0000154 // If replacement succeeded or warning disabled return with no warning.
155 if (!Rewrite.ReplaceStmt(Old, New)) {
156 ReplacedNodes[Old] = New;
157 return;
158 }
159 if (SilenceRewriteMacroWarning)
160 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000161 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
162 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000163 }
Steve Naroffb619d952008-12-09 12:56:34 +0000164
165 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
166 // Measaure the old text.
167 int Size = Rewrite.getRangeSize(SrcRange);
168 if (Size == -1) {
169 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
170 << Old->getSourceRange();
171 return;
172 }
173 // Get the new text.
174 std::string SStr;
175 llvm::raw_string_ostream S(SStr);
176 New->printPretty(S);
177 const std::string &Str = S.str();
178
179 // If replacement succeeded or warning disabled return with no warning.
180 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, &Str[0], Str.size())) {
181 ReplacedNodes[Old] = New;
182 return;
183 }
184 if (SilenceRewriteMacroWarning)
185 return;
186 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
187 << Old->getSourceRange();
188 }
189
Steve Naroffba92b2e2008-03-27 22:29:16 +0000190 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
191 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000192 // If insertion succeeded or warning disabled return with no warning.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000193 if (!Rewrite.InsertText(Loc, StrData, StrLen, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000194 SilenceRewriteMacroWarning)
195 return;
196
197 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
198 }
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000199
Chris Lattneraadaf782008-01-31 19:51:04 +0000200 void RemoveText(SourceLocation Loc, unsigned StrLen) {
201 // If removal succeeded or warning disabled return with no warning.
202 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
203 return;
204
205 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
206 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000207
Chris Lattneraadaf782008-01-31 19:51:04 +0000208 void ReplaceText(SourceLocation Start, unsigned OrigLength,
209 const char *NewStr, unsigned NewLength) {
210 // If removal succeeded or warning disabled return with no warning.
211 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
212 SilenceRewriteMacroWarning)
213 return;
214
215 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
216 }
217
Chris Lattnerf04da132007-10-24 17:06:59 +0000218 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000219 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000220 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000221 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000222 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffa0876e82008-12-02 17:36:43 +0000223 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
224 ObjCImplementationDecl *IMD,
225 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000226 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000227 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000228 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
229 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
230 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
231 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
232 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000233 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000234 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000235 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff4f95b752008-07-29 18:15:38 +0000236 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000237 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000238 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000239 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000240 QualType getConstantStringStructType();
Steve Naroffbaf58c32008-05-31 14:15:04 +0000241 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Chris Lattner311ff022007-10-16 22:36:42 +0000242
Chris Lattnerf04da132007-10-24 17:06:59 +0000243 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000244 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroffc77a6362008-12-04 16:24:46 +0000245 void CollectPropertySetters(Stmt *S);
246
Steve Naroff8599e7a2008-12-08 16:43:47 +0000247 Stmt *CurrentBody;
248 ParentMap *PropParentMap; // created lazily.
249
Chris Lattnere64b7772007-10-24 16:57:36 +0000250 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000251 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroffc77a6362008-12-04 16:24:46 +0000252 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Steve Naroffb619d952008-12-09 12:56:34 +0000253 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
254 SourceRange SrcRange);
Steve Naroffb42f8412007-11-05 14:50:49 +0000255 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000256 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000257 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000258 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroff8c565152008-12-05 17:03:39 +0000259 void WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000260 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000261 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000262 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
263 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
264 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000265 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
266 SourceLocation OrigEnd);
Steve Naroff934f2762007-10-24 22:48:43 +0000267 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
268 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000269 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000270 Stmt *RewriteBreakStmt(BreakStmt *S);
271 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000272 void SynthCountByEnumWithState(std::string &buf);
273
Steve Naroff09b266e2007-10-30 23:14:51 +0000274 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000275 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000276 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000277 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000278 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000279 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000280 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000281 void SynthSelGetUidFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000282 void SynthSuperContructorFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000283
Chris Lattnerf04da132007-10-24 17:06:59 +0000284 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000285 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000286 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000287
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000288 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000289 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000290
Douglas Gregor653f1b12009-04-23 01:02:12 +0000291 template<typename MethodIterator>
292 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
293 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000294 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000295 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000296 const char *ClassName,
297 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000298
Steve Naroff621edce2009-04-29 16:37:50 +0000299 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
300 const char *prefix,
301 const char *ClassName,
302 std::string &Result);
303 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
304 const char *prefix,
305 const char *ClassName,
306 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000307 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000308 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000309 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
310 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000311 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000312 void RewriteImplementations();
313 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Steve Naroff54055232008-10-27 17:20:55 +0000314
315 // Block rewriting.
Douglas Gregor72564e72009-02-26 23:50:07 +0000316 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff54055232008-10-27 17:20:55 +0000317 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
318
319 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
320 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
321
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000322 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000323 void RewriteBlockCall(CallExpr *Exp);
324 void RewriteBlockPointerDecl(NamedDecl *VD);
Steve Naroff621edce2009-04-29 16:37:50 +0000325 Stmt *RewriteBlockDeclRefExpr(BlockDeclRefExpr *VD);
Steve Naroff54055232008-10-27 17:20:55 +0000326 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
327
328 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
329 const char *funcName, std::string Tag);
330 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
331 const char *funcName, std::string Tag);
332 std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
333 bool hasCopyDisposeHelpers);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +0000334 Stmt *SynthesizeBlockCall(CallExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000335 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
336 const char *FunName);
337
338 void CollectBlockDeclRefInfo(BlockExpr *Exp);
339 void GetBlockCallExprs(Stmt *S);
340 void GetBlockDeclRefExprs(Stmt *S);
341
342 // We avoid calling Type::isBlockPointerType(), since it operates on the
343 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000344 bool isTopLevelBlockPointerType(QualType T) {
345 return isa<BlockPointerType>(T);
346 }
Steve Naroff54055232008-10-27 17:20:55 +0000347
348 // FIXME: This predicate seems like it would be useful to add to ASTContext.
349 bool isObjCType(QualType T) {
350 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
351 return false;
352
353 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
354
355 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
356 OCT == Context->getCanonicalType(Context->getObjCClassType()))
357 return true;
358
359 if (const PointerType *PT = OCT->getAsPointerType()) {
360 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
361 isa<ObjCQualifiedIdType>(PT->getPointeeType()))
362 return true;
363 }
364 return false;
365 }
366 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000367 void GetExtentOfArgList(const char *Name, const char *&LParen,
368 const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000369 void RewriteCastExpr(CStyleCastExpr *CE);
Steve Narofffa15fd92008-10-28 20:29:00 +0000370
371 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000372 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Steve Naroff621edce2009-04-29 16:37:50 +0000373
374 void QuoteDoublequotes(std::string &From, std::string &To) {
375 for(unsigned i = 0; i < From.length(); i++) {
376 if (From[i] == '"')
377 To += "\\\"";
378 else
379 To += From[i];
380 }
381 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000382 };
383}
384
Douglas Gregor72564e72009-02-26 23:50:07 +0000385void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
Steve Naroff54055232008-10-27 17:20:55 +0000386 NamedDecl *D) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000387 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
388 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000389 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000390 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000391 // All the args are checked/rewritten. Don't call twice!
392 RewriteBlockPointerDecl(D);
393 break;
394 }
395 }
396}
397
398void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
399 const PointerType *PT = funcType->getAsPointerType();
400 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000401 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000402}
403
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000404static bool IsHeaderFile(const std::string &Filename) {
405 std::string::size_type DotPos = Filename.rfind('.');
406
407 if (DotPos == std::string::npos) {
408 // no file extension
409 return false;
410 }
411
412 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
413 // C header: .h
414 // C++ header: .hh or .H;
415 return Ext == "h" || Ext == "hh" || Ext == "H";
416}
417
Eli Friedman66d6f042009-05-18 22:20:00 +0000418RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000419 Diagnostic &D, const LangOptions &LOpts,
420 bool silenceMacroWarn)
421 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
422 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000423 IsHeader = IsHeaderFile(inFile);
Steve Naroffa7b402d2008-03-28 22:26:09 +0000424 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
425 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff8c565152008-12-05 17:03:39 +0000426 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000427 "rewriter doesn't support user-specified control flow semantics "
428 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000429}
430
Eli Friedmanbce831b2009-05-18 22:29:17 +0000431ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
432 llvm::raw_ostream* OS,
433 Diagnostic &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000434 const LangOptions &LOpts,
435 bool SilenceRewriteMacroWarning) {
436 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000437}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000438
Steve Naroffb29b4272008-04-14 22:03:09 +0000439void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000440 Context = &context;
441 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000442 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000443 MsgSendFunctionDecl = 0;
444 MsgSendSuperFunctionDecl = 0;
445 MsgSendStretFunctionDecl = 0;
446 MsgSendSuperStretFunctionDecl = 0;
447 MsgSendFpretFunctionDecl = 0;
448 GetClassFunctionDecl = 0;
449 GetMetaClassFunctionDecl = 0;
450 SelGetUidFunctionDecl = 0;
451 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000452 ConstantStringClassReference = 0;
453 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000454 CurMethodDef = 0;
455 CurFunctionDef = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000456 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000457 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000458 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000459 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000460 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000461 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000462 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000463 PropParentMap = 0;
464 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000465 DisableReplaceStmt = false;
466
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000467 // Get the ID and start/end of the main file.
468 MainFileID = SM->getMainFileID();
469 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
470 MainFileStart = MainBuf->getBufferStart();
471 MainFileEnd = MainBuf->getBufferEnd();
Steve Naroffba92b2e2008-03-27 22:29:16 +0000472
Chris Lattner2c78b872009-04-14 23:22:57 +0000473 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000474
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000475 // declaring objc_selector outside the parameter list removes a silly
476 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000477 if (IsHeader)
Steve Naroff62c26322009-02-03 20:39:18 +0000478 Preamble = "#pragma once\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000479 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff46a98a72008-12-23 20:11:22 +0000480 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000481 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000482 if (LangOpts.Microsoft) {
483 // Add a constructor for creating temporary objects.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000484 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
485 ": ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000486 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000487 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000488 Preamble += "};\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000489 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
490 Preamble += "typedef struct objc_object Protocol;\n";
491 Preamble += "#define _REWRITER_typedef_Protocol\n";
492 Preamble += "#endif\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000493 if (LangOpts.Microsoft) {
494 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
495 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
496 } else
497 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
498 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000499 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000500 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000501 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000502 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000503 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000504 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000505 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000506 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000507 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000508 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000509 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000510 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000511 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000512 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
513 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
514 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
515 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
516 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000517 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000518 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000519 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
520 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
521 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000522 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
523 Preamble += "struct __objcFastEnumerationState {\n\t";
524 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000525 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000526 Preamble += "unsigned long *mutationsPtr;\n\t";
527 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000528 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000529 Preamble += "#define __FASTENUMERATIONSTATE\n";
530 Preamble += "#endif\n";
531 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
532 Preamble += "struct __NSConstantStringImpl {\n";
533 Preamble += " int *isa;\n";
534 Preamble += " int flags;\n";
535 Preamble += " char *str;\n";
536 Preamble += " long length;\n";
537 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000538 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
539 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
540 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000541 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000542 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000543 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
544 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000545 // Blocks preamble.
546 Preamble += "#ifndef BLOCK_IMPL\n";
547 Preamble += "#define BLOCK_IMPL\n";
548 Preamble += "struct __block_impl {\n";
549 Preamble += " void *isa;\n";
550 Preamble += " int Flags;\n";
551 Preamble += " int Size;\n";
552 Preamble += " void *FuncPtr;\n";
553 Preamble += "};\n";
Steve Naroff5bc60d02008-12-16 15:50:30 +0000554 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
555 Preamble += "__OBJC_RW_STATICIMPORT void _Block_object_assign(void *, const void *, const int);\n";
556 Preamble += "__OBJC_RW_STATICIMPORT void _Block_object_dispose(const void *, const int);\n";
557 Preamble += "__OBJC_RW_STATICIMPORT void *_NSConcreteGlobalBlock[32];\n";
558 Preamble += "__OBJC_RW_STATICIMPORT void *_NSConcreteStackBlock[32];\n";
Steve Naroff54055232008-10-27 17:20:55 +0000559 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000560 if (LangOpts.Microsoft) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000561 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
562 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000563 Preamble += "#define __attribute__(X)\n";
564 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000565}
566
567
Chris Lattnerf04da132007-10-24 17:06:59 +0000568//===----------------------------------------------------------------------===//
569// Top Level Driver Code
570//===----------------------------------------------------------------------===//
571
Chris Lattner682bf922009-03-29 16:50:03 +0000572void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000573 // Two cases: either the decl could be in the main file, or it could be in a
574 // #included file. If the former, rewrite it now. If the later, check to see
575 // if we rewrote the #include/#import.
576 SourceLocation Loc = D->getLocation();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000577 Loc = SM->getInstantiationLoc(Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000578
579 // If this is for a builtin, ignore it.
580 if (Loc.isInvalid()) return;
581
Steve Naroffebf2b562007-10-23 23:50:29 +0000582 // Look for built-in declarations that we need to refer during the rewrite.
583 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000584 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000585 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000586 // declared in <Foundation/NSString.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +0000587 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000588 ConstantStringClassReference = FVD;
589 return;
590 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000591 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000592 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000593 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000594 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000595 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000596 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000597 } else if (ObjCForwardProtocolDecl *FP =
598 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000599 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000600 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
601 // Recurse into linkage specifications
Douglas Gregor6ab35242009-04-09 21:40:53 +0000602 for (DeclContext::decl_iterator DI = LSD->decls_begin(*Context),
603 DIEnd = LSD->decls_end(*Context);
Douglas Gregord0434102009-01-09 00:49:46 +0000604 DI != DIEnd; ++DI)
Chris Lattner682bf922009-03-29 16:50:03 +0000605 HandleTopLevelSingleDecl(*DI);
Steve Naroffebf2b562007-10-23 23:50:29 +0000606 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000607 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000608 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000609 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000610}
611
Chris Lattnerf04da132007-10-24 17:06:59 +0000612//===----------------------------------------------------------------------===//
613// Syntactic (non-AST) Rewriting Code
614//===----------------------------------------------------------------------===//
615
Steve Naroffb29b4272008-04-14 22:03:09 +0000616void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000617 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000618 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
619 const char *MainBufStart = MainBuf.first;
620 const char *MainBufEnd = MainBuf.second;
621 size_t ImportLen = strlen("import");
622 size_t IncludeLen = strlen("include");
623
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000624 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000625 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
626 if (*BufPtr == '#') {
627 if (++BufPtr == MainBufEnd)
628 return;
629 while (*BufPtr == ' ' || *BufPtr == '\t')
630 if (++BufPtr == MainBufEnd)
631 return;
632 if (!strncmp(BufPtr, "import", ImportLen)) {
633 // replace import with include
634 SourceLocation ImportLoc =
635 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000636 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000637 BufPtr += ImportLen;
638 }
639 }
640 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000641}
642
Steve Naroffb29b4272008-04-14 22:03:09 +0000643void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000644 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
645 const char *MainBufStart = MainBuf.first;
646 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000647
Chris Lattnerf04da132007-10-24 17:06:59 +0000648 // Loop over the whole file, looking for tabs.
649 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
650 if (*BufPtr != '\t')
651 continue;
652
653 // Okay, we found a tab. This tab will turn into at least one character,
654 // but it depends on which 'virtual column' it is in. Compute that now.
655 unsigned VCol = 0;
656 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
657 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
658 ++VCol;
659
660 // Okay, now that we know the virtual column, we know how many spaces to
661 // insert. We assume 8-character tab-stops.
662 unsigned Spaces = 8-(VCol & 7);
663
664 // Get the location of the tab.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000665 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
666 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattnerf04da132007-10-24 17:06:59 +0000667
668 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000669 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000670 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000671}
672
Steve Naroffeb0646c2008-12-02 15:48:25 +0000673static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
674 ObjCIvarDecl *OID) {
675 std::string S;
676 S = "((struct ";
677 S += ClassDecl->getIdentifier()->getName();
678 S += "_IMPL *)self)->";
679 S += OID->getNameAsCString();
680 return S;
681}
682
Steve Naroffa0876e82008-12-02 17:36:43 +0000683void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
684 ObjCImplementationDecl *IMD,
685 ObjCCategoryImplDecl *CID) {
Steve Naroffd40910b2008-12-01 20:33:01 +0000686 SourceLocation startLoc = PID->getLocStart();
687 InsertText(startLoc, "// ", 3);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000688 const char *startBuf = SM->getCharacterData(startLoc);
689 assert((*startBuf == '@') && "bogus @synthesize location");
690 const char *semiBuf = strchr(startBuf, ';');
691 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000692 SourceLocation onePastSemiLoc =
693 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000694
695 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
696 return; // FIXME: is this correct?
697
698 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000699 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000700 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000701 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000702
703 if (!OID)
704 return;
705
706 std::string Getr;
707 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
708 Getr += "{ ";
709 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroff3539cdb2008-12-02 17:54:50 +0000710 // FIXME: deal with code generation implications for various property
711 // attributes (copy, retain, nonatomic).
712 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000713 Getr += "return " + getIvarAccessString(ClassDecl, OID);
714 Getr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000715 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroffeb0646c2008-12-02 15:48:25 +0000716 if (PD->isReadOnly())
717 return;
718
719 // Generate the 'setter' function.
720 std::string Setr;
721 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000722 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000723 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff3539cdb2008-12-02 17:54:50 +0000724 // FIXME: deal with code generation implications for various property
725 // attributes (copy, retain, nonatomic).
Steve Naroff15f081d2008-12-03 00:56:33 +0000726 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000727 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Steve Narofff4312dc2008-12-11 19:29:16 +0000728 Setr += PD->getNameAsCString();
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000729 Setr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000730 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffd40910b2008-12-01 20:33:01 +0000731}
Chris Lattner8a12c272007-10-11 18:38:32 +0000732
Steve Naroffb29b4272008-04-14 22:03:09 +0000733void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000734 // Get the start location and compute the semi location.
735 SourceLocation startLoc = ClassDecl->getLocation();
736 const char *startBuf = SM->getCharacterData(startLoc);
737 const char *semiPtr = strchr(startBuf, ';');
738
739 // Translate to typedef's that forward reference structs with the same name
740 // as the class. As a convenience, we include the original declaration
741 // as a comment.
742 std::string typedefString;
743 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000744 typedefString.append(startBuf, semiPtr-startBuf+1);
745 typedefString += "\n";
Chris Lattner67956052009-02-20 18:04:31 +0000746 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
747 I != E; ++I) {
748 ObjCInterfaceDecl *ForwardDecl = *I;
Steve Naroff32174822007-11-09 12:50:28 +0000749 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000750 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000751 typedefString += "\n";
752 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000753 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000754 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000755 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000756 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000757 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000758 }
759
760 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000761 ReplaceText(startLoc, semiPtr-startBuf+1,
762 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000763}
764
Steve Naroffb29b4272008-04-14 22:03:09 +0000765void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000766 SourceLocation LocStart = Method->getLocStart();
767 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000768
Chris Lattner30fc9332009-02-04 01:06:56 +0000769 if (SM->getInstantiationLineNumber(LocEnd) >
770 SM->getInstantiationLineNumber(LocStart)) {
Steve Naroff94ac21e2008-10-21 13:37:27 +0000771 InsertText(LocStart, "#if 0\n", 6);
772 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000773 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000774 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000775 }
776}
777
Steve Naroff6327e0d2009-01-11 01:06:09 +0000778void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000779{
Steve Naroff6327e0d2009-01-11 01:06:09 +0000780 SourceLocation Loc = prop->getLocation();
781
782 ReplaceText(Loc, 0, "// ", 3);
783
784 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000785}
786
Steve Naroffb29b4272008-04-14 22:03:09 +0000787void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000788 SourceLocation LocStart = CatDecl->getLocStart();
789
790 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000791 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000792
Douglas Gregor6ab35242009-04-09 21:40:53 +0000793 for (ObjCCategoryDecl::instmeth_iterator
794 I = CatDecl->instmeth_begin(*Context),
795 E = CatDecl->instmeth_end(*Context);
796 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000797 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000798 for (ObjCCategoryDecl::classmeth_iterator
799 I = CatDecl->classmeth_begin(*Context),
800 E = CatDecl->classmeth_end(*Context);
801 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000802 RewriteMethodDeclaration(*I);
803
Steve Naroff423cb562007-10-30 13:30:57 +0000804 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000805 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000806}
807
Steve Naroffb29b4272008-04-14 22:03:09 +0000808void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000809 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000810
Steve Naroff752d6ef2007-10-30 16:42:30 +0000811 SourceLocation LocStart = PDecl->getLocStart();
812
813 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000814 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000815
Douglas Gregor6ab35242009-04-09 21:40:53 +0000816 for (ObjCProtocolDecl::instmeth_iterator
817 I = PDecl->instmeth_begin(*Context),
818 E = PDecl->instmeth_end(*Context);
819 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000820 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000821 for (ObjCProtocolDecl::classmeth_iterator
822 I = PDecl->classmeth_begin(*Context),
823 E = PDecl->classmeth_end(*Context);
824 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000825 RewriteMethodDeclaration(*I);
826
Steve Naroff752d6ef2007-10-30 16:42:30 +0000827 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000828 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000829 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000830
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000831 // Must comment out @optional/@required
832 const char *startBuf = SM->getCharacterData(LocStart);
833 const char *endBuf = SM->getCharacterData(LocEnd);
834 for (const char *p = startBuf; p < endBuf; p++) {
835 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
836 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000837 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000838 ReplaceText(OptionalLoc, strlen("@optional"),
839 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000840
841 }
842 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
843 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000844 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000845 ReplaceText(OptionalLoc, strlen("@required"),
846 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000847
848 }
849 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000850}
851
Steve Naroffb29b4272008-04-14 22:03:09 +0000852void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000853 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000854 if (LocStart.isInvalid())
855 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000856 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000857 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000858}
859
Steve Naroffb29b4272008-04-14 22:03:09 +0000860void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000861 std::string &ResultStr) {
Steve Naroffced80a82008-10-30 12:09:33 +0000862 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroff76e429d2008-07-16 14:40:40 +0000863 const FunctionType *FPRetType = 0;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000864 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000865 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000866 ResultStr += "id";
Steve Narofff4312dc2008-12-11 19:29:16 +0000867 else if (OMD->getResultType()->isFunctionPointerType() ||
868 OMD->getResultType()->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +0000869 // needs special handling, since pointer-to-functions have special
870 // syntax (where a decaration models use).
871 QualType retType = OMD->getResultType();
Steve Narofff4312dc2008-12-11 19:29:16 +0000872 QualType PointeeTy;
873 if (const PointerType* PT = retType->getAsPointerType())
874 PointeeTy = PT->getPointeeType();
875 else if (const BlockPointerType *BPT = retType->getAsBlockPointerType())
876 PointeeTy = BPT->getPointeeType();
877 if ((FPRetType = PointeeTy->getAsFunctionType())) {
878 ResultStr += FPRetType->getResultType().getAsString();
879 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +0000880 }
881 } else
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000882 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000883 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000884
885 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000886 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000887
Douglas Gregorf8d49f62009-01-09 17:18:27 +0000888 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000889 NameStr += "_I_";
890 else
891 NameStr += "_C_";
892
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000893 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000894 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000895
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000896 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +0000897 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000898 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000899 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000900 }
Steve Naroff563b8282008-04-04 22:23:44 +0000901 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +0000902 {
903 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000904 int len = selString.size();
905 for (int i = 0; i < len; i++)
906 if (selString[i] == ':')
907 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000908 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000909 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000910 // Remember this name for metadata emission
911 MethodInternalNames[OMD] = NameStr;
912 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000913
914 // Rewrite arguments
915 ResultStr += "(";
916
917 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +0000918 if (OMD->isInstanceMethod()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000919 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000920 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000921 if (!LangOpts.Microsoft) {
922 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
923 ResultStr += "struct ";
924 }
925 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000926 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000927 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000928 }
929 else
Steve Naroff621edce2009-04-29 16:37:50 +0000930 ResultStr += Context->getObjCClassType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000931
932 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000933 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000934 ResultStr += " _cmd";
935
936 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +0000937 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
938 E = OMD->param_end(); PI != E; ++PI) {
939 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000940 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +0000941 if (PDecl->getType()->isObjCQualifiedIdType()) {
942 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000943 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +0000944 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000945 std::string Name = PDecl->getNameAsString();
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000946 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroffc8ad87b2008-10-30 14:45:29 +0000947 // Make sure we convert "t (^)(...)" to "t (*)(...)".
948 const BlockPointerType *BPT = PDecl->getType()->getAsBlockPointerType();
949 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name);
950 } else
951 PDecl->getType().getAsStringInternal(Name);
Steve Naroff543409e2008-04-18 21:13:19 +0000952 ResultStr += Name;
953 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000954 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000955 if (OMD->isVariadic())
956 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000957 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000958
Steve Naroff76e429d2008-07-16 14:40:40 +0000959 if (FPRetType) {
960 ResultStr += ")"; // close the precedence "scope" for "*".
961
962 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +0000963 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +0000964 ResultStr += "(";
965 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
966 if (i) ResultStr += ", ";
967 std::string ParamStr = FT->getArgType(i).getAsString();
968 ResultStr += ParamStr;
969 }
970 if (FT->isVariadic()) {
971 if (FT->getNumArgs()) ResultStr += ", ";
972 ResultStr += "...";
973 }
974 ResultStr += ")";
975 } else {
976 ResultStr += "()";
977 }
978 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000979}
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000980void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000981 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
982 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000983
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000984 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000985 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000986 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000987 InsertText(CID->getLocStart(), "// ", 3);
Steve Narofface66252008-11-13 20:07:04 +0000988
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000989 for (ObjCCategoryImplDecl::instmeth_iterator
Douglas Gregor653f1b12009-04-23 01:02:12 +0000990 I = IMD ? IMD->instmeth_begin(*Context) : CID->instmeth_begin(*Context),
991 E = IMD ? IMD->instmeth_end(*Context) : CID->instmeth_end(*Context);
992 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000993 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000994 ObjCMethodDecl *OMD = *I;
995 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000996 SourceLocation LocStart = OMD->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +0000997 SourceLocation LocEnd = OMD->getCompoundBody(*Context)->getLocStart();
998
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000999 const char *startBuf = SM->getCharacterData(LocStart);
1000 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +00001001 ReplaceText(LocStart, endBuf-startBuf,
1002 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001003 }
1004
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001005 for (ObjCCategoryImplDecl::classmeth_iterator
Douglas Gregor653f1b12009-04-23 01:02:12 +00001006 I = IMD ? IMD->classmeth_begin(*Context) : CID->classmeth_begin(*Context),
1007 E = IMD ? IMD->classmeth_end(*Context) : CID->classmeth_end(*Context);
1008 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001009 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001010 ObjCMethodDecl *OMD = *I;
1011 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001012 SourceLocation LocStart = OMD->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001013 SourceLocation LocEnd = OMD->getCompoundBody(*Context)->getLocStart();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001014
1015 const char *startBuf = SM->getCharacterData(LocStart);
1016 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +00001017 ReplaceText(LocStart, endBuf-startBuf,
1018 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001019 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001020 for (ObjCCategoryImplDecl::propimpl_iterator
Douglas Gregor653f1b12009-04-23 01:02:12 +00001021 I = IMD ? IMD->propimpl_begin(*Context) : CID->propimpl_begin(*Context),
1022 E = IMD ? IMD->propimpl_end(*Context) : CID->propimpl_end(*Context);
1023 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001024 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001025 }
1026
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001027 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001028 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001029 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001030 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001031}
1032
Steve Naroffb29b4272008-04-14 22:03:09 +00001033void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001034 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001035 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001036 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001037 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001038 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001039 ResultStr += "\n";
1040 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001041 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001042 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001043 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001044 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001045 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001046 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001047 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001048 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001049 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +00001050
Douglas Gregor6ab35242009-04-09 21:40:53 +00001051 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(*Context),
1052 E = ClassDecl->prop_end(*Context); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001053 RewriteProperty(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001054 for (ObjCInterfaceDecl::instmeth_iterator
1055 I = ClassDecl->instmeth_begin(*Context),
1056 E = ClassDecl->instmeth_end(*Context);
1057 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001058 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001059 for (ObjCInterfaceDecl::classmeth_iterator
1060 I = ClassDecl->classmeth_begin(*Context),
1061 E = ClassDecl->classmeth_end(*Context);
1062 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001063 RewriteMethodDeclaration(*I);
1064
Steve Naroff2feac5e2007-10-30 03:43:13 +00001065 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +00001066 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +00001067}
1068
Steve Naroffb619d952008-12-09 12:56:34 +00001069Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1070 SourceRange SrcRange) {
Steve Naroffc77a6362008-12-04 16:24:46 +00001071 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1072 // This allows us to reuse all the fun and games in SynthMessageExpr().
1073 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1074 ObjCMessageExpr *MsgExpr;
1075 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1076 llvm::SmallVector<Expr *, 1> ExprVec;
1077 ExprVec.push_back(newStmt);
1078
Steve Naroff8599e7a2008-12-08 16:43:47 +00001079 Stmt *Receiver = PropRefExpr->getBase();
1080 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1081 if (PRE && PropGetters[PRE]) {
1082 // This allows us to handle chain/nested property getters.
1083 Receiver = PropGetters[PRE];
1084 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00001085 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
Steve Naroffc77a6362008-12-04 16:24:46 +00001086 PDecl->getSetterName(), PDecl->getType(),
1087 PDecl->getSetterMethodDecl(),
1088 SourceLocation(), SourceLocation(),
1089 &ExprVec[0], 1);
1090 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
1091
1092 // Now do the actual rewrite.
Steve Naroffb619d952008-12-09 12:56:34 +00001093 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffe58ee0c2008-12-10 14:53:27 +00001094 //delete BinOp;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001095 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1096 // to things that stay around.
1097 Context->Deallocate(MsgExpr);
Steve Naroffc77a6362008-12-04 16:24:46 +00001098 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001099}
1100
Steve Naroffc77a6362008-12-04 16:24:46 +00001101Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Naroff15f081d2008-12-03 00:56:33 +00001102 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1103 // This allows us to reuse all the fun and games in SynthMessageExpr().
1104 ObjCMessageExpr *MsgExpr;
1105 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1106
Steve Naroff8599e7a2008-12-08 16:43:47 +00001107 Stmt *Receiver = PropRefExpr->getBase();
1108
1109 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1110 if (PRE && PropGetters[PRE]) {
1111 // This allows us to handle chain/nested property getters.
1112 Receiver = PropGetters[PRE];
1113 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00001114 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
Steve Naroff15f081d2008-12-03 00:56:33 +00001115 PDecl->getGetterName(), PDecl->getType(),
1116 PDecl->getGetterMethodDecl(),
1117 SourceLocation(), SourceLocation(),
1118 0, 0);
1119
Steve Naroff4c3580e2008-12-04 23:50:32 +00001120 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001121
1122 if (!PropParentMap)
1123 PropParentMap = new ParentMap(CurrentBody);
1124
1125 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1126 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1127 // We stash away the ReplacingStmt since actually doing the
1128 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1129 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001130 // 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 PropRefExpr; // return the original...
1134 } else {
1135 ReplaceStmt(PropRefExpr, ReplacingStmt);
Ted Kremenek8189cde2009-02-07 01:47:29 +00001136 // delete PropRefExpr; elsewhere...
1137 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1138 // to things that stay around.
1139 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001140 return ReplacingStmt;
1141 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001142}
1143
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001144Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
1145 SourceLocation OrigStart) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001146 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff54055232008-10-27 17:20:55 +00001147 if (CurMethodDef) {
Steve Naroff05b8c782008-03-12 00:25:36 +00001148 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001149 ObjCInterfaceType *iFaceDecl =
1150 dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Narofff0757612008-05-08 17:52:16 +00001151 // lookup which class implements the instance variable.
1152 ObjCInterfaceDecl *clsDeclared = 0;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001153 iFaceDecl->getDecl()->lookupInstanceVariable(*Context,
1154 D->getIdentifier(),
1155 clsDeclared);
Steve Narofff0757612008-05-08 17:52:16 +00001156 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1157
1158 // Synthesize an explicit cast to gain access to the ivar.
1159 std::string RecName = clsDeclared->getIdentifier()->getName();
1160 RecName += "_IMPL";
1161 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001162 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001163 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001164 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1165 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Ted Kremenek8189cde2009-02-07 01:47:29 +00001166 CastExpr *castExpr = new (Context) CStyleCastExpr(castT, IV->getBase(),
1167 castT,SourceLocation(),
1168 SourceLocation());
Steve Narofff0757612008-05-08 17:52:16 +00001169 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001170 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1171 IV->getBase()->getLocEnd(),
1172 castExpr);
Steve Narofff0757612008-05-08 17:52:16 +00001173 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001174 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001175 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1176 IV->getLocation(),
1177 D->getType());
Steve Narofff0757612008-05-08 17:52:16 +00001178 ReplaceStmt(IV, ME);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001179 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001180 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001181 }
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001182
1183 ReplaceStmt(IV->getBase(), PE);
1184 // Cannot delete IV->getBase(), since PE points to it.
1185 // Replace the old base with the cast. This is important when doing
1186 // embedded rewrites. For example, [newInv->_container addObject:0].
1187 IV->setBase(PE);
1188 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001189 }
Steve Naroff84472a82008-04-18 21:55:08 +00001190 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001191 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
1192
1193 // Explicit ivar refs need to have a cast inserted.
1194 // FIXME: consider sharing some of this code with the code above.
1195 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +00001196 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001197 // lookup which class implements the instance variable.
1198 ObjCInterfaceDecl *clsDeclared = 0;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001199 iFaceDecl->getDecl()->lookupInstanceVariable(*Context,
1200 D->getIdentifier(),
1201 clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001202 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1203
1204 // Synthesize an explicit cast to gain access to the ivar.
1205 std::string RecName = clsDeclared->getIdentifier()->getName();
1206 RecName += "_IMPL";
1207 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001208 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001209 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001210 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1211 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Ted Kremenek8189cde2009-02-07 01:47:29 +00001212 CastExpr *castExpr = new (Context) CStyleCastExpr(castT, IV->getBase(),
1213 castT, SourceLocation(),
1214 SourceLocation());
Steve Naroff9f525972008-05-06 23:20:07 +00001215 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001216 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner8d366162008-05-28 16:38:23 +00001217 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +00001218 ReplaceStmt(IV->getBase(), PE);
1219 // Cannot delete IV->getBase(), since PE points to it.
1220 // Replace the old base with the cast. This is important when doing
1221 // embedded rewrites. For example, [newInv->_container addObject:0].
1222 IV->setBase(PE);
1223 return IV;
1224 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001225 }
Steve Naroff84472a82008-04-18 21:55:08 +00001226 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001227}
1228
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001229/// SynthCountByEnumWithState - To print:
1230/// ((unsigned int (*)
1231/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1232/// (void *)objc_msgSend)((id)l_collection,
1233/// sel_registerName(
1234/// "countByEnumeratingWithState:objects:count:"),
1235/// &enumState,
1236/// (id *)items, (unsigned int)16)
1237///
Steve Naroffb29b4272008-04-14 22:03:09 +00001238void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001239 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1240 "id *, unsigned int))(void *)objc_msgSend)";
1241 buf += "\n\t\t";
1242 buf += "((id)l_collection,\n\t\t";
1243 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1244 buf += "\n\t\t";
1245 buf += "&enumState, "
1246 "(id *)items, (unsigned int)16)";
1247}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001248
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001249/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1250/// statement to exit to its outer synthesized loop.
1251///
Steve Naroffb29b4272008-04-14 22:03:09 +00001252Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001253 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1254 return S;
1255 // replace break with goto __break_label
1256 std::string buf;
1257
1258 SourceLocation startLoc = S->getLocStart();
1259 buf = "goto __break_label_";
1260 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001261 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001262
1263 return 0;
1264}
1265
1266/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1267/// statement to continue with its inner synthesized loop.
1268///
Steve Naroffb29b4272008-04-14 22:03:09 +00001269Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001270 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1271 return S;
1272 // replace continue with goto __continue_label
1273 std::string buf;
1274
1275 SourceLocation startLoc = S->getLocStart();
1276 buf = "goto __continue_label_";
1277 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001278 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001279
1280 return 0;
1281}
1282
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001283/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001284/// It rewrites:
1285/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001286
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001287/// Into:
1288/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001289/// type elem;
1290/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001291/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001292/// id l_collection = (id)collection;
1293/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1294/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001295/// if (limit) {
1296/// unsigned long startMutations = *enumState.mutationsPtr;
1297/// do {
1298/// unsigned long counter = 0;
1299/// do {
1300/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001301/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001302/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001303/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001304/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001305/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001306/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1307/// objects:items count:16]);
1308/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001309/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001310/// }
1311/// else
1312/// elem = nil;
1313/// }
1314///
Steve Naroffb29b4272008-04-14 22:03:09 +00001315Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001316 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001317 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1318 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1319 "ObjCForCollectionStmt Statement stack mismatch");
1320 assert(!ObjCBcLabelNo.empty() &&
1321 "ObjCForCollectionStmt - Label No stack empty");
1322
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001323 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001324 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001325 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001326 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001327 std::string buf;
1328 buf = "\n{\n\t";
1329 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1330 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001331 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001332 QualType ElementType = cast<ValueDecl>(D)->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001333 elementTypeAsString = ElementType.getAsString();
1334 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001335 buf += " ";
Chris Lattner8ec03f52008-11-24 03:54:41 +00001336 elementName = D->getNameAsCString();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001337 buf += elementName;
1338 buf += ";\n\t";
1339 }
Chris Lattner06767512008-04-08 05:52:18 +00001340 else {
1341 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001342 elementName = DR->getDecl()->getNameAsCString();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001343 elementTypeAsString
1344 = cast<ValueDecl>(DR->getDecl())->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001345 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001346
1347 // struct __objcFastEnumerationState enumState = { 0 };
1348 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1349 // id items[16];
1350 buf += "id items[16];\n\t";
1351 // id l_collection = (id)
1352 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001353 // Find start location of 'collection' the hard way!
1354 const char *startCollectionBuf = startBuf;
1355 startCollectionBuf += 3; // skip 'for'
1356 startCollectionBuf = strchr(startCollectionBuf, '(');
1357 startCollectionBuf++; // skip '('
1358 // find 'in' and skip it.
1359 while (*startCollectionBuf != ' ' ||
1360 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1361 (*(startCollectionBuf+3) != ' ' &&
1362 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1363 startCollectionBuf++;
1364 startCollectionBuf += 3;
1365
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001366 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001367 ReplaceText(startLoc, startCollectionBuf - startBuf,
1368 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001369 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001370 SourceLocation rightParenLoc = S->getRParenLoc();
1371 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1372 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001373 buf = ";\n\t";
1374
1375 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1376 // objects:items count:16];
1377 // which is synthesized into:
1378 // unsigned int limit =
1379 // ((unsigned int (*)
1380 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1381 // (void *)objc_msgSend)((id)l_collection,
1382 // sel_registerName(
1383 // "countByEnumeratingWithState:objects:count:"),
1384 // (struct __objcFastEnumerationState *)&state,
1385 // (id *)items, (unsigned int)16);
1386 buf += "unsigned long limit =\n\t\t";
1387 SynthCountByEnumWithState(buf);
1388 buf += ";\n\t";
1389 /// if (limit) {
1390 /// unsigned long startMutations = *enumState.mutationsPtr;
1391 /// do {
1392 /// unsigned long counter = 0;
1393 /// do {
1394 /// if (startMutations != *enumState.mutationsPtr)
1395 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001396 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001397 buf += "if (limit) {\n\t";
1398 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1399 buf += "do {\n\t\t";
1400 buf += "unsigned long counter = 0;\n\t\t";
1401 buf += "do {\n\t\t\t";
1402 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1403 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1404 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001405 buf += " = (";
1406 buf += elementTypeAsString;
1407 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001408 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001409 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001410
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001411 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001412 /// } while (counter < limit);
1413 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1414 /// objects:items count:16]);
1415 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001416 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001417 /// }
1418 /// else
1419 /// elem = nil;
1420 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001421 ///
1422 buf = ";\n\t";
1423 buf += "__continue_label_";
1424 buf += utostr(ObjCBcLabelNo.back());
1425 buf += ": ;";
1426 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001427 buf += "} while (counter < limit);\n\t";
1428 buf += "} while (limit = ";
1429 SynthCountByEnumWithState(buf);
1430 buf += ");\n\t";
1431 buf += elementName;
Steve Naroff5605fdf2008-12-17 14:24:39 +00001432 buf += " = ((id)0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001433 buf += "__break_label_";
1434 buf += utostr(ObjCBcLabelNo.back());
1435 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001436 buf += "}\n\t";
1437 buf += "else\n\t\t";
1438 buf += elementName;
Steve Naroff5605fdf2008-12-17 14:24:39 +00001439 buf += " = ((id)0);\n";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001440 buf += "}\n";
Steve Naroff600e4e82008-07-21 18:26:02 +00001441
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001442 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001443 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001444 if (isa<CompoundStmt>(S->getBody())) {
1445 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1446 InsertText(endBodyLoc, buf.c_str(), buf.size());
1447 } else {
1448 /* Need to treat single statements specially. For example:
1449 *
1450 * for (A *a in b) if (stuff()) break;
1451 * for (A *a in b) xxxyy;
1452 *
1453 * The following code simply scans ahead to the semi to find the actual end.
1454 */
1455 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1456 const char *semiBuf = strchr(stmtBuf, ';');
1457 assert(semiBuf && "Can't find ';'");
1458 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1459 InsertText(endBodyLoc, buf.c_str(), buf.size());
1460 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001461 Stmts.pop_back();
1462 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001463 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001464}
1465
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001466/// RewriteObjCSynchronizedStmt -
1467/// This routine rewrites @synchronized(expr) stmt;
1468/// into:
1469/// objc_sync_enter(expr);
1470/// @try stmt @finally { objc_sync_exit(expr); }
1471///
Steve Naroffb29b4272008-04-14 22:03:09 +00001472Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001473 // Get the start location and compute the semi location.
1474 SourceLocation startLoc = S->getLocStart();
1475 const char *startBuf = SM->getCharacterData(startLoc);
1476
1477 assert((*startBuf == '@') && "bogus @synchronized location");
1478
1479 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001480 buf = "objc_sync_enter((id)";
1481 const char *lparenBuf = startBuf;
1482 while (*lparenBuf != '(') lparenBuf++;
1483 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Steve Naroffc7089f12008-08-19 13:04:19 +00001484 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1485 // the sync expression is typically a message expression that's already
1486 // been rewritten! (which implies the SourceLocation's are invalid).
1487 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001488 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001489 while (*endBuf != ')') endBuf--;
1490 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001491 buf = ");\n";
1492 // declare a new scope with two variables, _stack and _rethrow.
1493 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1494 buf += "int buf[18/*32-bit i386*/];\n";
1495 buf += "char *pointers[4];} _stack;\n";
1496 buf += "id volatile _rethrow = 0;\n";
1497 buf += "objc_exception_try_enter(&_stack);\n";
1498 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001499 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001500 startLoc = S->getSynchBody()->getLocEnd();
1501 startBuf = SM->getCharacterData(startLoc);
1502
Steve Naroffc7089f12008-08-19 13:04:19 +00001503 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001504 SourceLocation lastCurlyLoc = startLoc;
1505 buf = "}\nelse {\n";
1506 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001507 buf += "}\n";
1508 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001509 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb2a39452008-07-16 19:47:39 +00001510 buf += " objc_sync_exit(";
Ted Kremenek8189cde2009-02-07 01:47:29 +00001511 Expr *syncExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
1512 S->getSynchExpr(),
1513 Context->getObjCIdType(),
1514 SourceLocation(),
1515 SourceLocation());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001516 std::string syncExprBufS;
1517 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Steve Naroff3498cc92008-08-21 13:03:03 +00001518 syncExpr->printPretty(syncExprBuf);
Steve Naroffb2a39452008-07-16 19:47:39 +00001519 buf += syncExprBuf.str();
1520 buf += ");\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001521 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1522 buf += "}\n";
1523 buf += "}";
1524
Chris Lattneraadaf782008-01-31 19:51:04 +00001525 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001526 return 0;
1527}
1528
Steve Naroff8c565152008-12-05 17:03:39 +00001529void RewriteObjC::WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S) {
1530 // Perform a bottom up traversal of all children.
1531 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1532 CI != E; ++CI)
1533 if (*CI)
1534 WarnAboutReturnGotoContinueOrBreakStmts(*CI);
1535
1536 if (isa<ReturnStmt>(S) || isa<ContinueStmt>(S) ||
1537 isa<BreakStmt>(S) || isa<GotoStmt>(S)) {
1538 Diags.Report(Context->getFullLoc(S->getLocStart()),
1539 TryFinallyContainsReturnDiag);
1540 }
1541 return;
1542}
1543
Steve Naroffb29b4272008-04-14 22:03:09 +00001544Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001545 // Get the start location and compute the semi location.
1546 SourceLocation startLoc = S->getLocStart();
1547 const char *startBuf = SM->getCharacterData(startLoc);
1548
1549 assert((*startBuf == '@') && "bogus @try location");
1550
1551 std::string buf;
1552 // declare a new scope with two variables, _stack and _rethrow.
1553 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1554 buf += "int buf[18/*32-bit i386*/];\n";
1555 buf += "char *pointers[4];} _stack;\n";
1556 buf += "id volatile _rethrow = 0;\n";
1557 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001558 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001559
Chris Lattneraadaf782008-01-31 19:51:04 +00001560 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001561
1562 startLoc = S->getTryBody()->getLocEnd();
1563 startBuf = SM->getCharacterData(startLoc);
1564
1565 assert((*startBuf == '}') && "bogus @try block");
Steve Naroffc9ba1722008-07-16 15:31:30 +00001566
Steve Naroff75730982007-11-07 04:08:17 +00001567 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001568 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1569 if (catchList) {
1570 startLoc = startLoc.getFileLocWithOffset(1);
1571 buf = " /* @catch begin */ else {\n";
1572 buf += " id _caught = objc_exception_extract(&_stack);\n";
1573 buf += " objc_exception_try_enter (&_stack);\n";
1574 buf += " if (_setjmp(_stack.buf))\n";
1575 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1576 buf += " else { /* @catch continue */";
1577
1578 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001579 } else { /* no catch list */
1580 buf = "}\nelse {\n";
1581 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1582 buf += "}";
1583 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffc9ba1722008-07-16 15:31:30 +00001584 }
Steve Naroff75730982007-11-07 04:08:17 +00001585 bool sawIdTypedCatch = false;
1586 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001587 while (catchList) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00001588 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001589
1590 if (catchList == S->getCatchStmts())
1591 buf = "if ("; // we are generating code for the first catch clause
1592 else
1593 buf = "else if (";
1594 startLoc = catchList->getLocStart();
1595 startBuf = SM->getCharacterData(startLoc);
1596
1597 assert((*startBuf == '@') && "bogus @catch location");
1598
1599 const char *lParenLoc = strchr(startBuf, '(');
1600
Steve Naroffbe4b3332008-02-01 22:08:12 +00001601 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001602 // Now rewrite the body...
1603 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001604 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1605 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001606 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1607 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001608 assert((*bodyBuf == '{') && "bogus @catch body location");
1609
1610 buf += "1) { id _tmp = _caught;";
1611 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1612 buf.c_str(), buf.size());
Steve Naroff7ba138a2009-03-03 19:52:17 +00001613 } else if (catchDecl) {
1614 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001615 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001616 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001617 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001618 sawIdTypedCatch = true;
1619 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001620 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001621
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001622 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001623 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001624 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001625 buf += cls->getDecl()->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001626 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001627 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001628 }
1629 }
1630 // Now rewrite the body...
1631 lastCatchBody = catchList->getCatchBody();
1632 SourceLocation rParenLoc = catchList->getRParenLoc();
1633 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1634 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1635 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1636 assert((*rParenBuf == ')') && "bogus @catch paren location");
1637 assert((*bodyBuf == '{') && "bogus @catch body location");
1638
1639 buf = " = _caught;";
1640 // Here we replace ") {" with "= _caught;" (which initializes and
1641 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001642 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff7ba138a2009-03-03 19:52:17 +00001643 } else {
Steve Naroff75730982007-11-07 04:08:17 +00001644 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001645 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001646 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001647 catchList = catchList->getNextCatchStmt();
1648 }
1649 // Complete the catch list...
1650 if (lastCatchBody) {
1651 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001652 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1653 "bogus @catch body location");
Steve Naroff75730982007-11-07 04:08:17 +00001654
Steve Naroff378f47a2008-09-11 15:29:03 +00001655 // Insert the last (implicit) else clause *before* the right curly brace.
1656 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1657 buf = "} /* last catch end */\n";
1658 buf += "else {\n";
1659 buf += " _rethrow = _caught;\n";
1660 buf += " objc_exception_try_exit(&_stack);\n";
1661 buf += "} } /* @catch end */\n";
1662 if (!S->getFinallyStmt())
1663 buf += "}\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001664 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001665
1666 // Set lastCurlyLoc
1667 lastCurlyLoc = lastCatchBody->getLocEnd();
1668 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001669 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001670 startLoc = finalStmt->getLocStart();
1671 startBuf = SM->getCharacterData(startLoc);
1672 assert((*startBuf == '@') && "bogus @finally start");
1673
1674 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001675 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001676
1677 Stmt *body = finalStmt->getFinallyBody();
1678 SourceLocation startLoc = body->getLocStart();
1679 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001680 assert(*SM->getCharacterData(startLoc) == '{' &&
1681 "bogus @finally body location");
1682 assert(*SM->getCharacterData(endLoc) == '}' &&
1683 "bogus @finally body location");
Steve Naroff75730982007-11-07 04:08:17 +00001684
1685 startLoc = startLoc.getFileLocWithOffset(1);
1686 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001687 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001688 endLoc = endLoc.getFileLocWithOffset(-1);
1689 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001690 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001691
1692 // Set lastCurlyLoc
1693 lastCurlyLoc = body->getLocEnd();
Steve Naroff8c565152008-12-05 17:03:39 +00001694
1695 // Now check for any return/continue/go statements within the @try.
1696 WarnAboutReturnGotoContinueOrBreakStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00001697 } else { /* no finally clause - make sure we synthesize an implicit one */
1698 buf = "{ /* implicit finally clause */\n";
1699 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1700 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1701 buf += "}";
1702 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001703 }
1704 // Now emit the final closing curly brace...
1705 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1706 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001707 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001708 return 0;
1709}
1710
Steve Naroffb29b4272008-04-14 22:03:09 +00001711Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001712 return 0;
1713}
1714
Steve Naroffb29b4272008-04-14 22:03:09 +00001715Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001716 return 0;
1717}
1718
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001719// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001720// the throw expression is typically a message expression that's already
1721// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001722Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001723 // Get the start location and compute the semi location.
1724 SourceLocation startLoc = S->getLocStart();
1725 const char *startBuf = SM->getCharacterData(startLoc);
1726
1727 assert((*startBuf == '@') && "bogus @throw location");
1728
1729 std::string buf;
1730 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001731 if (S->getThrowExpr())
1732 buf = "objc_exception_throw(";
1733 else // add an implicit argument
1734 buf = "objc_exception_throw(_caught";
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001735
1736 // handle "@ throw" correctly.
1737 const char *wBuf = strchr(startBuf, 'w');
1738 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1739 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1740
Steve Naroff2bd03922007-11-07 15:32:26 +00001741 const char *semiBuf = strchr(startBuf, ';');
1742 assert((*semiBuf == ';') && "@throw: can't find ';'");
1743 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1744 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001745 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001746 return 0;
1747}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001748
Steve Naroffb29b4272008-04-14 22:03:09 +00001749Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001750 // Create a new string expression.
1751 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001752 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001753 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattner2085fd62009-02-18 06:40:38 +00001754 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
1755 StrEncoding.length(), false,StrType,
1756 SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001757 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001758
Chris Lattner07506182007-11-30 22:53:43 +00001759 // Replace this subexpr in the parent.
Steve Naroff4c3580e2008-12-04 23:50:32 +00001760 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00001761 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001762}
1763
Steve Naroffb29b4272008-04-14 22:03:09 +00001764Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00001765 if (!SelGetUidFunctionDecl)
1766 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00001767 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1768 // Create a call to sel_registerName("selName").
1769 llvm::SmallVector<Expr*, 8> SelExprs;
1770 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00001771 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00001772 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00001773 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00001774 false, argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00001775 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1776 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001777 ReplaceStmt(Exp, SelExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001778 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00001779 return SelExp;
1780}
1781
Steve Naroffb29b4272008-04-14 22:03:09 +00001782CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001783 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001784 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001785 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001786
1787 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001788 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001789
1790 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001791 QualType pToFunc = Context->getPointerType(msgSendType);
Ted Kremenek8189cde2009-02-07 01:47:29 +00001792 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc, DRE,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001793 /*isLvalue=*/false);
Steve Naroffebf2b562007-10-23 23:50:29 +00001794
1795 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001796
Ted Kremenek668bf912009-02-09 20:51:47 +00001797 return new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
1798 SourceLocation());
Steve Naroff934f2762007-10-24 22:48:43 +00001799}
1800
Steve Naroffd5255f52007-11-01 13:24:47 +00001801static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1802 const char *&startRef, const char *&endRef) {
1803 while (startBuf < endBuf) {
1804 if (*startBuf == '<')
1805 startRef = startBuf; // mark the start.
1806 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001807 if (startRef && *startRef == '<') {
1808 endRef = startBuf; // mark the end.
1809 return true;
1810 }
1811 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001812 }
1813 startBuf++;
1814 }
1815 return false;
1816}
1817
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001818static void scanToNextArgument(const char *&argRef) {
1819 int angle = 0;
1820 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1821 if (*argRef == '<')
1822 angle++;
1823 else if (*argRef == '>')
1824 angle--;
1825 argRef++;
1826 }
1827 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1828}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001829
Steve Naroffb29b4272008-04-14 22:03:09 +00001830bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001831
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001832 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001833 return true;
1834
Steve Naroffd5255f52007-11-01 13:24:47 +00001835 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001836 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001837 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001838 return true; // we have "Class <Protocol> *".
1839 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001840 return false;
1841}
1842
Steve Naroff4f95b752008-07-29 18:15:38 +00001843void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1844 QualType Type = E->getType();
1845 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00001846 SourceLocation Loc, EndLoc;
1847
1848 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1849 Loc = ECE->getLParenLoc();
1850 EndLoc = ECE->getRParenLoc();
1851 } else {
1852 Loc = E->getLocStart();
1853 EndLoc = E->getLocEnd();
1854 }
1855 // This will defend against trying to rewrite synthesized expressions.
1856 if (Loc.isInvalid() || EndLoc.isInvalid())
1857 return;
1858
Steve Naroff4f95b752008-07-29 18:15:38 +00001859 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00001860 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00001861 const char *startRef = 0, *endRef = 0;
1862 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1863 // Get the locations of the startRef, endRef.
1864 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1865 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1866 // Comment out the protocol references.
1867 InsertText(LessLoc, "/*", 2);
1868 InsertText(GreaterLoc, "*/", 2);
1869 }
1870 }
1871}
1872
Steve Naroffb29b4272008-04-14 22:03:09 +00001873void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001874 SourceLocation Loc;
1875 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00001876 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001877 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1878 Loc = VD->getLocation();
1879 Type = VD->getType();
1880 }
1881 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1882 Loc = FD->getLocation();
1883 // Check for ObjC 'id' and class types that have been adorned with protocol
1884 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1885 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1886 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00001887 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001888 if (!proto)
1889 return;
1890 Type = proto->getResultType();
1891 }
1892 else
1893 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001894
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001895 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001896 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001897
1898 const char *endBuf = SM->getCharacterData(Loc);
1899 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00001900 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001901 startBuf--; // scan backward (from the decl location) for return type.
1902 const char *startRef = 0, *endRef = 0;
1903 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1904 // Get the locations of the startRef, endRef.
1905 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1906 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1907 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001908 InsertText(LessLoc, "/*", 2);
1909 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001910 }
1911 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001912 if (!proto)
1913 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001914 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001915 const char *startBuf = SM->getCharacterData(Loc);
1916 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001917 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1918 if (needToScanForQualifiers(proto->getArgType(i))) {
1919 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001920
Steve Naroffd5255f52007-11-01 13:24:47 +00001921 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001922 // scan forward (from the decl location) for argument types.
1923 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001924 const char *startRef = 0, *endRef = 0;
1925 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1926 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001927 SourceLocation LessLoc =
1928 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1929 SourceLocation GreaterLoc =
1930 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001931 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001932 InsertText(LessLoc, "/*", 2);
1933 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001934 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001935 startBuf = ++endBuf;
1936 }
1937 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00001938 // If the function name is derived from a macro expansion, then the
1939 // argument buffer will not follow the name. Need to speak with Chris.
1940 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001941 startBuf++; // scan forward (from the decl location) for argument types.
1942 startBuf++;
1943 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001944 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001945}
1946
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001947// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00001948void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001949 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1950 llvm::SmallVector<QualType, 16> ArgTys;
1951 ArgTys.push_back(Context->getPointerType(
1952 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001953 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001954 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001955 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001956 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001957 SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001958 SelGetUidIdent, getFuncType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001959 FunctionDecl::Extern, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001960}
1961
Steve Naroffb29b4272008-04-14 22:03:09 +00001962void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001963 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00001964 if (FD->getIdentifier() &&
1965 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001966 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001967 return;
1968 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001969 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001970}
1971
Steve Naroffc0a123c2008-03-11 17:37:02 +00001972// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00001973void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00001974 if (SuperContructorFunctionDecl)
1975 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00001976 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroffc0a123c2008-03-11 17:37:02 +00001977 llvm::SmallVector<QualType, 16> ArgTys;
1978 QualType argT = Context->getObjCIdType();
1979 assert(!argT.isNull() && "Can't find 'id' type");
1980 ArgTys.push_back(argT);
1981 ArgTys.push_back(argT);
1982 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1983 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001984 false, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001985 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001986 SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00001987 msgSendIdent, msgSendType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001988 FunctionDecl::Extern, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00001989}
1990
Steve Naroff09b266e2007-10-30 23:14:51 +00001991// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001992void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001993 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1994 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001995 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001996 assert(!argT.isNull() && "Can't find 'id' type");
1997 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001998 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001999 assert(!argT.isNull() && "Can't find 'SEL' type");
2000 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002001 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002002 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002003 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002004 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002005 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002006 msgSendIdent, msgSendType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002007 FunctionDecl::Extern, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002008}
2009
Steve Naroff874e2322007-11-15 10:28:18 +00002010// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002011void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002012 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2013 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002014 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002015 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002016 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002017 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2018 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2019 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002020 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002021 assert(!argT.isNull() && "Can't find 'SEL' type");
2022 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002023 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00002024 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002025 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002026 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002027 SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00002028 msgSendIdent, msgSendType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002029 FunctionDecl::Extern, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002030}
2031
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002032// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002033void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002034 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2035 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002036 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002037 assert(!argT.isNull() && "Can't find 'id' type");
2038 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002039 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002040 assert(!argT.isNull() && "Can't find 'SEL' type");
2041 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002042 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002043 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002044 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002045 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002046 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002047 msgSendIdent, msgSendType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002048 FunctionDecl::Extern, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002049}
2050
2051// SynthMsgSendSuperStretFunctionDecl -
2052// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002053void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002054 IdentifierInfo *msgSendIdent =
2055 &Context->Idents.get("objc_msgSendSuper_stret");
2056 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002057 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002058 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002059 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002060 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2061 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2062 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002063 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002064 assert(!argT.isNull() && "Can't find 'SEL' type");
2065 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002066 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002067 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002068 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002069 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnera98e58d2008-03-15 21:24:04 +00002070 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002071 msgSendIdent, msgSendType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002072 FunctionDecl::Extern, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002073}
2074
Steve Naroff1284db82008-05-08 22:02:18 +00002075// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002076void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002077 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2078 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002079 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002080 assert(!argT.isNull() && "Can't find 'id' type");
2081 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002082 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002083 assert(!argT.isNull() && "Can't find 'SEL' type");
2084 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00002085 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002086 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002087 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002088 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002089 SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002090 msgSendIdent, msgSendType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002091 FunctionDecl::Extern, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002092}
2093
Steve Naroff09b266e2007-10-30 23:14:51 +00002094// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002095void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002096 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2097 llvm::SmallVector<QualType, 16> ArgTys;
2098 ArgTys.push_back(Context->getPointerType(
2099 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002100 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002101 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002102 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002103 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002104 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002105 getClassIdent, getClassType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002106 FunctionDecl::Extern, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002107}
2108
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002109// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002110void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002111 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2112 llvm::SmallVector<QualType, 16> ArgTys;
2113 ArgTys.push_back(Context->getPointerType(
2114 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002115 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002116 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002117 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002118 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002119 SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002120 getClassIdent, getClassType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002121 FunctionDecl::Extern, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002122}
2123
Steve Naroffb29b4272008-04-14 22:03:09 +00002124Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002125 QualType strType = getConstantStringStructType();
2126
2127 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002128
2129 std::string tmpName = InFileName;
2130 unsigned i;
2131 for (i=0; i < tmpName.length(); i++) {
2132 char c = tmpName.at(i);
2133 // replace any non alphanumeric characters with '_'.
2134 if (!isalpha(c) && (c < '0' || c > '9'))
2135 tmpName[i] = '_';
2136 }
2137 S += tmpName;
2138 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002139 S += utostr(NumObjCStringLiterals++);
2140
Steve Naroffba92b2e2008-03-27 22:29:16 +00002141 Preamble += "static __NSConstantStringImpl " + S;
2142 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2143 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002144 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002145 std::string prettyBufS;
2146 llvm::raw_string_ostream prettyBuf(prettyBufS);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002147 Exp->getString()->printPretty(prettyBuf);
Steve Naroffba92b2e2008-03-27 22:29:16 +00002148 Preamble += prettyBuf.str();
2149 Preamble += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00002150 // The minus 2 removes the begin/end double quotes.
Steve Naroffba92b2e2008-03-27 22:29:16 +00002151 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002152
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002153 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff248a7532008-04-15 22:42:06 +00002154 &Context->Idents.get(S.c_str()), strType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002155 VarDecl::Static);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002156 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2157 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002158 Context->getPointerType(DRE->getType()),
2159 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002160 // cast to NSConstantString *
Ted Kremenek8189cde2009-02-07 01:47:29 +00002161 CastExpr *cast = new (Context) CStyleCastExpr(Exp->getType(), Unop,
Steve Naroffb2f9e512008-11-03 23:29:32 +00002162 Exp->getType(), SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002163 ReplaceStmt(Exp, cast);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002164 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002165 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002166}
2167
Steve Naroffb29b4272008-04-14 22:03:09 +00002168ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002169 // check if we are sending a message to 'super'
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002170 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002171
Douglas Gregorcd9b46e2008-11-04 14:56:14 +00002172 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
2173 const PointerType *PT = Super->getType()->getAsPointerType();
Chris Lattner0d17f6f2008-06-21 18:04:54 +00002174 assert(PT);
2175 ObjCInterfaceType *IT = cast<ObjCInterfaceType>(PT->getPointeeType());
2176 return IT->getDecl();
2177 }
2178 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00002179}
2180
2181// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002182QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002183 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002184 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002185 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002186 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002187 QualType FieldTypes[2];
2188
2189 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002190 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002191 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002192 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002193
Steve Naroff874e2322007-11-15 10:28:18 +00002194 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002195 for (unsigned i = 0; i < 2; ++i) {
Douglas Gregor6ab35242009-04-09 21:40:53 +00002196 SuperStructDecl->addDecl(*Context,
2197 FieldDecl::Create(*Context, SuperStructDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002198 SourceLocation(), 0,
2199 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002200 /*Mutable=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002201 }
Steve Naroff874e2322007-11-15 10:28:18 +00002202
Douglas Gregor44b43212008-12-11 16:49:14 +00002203 SuperStructDecl->completeDefinition(*Context);
Steve Naroff874e2322007-11-15 10:28:18 +00002204 }
2205 return Context->getTagDeclType(SuperStructDecl);
2206}
2207
Steve Naroffb29b4272008-04-14 22:03:09 +00002208QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002209 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002210 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002211 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002212 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002213 QualType FieldTypes[4];
2214
2215 // struct objc_object *receiver;
2216 FieldTypes[0] = Context->getObjCIdType();
2217 // int flags;
2218 FieldTypes[1] = Context->IntTy;
2219 // char *str;
2220 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2221 // long length;
2222 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002223
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002224 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002225 for (unsigned i = 0; i < 4; ++i) {
Douglas Gregor6ab35242009-04-09 21:40:53 +00002226 ConstantStringDecl->addDecl(*Context,
2227 FieldDecl::Create(*Context,
Douglas Gregor44b43212008-12-11 16:49:14 +00002228 ConstantStringDecl,
2229 SourceLocation(), 0,
2230 FieldTypes[i],
2231 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002232 /*Mutable=*/true));
Douglas Gregor44b43212008-12-11 16:49:14 +00002233 }
2234
2235 ConstantStringDecl->completeDefinition(*Context);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002236 }
2237 return Context->getTagDeclType(ConstantStringDecl);
2238}
2239
Steve Naroffb29b4272008-04-14 22:03:09 +00002240Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002241 if (!SelGetUidFunctionDecl)
2242 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002243 if (!MsgSendFunctionDecl)
2244 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002245 if (!MsgSendSuperFunctionDecl)
2246 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002247 if (!MsgSendStretFunctionDecl)
2248 SynthMsgSendStretFunctionDecl();
2249 if (!MsgSendSuperStretFunctionDecl)
2250 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002251 if (!MsgSendFpretFunctionDecl)
2252 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002253 if (!GetClassFunctionDecl)
2254 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002255 if (!GetMetaClassFunctionDecl)
2256 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002257
Steve Naroff874e2322007-11-15 10:28:18 +00002258 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002259 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2260 // May need to use objc_msgSend_stret() as well.
2261 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002262 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2263 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00002264 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002265 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002266 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002267 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002268 }
Steve Naroff874e2322007-11-15 10:28:18 +00002269
Steve Naroff934f2762007-10-24 22:48:43 +00002270 // Synthesize a call to objc_msgSend().
2271 llvm::SmallVector<Expr*, 8> MsgExprs;
2272 IdentifierInfo *clsName = Exp->getClassName();
2273
2274 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2275 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002276 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2277 // the 'super' idiom within a class method.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002278 if (!strcmp(clsName->getName(), "super")) {
2279 MsgSendFlavor = MsgSendSuperFunctionDecl;
2280 if (MsgSendStretFlavor)
2281 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2282 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2283
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002284 ObjCInterfaceDecl *SuperDecl =
Steve Naroff54055232008-10-27 17:20:55 +00002285 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002286
2287 llvm::SmallVector<Expr*, 4> InitExprs;
2288
2289 // set the receiver to self, the first argument to all methods.
Steve Naroff621edce2009-04-29 16:37:50 +00002290 InitExprs.push_back(
2291 new (Context) CStyleCastExpr(Context->getObjCIdType(),
2292 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2293 Context->getObjCIdType(),
2294 SourceLocation()),
2295 Context->getObjCIdType(),
2296 SourceLocation(), SourceLocation())); // set the 'receiver'.
2297
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002298 llvm::SmallVector<Expr*, 8> ClsExprs;
2299 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002300 ClsExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002301 SuperDecl->getIdentifier()->getName(),
2302 SuperDecl->getIdentifier()->getLength(),
Chris Lattner726e1682009-02-18 05:49:11 +00002303 false, argType, SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002304 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2305 &ClsExprs[0],
2306 ClsExprs.size());
2307 // To turn off a warning, type-cast to 'id'
Douglas Gregor49badde2008-10-27 19:41:14 +00002308 InitExprs.push_back( // set 'super class', using objc_getClass().
Ted Kremenek8189cde2009-02-07 01:47:29 +00002309 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002310 Cls, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002311 SourceLocation(), SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002312 // struct objc_super
2313 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002314 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002315
Steve Naroff23f41272008-03-11 18:14:26 +00002316 if (LangOpts.Microsoft) {
2317 SynthSuperContructorFunctionDecl();
2318 // Simulate a contructor call...
Ted Kremenek8189cde2009-02-07 01:47:29 +00002319 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff23f41272008-03-11 18:14:26 +00002320 superType, SourceLocation());
Ted Kremenek668bf912009-02-09 20:51:47 +00002321 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2322 InitExprs.size(),
2323 superType, SourceLocation());
Steve Naroff46a98a72008-12-23 20:11:22 +00002324 // The code for super is a little tricky to prevent collision with
2325 // the structure definition in the header. The rewriter has it's own
2326 // internal definition (__rw_objc_super) that is uses. This is why
2327 // we need the cast below. For example:
2328 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2329 //
Ted Kremenek8189cde2009-02-07 01:47:29 +00002330 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Steve Naroff46a98a72008-12-23 20:11:22 +00002331 Context->getPointerType(SuperRep->getType()),
2332 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00002333 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Steve Naroff46a98a72008-12-23 20:11:22 +00002334 SuperRep, Context->getPointerType(superType),
2335 SourceLocation(), SourceLocation());
Steve Naroff23f41272008-03-11 18:14:26 +00002336 } else {
2337 // (struct objc_super) { <exprs from above> }
Ted Kremenek8189cde2009-02-07 01:47:29 +00002338 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
Steve Naroff23f41272008-03-11 18:14:26 +00002339 &InitExprs[0], InitExprs.size(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002340 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00002341 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE,
Chris Lattner418f6c72008-10-26 23:43:26 +00002342 false);
Steve Naroff46a98a72008-12-23 20:11:22 +00002343 // struct objc_super *
Ted Kremenek8189cde2009-02-07 01:47:29 +00002344 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Steve Naroff46a98a72008-12-23 20:11:22 +00002345 Context->getPointerType(SuperRep->getType()),
2346 SourceLocation());
Steve Naroff23f41272008-03-11 18:14:26 +00002347 }
Steve Naroff46a98a72008-12-23 20:11:22 +00002348 MsgExprs.push_back(SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002349 } else {
2350 llvm::SmallVector<Expr*, 8> ClsExprs;
2351 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002352 ClsExprs.push_back(StringLiteral::Create(*Context,
2353 clsName->getName(),
2354 clsName->getLength(),
2355 false, argType,
2356 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002357 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2358 &ClsExprs[0],
2359 ClsExprs.size());
2360 MsgExprs.push_back(Cls);
2361 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002362 } else { // instance message.
2363 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002364
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002365 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002366 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002367 if (MsgSendStretFlavor)
2368 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002369 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2370
2371 llvm::SmallVector<Expr*, 4> InitExprs;
2372
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002373 InitExprs.push_back(
Ted Kremenek8189cde2009-02-07 01:47:29 +00002374 new (Context) CStyleCastExpr(Context->getObjCIdType(),
2375 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002376 Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002377 SourceLocation()),
2378 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002379 SourceLocation(), SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00002380
2381 llvm::SmallVector<Expr*, 8> ClsExprs;
2382 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002383 ClsExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002384 SuperDecl->getIdentifier()->getName(),
2385 SuperDecl->getIdentifier()->getLength(),
Chris Lattner726e1682009-02-18 05:49:11 +00002386 false, argType, SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002387 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002388 &ClsExprs[0],
2389 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002390 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002391 InitExprs.push_back(
Douglas Gregor49badde2008-10-27 19:41:14 +00002392 // set 'super class', using objc_getClass().
Ted Kremenek8189cde2009-02-07 01:47:29 +00002393 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002394 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002395 // struct objc_super
2396 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002397 Expr *SuperRep;
2398
2399 if (LangOpts.Microsoft) {
2400 SynthSuperContructorFunctionDecl();
2401 // Simulate a contructor call...
Ted Kremenek8189cde2009-02-07 01:47:29 +00002402 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroffc0a123c2008-03-11 17:37:02 +00002403 superType, SourceLocation());
Ted Kremenek668bf912009-02-09 20:51:47 +00002404 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2405 InitExprs.size(),
2406 superType, SourceLocation());
Steve Naroff46a98a72008-12-23 20:11:22 +00002407 // The code for super is a little tricky to prevent collision with
2408 // the structure definition in the header. The rewriter has it's own
2409 // internal definition (__rw_objc_super) that is uses. This is why
2410 // we need the cast below. For example:
2411 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2412 //
Ted Kremenek8189cde2009-02-07 01:47:29 +00002413 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Steve Naroff46a98a72008-12-23 20:11:22 +00002414 Context->getPointerType(SuperRep->getType()),
2415 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00002416 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Steve Naroff46a98a72008-12-23 20:11:22 +00002417 SuperRep, Context->getPointerType(superType),
2418 SourceLocation(), SourceLocation());
Steve Naroffc0a123c2008-03-11 17:37:02 +00002419 } else {
2420 // (struct objc_super) { <exprs from above> }
Ted Kremenek8189cde2009-02-07 01:47:29 +00002421 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00002422 &InitExprs[0], InitExprs.size(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002423 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00002424 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002425 }
Steve Naroff46a98a72008-12-23 20:11:22 +00002426 MsgExprs.push_back(SuperRep);
Steve Naroff874e2322007-11-15 10:28:18 +00002427 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002428 // Remove all type-casts because it may contain objc-style types; e.g.
2429 // Foo<Proto> *.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002430 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002431 recExpr = CE->getSubExpr();
Ted Kremenek8189cde2009-02-07 01:47:29 +00002432 recExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(), recExpr,
Douglas Gregor49badde2008-10-27 19:41:14 +00002433 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002434 SourceLocation(), SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002435 MsgExprs.push_back(recExpr);
2436 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002437 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002438 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002439 llvm::SmallVector<Expr*, 8> SelExprs;
2440 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002441 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002442 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002443 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00002444 false, argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00002445 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2446 &SelExprs[0], SelExprs.size());
2447 MsgExprs.push_back(SelExp);
2448
2449 // Now push any user supplied arguments.
2450 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002451 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002452 // Make all implicit casts explicit...ICE comes in handy:-)
2453 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2454 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002455 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002456 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002457 : ICE->getType();
Ted Kremenek8189cde2009-02-07 01:47:29 +00002458 userExpr = new (Context) CStyleCastExpr(type, userExpr, type, SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002459 }
2460 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002461 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002462 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002463 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002464 userExpr = CE->getSubExpr();
Ted Kremenek8189cde2009-02-07 01:47:29 +00002465 userExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002466 userExpr, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002467 SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002468 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002469 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002470 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00002471 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2472 // out the argument in the original expression (since we aren't deleting
2473 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2474 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00002475 }
Steve Naroffab972d32007-11-04 22:37:50 +00002476 // Generate the funky cast.
2477 CastExpr *cast;
2478 llvm::SmallVector<QualType, 8> ArgTypes;
2479 QualType returnType;
2480
2481 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002482 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2483 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2484 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002485 ArgTypes.push_back(Context->getObjCIdType());
2486 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00002487 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002488 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00002489 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2490 E = OMD->param_end(); PI != E; ++PI) {
2491 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002492 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00002493 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002494 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00002495 if (isTopLevelBlockPointerType(t)) {
Steve Naroffa206b062008-10-29 14:49:46 +00002496 const BlockPointerType *BPT = t->getAsBlockPointerType();
2497 t = Context->getPointerType(BPT->getPointeeType());
2498 }
Steve Naroff352336b2007-11-05 14:36:37 +00002499 ArgTypes.push_back(t);
2500 }
Chris Lattner89951a82009-02-20 18:43:26 +00002501 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2502 ? Context->getObjCIdType() : OMD->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002503 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002504 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002505 }
2506 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002507 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002508
2509 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002510 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002511 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002512
2513 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2514 // If we don't do this cast, we get the following bizarre warning/note:
2515 // xx.m:13: warning: function called through a non-compatible type
2516 // xx.m:13: note: if this code is reached, the program will abort
Ted Kremenek8189cde2009-02-07 01:47:29 +00002517 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy), DRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002518 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002519 SourceLocation(), SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002520
Steve Naroffab972d32007-11-04 22:37:50 +00002521 // Now do the "normal" pointer to function cast.
2522 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002523 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002524 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002525 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroffab972d32007-11-04 22:37:50 +00002526 castType = Context->getPointerType(castType);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002527 cast = new (Context) CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002528
2529 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002530 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Steve Naroffab972d32007-11-04 22:37:50 +00002531
2532 const FunctionType *FT = msgSendType->getAsFunctionType();
Ted Kremenek668bf912009-02-09 20:51:47 +00002533 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2534 MsgExprs.size(),
2535 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002536 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002537 if (MsgSendStretFlavor) {
2538 // We have the method which returns a struct/union. Must also generate
2539 // call to objc_msgSend_stret and hang both varieties on a conditional
2540 // expression which dictate which one to envoke depending on size of
2541 // method's return type.
2542
2543 // Create a reference to the objc_msgSend_stret() declaration.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002544 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002545 SourceLocation());
2546 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Ted Kremenek8189cde2009-02-07 01:47:29 +00002547 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy), STDRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002548 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002549 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002550 // Now do the "normal" pointer to function cast.
2551 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002552 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002553 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002554 castType = Context->getPointerType(castType);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002555 cast = new (Context) CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002556
2557 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002558 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002559
2560 FT = msgSendType->getAsFunctionType();
Ted Kremenek668bf912009-02-09 20:51:47 +00002561 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2562 MsgExprs.size(),
2563 FT->getResultType(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002564
2565 // Build sizeof(returnType)
Douglas Gregorba498172009-03-13 21:01:28 +00002566 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
2567 returnType,
Sebastian Redl05189992008-11-11 17:56:53 +00002568 Context->getSizeType(),
2569 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002570 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2571 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2572 // For X86 it is more complicated and some kind of target specific routine
2573 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002574 unsigned IntSize =
2575 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Ted Kremenek8189cde2009-02-07 01:47:29 +00002576 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002577 Context->IntTy,
2578 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00002579 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002580 BinaryOperator::LE,
2581 Context->IntTy,
2582 SourceLocation());
2583 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2584 ConditionalOperator *CondExpr =
Ted Kremenek8189cde2009-02-07 01:47:29 +00002585 new (Context) ConditionalOperator(lessThanExpr, CE, STCE, returnType);
2586 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002587 }
Steve Naroff621edce2009-04-29 16:37:50 +00002588 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002589 return ReplacingStmt;
2590}
2591
Steve Naroffb29b4272008-04-14 22:03:09 +00002592Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002593 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff80c28552008-10-27 20:54:44 +00002594
Steve Naroff934f2762007-10-24 22:48:43 +00002595 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002596 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002597
Steve Naroff4c3580e2008-12-04 23:50:32 +00002598 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002599 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002600}
2601
Steve Naroff621edce2009-04-29 16:37:50 +00002602// typedef struct objc_object Protocol;
2603QualType RewriteObjC::getProtocolType() {
2604 if (!ProtocolTypeDecl) {
2605 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
2606 SourceLocation(),
2607 &Context->Idents.get("Protocol"),
2608 Context->getObjCIdType());
2609 }
2610 return Context->getTypeDeclType(ProtocolTypeDecl);
2611}
2612
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002613/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00002614/// a synthesized/forward data reference (to the protocol's metadata).
2615/// The forward references (and metadata) are generated in
2616/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00002617Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00002618 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
2619 IdentifierInfo *ID = &Context->Idents.get(Name);
2620 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2621 ID, QualType()/*UNUSED*/, VarDecl::Extern);
2622 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
2623 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
2624 Context->getPointerType(DRE->getType()),
2625 SourceLocation());
2626 CastExpr *castExpr = new (Context) CStyleCastExpr(DerefExpr->getType(), DerefExpr,
2627 DerefExpr->getType(),
2628 SourceLocation(), SourceLocation());
2629 ReplaceStmt(Exp, castExpr);
2630 ProtocolExprDecls.insert(Exp->getProtocol());
2631 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
2632 return castExpr;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002633
2634}
2635
Steve Naroffbaf58c32008-05-31 14:15:04 +00002636bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2637 const char *endBuf) {
2638 while (startBuf < endBuf) {
2639 if (*startBuf == '#') {
2640 // Skip whitespace.
2641 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2642 ;
2643 if (!strncmp(startBuf, "if", strlen("if")) ||
2644 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2645 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2646 !strncmp(startBuf, "define", strlen("define")) ||
2647 !strncmp(startBuf, "undef", strlen("undef")) ||
2648 !strncmp(startBuf, "else", strlen("else")) ||
2649 !strncmp(startBuf, "elif", strlen("elif")) ||
2650 !strncmp(startBuf, "endif", strlen("endif")) ||
2651 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2652 !strncmp(startBuf, "include", strlen("include")) ||
2653 !strncmp(startBuf, "import", strlen("import")) ||
2654 !strncmp(startBuf, "include_next", strlen("include_next")))
2655 return true;
2656 }
2657 startBuf++;
2658 }
2659 return false;
2660}
2661
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002662/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002663/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002664void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002665 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002666 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Chris Lattner8ec03f52008-11-24 03:54:41 +00002667 assert(CDecl->getNameAsCString() &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002668 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002669 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002670 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002671 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002672 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002673 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002674 SourceLocation LocStart = CDecl->getLocStart();
2675 SourceLocation LocEnd = CDecl->getLocEnd();
2676
2677 const char *startBuf = SM->getCharacterData(LocStart);
2678 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002679
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002680 // If no ivars and no root or if its root, directly or indirectly,
2681 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002682 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2683 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00002684 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Chris Lattneraadaf782008-01-31 19:51:04 +00002685 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002686 return;
2687 }
2688
2689 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002690 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002691 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002692 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002693 if (LangOpts.Microsoft)
2694 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002695
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002696 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002697 const char *cursor = strchr(startBuf, '{');
2698 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002699 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00002700 // If the buffer contains preprocessor directives, we do more fine-grained
2701 // rewrites. This is intended to fix code that looks like (which occurs in
2702 // NSURL.h, for example):
2703 //
2704 // #ifdef XYZ
2705 // @interface Foo : NSObject
2706 // #else
2707 // @interface FooBar : NSObject
2708 // #endif
2709 // {
2710 // int i;
2711 // }
2712 // @end
2713 //
2714 // This clause is segregated to avoid breaking the common case.
2715 if (BufferContainsPPDirectives(startBuf, cursor)) {
2716 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2717 CDecl->getClassLoc();
2718 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00002719 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002720
Chris Lattnercafeb352009-02-20 18:18:36 +00002721 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00002722 // advance to the end of the referenced protocols.
2723 while (endHeader < cursor && *endHeader != '>') endHeader++;
2724 endHeader++;
2725 }
2726 // rewrite the original header
2727 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2728 } else {
2729 // rewrite the original header *without* disturbing the '{'
2730 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2731 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002732 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002733 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002734 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002735 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002736 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002737 Result += "_IVARS;\n";
Steve Narofffea763e82007-11-14 19:25:57 +00002738
2739 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002740 SourceLocation OnePastCurly =
2741 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2742 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002743 }
2744 cursor++; // past '{'
2745
2746 // Now comment out any visibility specifiers.
2747 while (cursor < endBuf) {
2748 if (*cursor == '@') {
2749 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002750 // Skip whitespace.
2751 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2752 /*scan*/;
2753
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002754 // FIXME: presence of @public, etc. inside comment results in
2755 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002756 if (!strncmp(cursor, "public", strlen("public")) ||
2757 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002758 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002759 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002760 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002761 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002762 // FIXME: If there are cases where '<' is used in ivar declaration part
2763 // of user code, then scan the ivar list and use needToScanForQualifiers
2764 // for type checking.
2765 else if (*cursor == '<') {
2766 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002767 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002768 cursor = strchr(cursor, '>');
2769 cursor++;
2770 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002771 InsertText(atLoc, " */", 3);
Steve Naroffced80a82008-10-30 12:09:33 +00002772 } else if (*cursor == '^') { // rewrite block specifier.
2773 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2774 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002775 }
Steve Narofffea763e82007-11-14 19:25:57 +00002776 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002777 }
Steve Narofffea763e82007-11-14 19:25:57 +00002778 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002779 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002780 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00002781 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00002782 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002783 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002784 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002785 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002786 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002787 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002788 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002789 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002790 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002791 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002792}
2793
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002794// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002795/// class methods.
Douglas Gregor653f1b12009-04-23 01:02:12 +00002796template<typename MethodIterator>
2797void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
2798 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002799 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002800 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002801 const char *ClassName,
2802 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002803 if (MethodBegin == MethodEnd) return;
2804
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002805 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002806 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002807 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002808 SEL _cmd;
2809 char *method_types;
2810 void *_imp;
2811 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002812 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002813 Result += "\nstruct _objc_method {\n";
2814 Result += "\tSEL _cmd;\n";
2815 Result += "\tchar *method_types;\n";
2816 Result += "\tvoid *_imp;\n";
2817 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002818
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002819 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002820 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002821
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002822 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002823
2824 /* struct {
2825 struct _objc_method_list *next_method;
2826 int method_count;
2827 struct _objc_method method_list[];
2828 }
2829 */
Douglas Gregor653f1b12009-04-23 01:02:12 +00002830 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroff946a6932008-03-11 00:12:29 +00002831 Result += "\nstatic struct {\n";
2832 Result += "\tstruct _objc_method_list *next_method;\n";
2833 Result += "\tint method_count;\n";
2834 Result += "\tstruct _objc_method method_list[";
Douglas Gregor653f1b12009-04-23 01:02:12 +00002835 Result += utostr(NumMethods);
Steve Naroff946a6932008-03-11 00:12:29 +00002836 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002837 Result += prefix;
2838 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2839 Result += "_METHODS_";
2840 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002841 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002842 Result += IsInstanceMethod ? "inst" : "cls";
2843 Result += "_meth\")))= ";
Douglas Gregor653f1b12009-04-23 01:02:12 +00002844 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002845
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002846 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002847 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002848 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002849 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002850 Result += "\", \"";
2851 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002852 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002853 Result += MethodInternalNames[*MethodBegin];
2854 Result += "}\n";
2855 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2856 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002857 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002858 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002859 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002860 Result += "\", \"";
2861 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002862 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002863 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002864 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002865 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002866 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002867}
2868
Steve Naroff621edce2009-04-29 16:37:50 +00002869/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00002870void RewriteObjC::
Steve Naroff621edce2009-04-29 16:37:50 +00002871RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
2872 const char *ClassName, std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002873 static bool objc_protocol_methods = false;
Steve Naroff621edce2009-04-29 16:37:50 +00002874
2875 // Output struct protocol_methods holder of method selector and type.
2876 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2877 /* struct protocol_methods {
2878 SEL _cmd;
2879 char *method_types;
2880 }
2881 */
2882 Result += "\nstruct _protocol_methods {\n";
2883 Result += "\tstruct objc_selector *_cmd;\n";
2884 Result += "\tchar *method_types;\n";
2885 Result += "};\n";
2886
2887 objc_protocol_methods = true;
2888 }
2889 // Do not synthesize the protocol more than once.
2890 if (ObjCSynthesizedProtocols.count(PDecl))
2891 return;
2892
Douglas Gregor6ab35242009-04-09 21:40:53 +00002893 if (PDecl->instmeth_begin(*Context) != PDecl->instmeth_end(*Context)) {
2894 unsigned NumMethods = std::distance(PDecl->instmeth_begin(*Context),
2895 PDecl->instmeth_end(*Context));
Steve Naroff621edce2009-04-29 16:37:50 +00002896 /* struct _objc_protocol_method_list {
2897 int protocol_method_count;
2898 struct protocol_methods protocols[];
2899 }
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002900 */
Steve Naroff621edce2009-04-29 16:37:50 +00002901 Result += "\nstatic struct {\n";
2902 Result += "\tint protocol_method_count;\n";
2903 Result += "\tstruct _protocol_methods protocol_methods[";
2904 Result += utostr(NumMethods);
2905 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
2906 Result += PDecl->getNameAsString();
2907 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2908 "{\n\t" + utostr(NumMethods) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002909
Steve Naroff621edce2009-04-29 16:37:50 +00002910 // Output instance methods declared in this protocol.
2911 for (ObjCProtocolDecl::instmeth_iterator
2912 I = PDecl->instmeth_begin(*Context),
2913 E = PDecl->instmeth_end(*Context);
2914 I != E; ++I) {
2915 if (I == PDecl->instmeth_begin(*Context))
2916 Result += "\t ,{{(struct objc_selector *)\"";
2917 else
2918 Result += "\t ,{(struct objc_selector *)\"";
2919 Result += (*I)->getSelector().getAsString().c_str();
2920 std::string MethodTypeString;
2921 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2922 Result += "\", \"";
2923 Result += MethodTypeString;
2924 Result += "\"}\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002925 }
Steve Naroff621edce2009-04-29 16:37:50 +00002926 Result += "\t }\n};\n";
2927 }
2928
2929 // Output class methods declared in this protocol.
2930 unsigned NumMethods = std::distance(PDecl->classmeth_begin(*Context),
2931 PDecl->classmeth_end(*Context));
2932 if (NumMethods > 0) {
2933 /* struct _objc_protocol_method_list {
2934 int protocol_method_count;
2935 struct protocol_methods protocols[];
2936 }
2937 */
2938 Result += "\nstatic struct {\n";
2939 Result += "\tint protocol_method_count;\n";
2940 Result += "\tstruct _protocol_methods protocol_methods[";
2941 Result += utostr(NumMethods);
2942 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
2943 Result += PDecl->getNameAsString();
2944 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2945 "{\n\t";
2946 Result += utostr(NumMethods);
2947 Result += "\n";
2948
2949 // Output instance methods declared in this protocol.
2950 for (ObjCProtocolDecl::classmeth_iterator
2951 I = PDecl->classmeth_begin(*Context),
2952 E = PDecl->classmeth_end(*Context);
2953 I != E; ++I) {
2954 if (I == PDecl->classmeth_begin(*Context))
2955 Result += "\t ,{{(struct objc_selector *)\"";
2956 else
2957 Result += "\t ,{(struct objc_selector *)\"";
2958 Result += (*I)->getSelector().getAsString().c_str();
2959 std::string MethodTypeString;
2960 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2961 Result += "\", \"";
2962 Result += MethodTypeString;
2963 Result += "\"}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002964 }
Steve Naroff621edce2009-04-29 16:37:50 +00002965 Result += "\t }\n};\n";
2966 }
2967
2968 // Output:
2969 /* struct _objc_protocol {
2970 // Objective-C 1.0 extensions
2971 struct _objc_protocol_extension *isa;
2972 char *protocol_name;
2973 struct _objc_protocol **protocol_list;
2974 struct _objc_protocol_method_list *instance_methods;
2975 struct _objc_protocol_method_list *class_methods;
2976 };
2977 */
2978 static bool objc_protocol = false;
2979 if (!objc_protocol) {
2980 Result += "\nstruct _objc_protocol {\n";
2981 Result += "\tstruct _objc_protocol_extension *isa;\n";
2982 Result += "\tchar *protocol_name;\n";
2983 Result += "\tstruct _objc_protocol **protocol_list;\n";
2984 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2985 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002986 Result += "};\n";
2987
Steve Naroff621edce2009-04-29 16:37:50 +00002988 objc_protocol = true;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002989 }
Steve Naroff621edce2009-04-29 16:37:50 +00002990
2991 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2992 Result += PDecl->getNameAsString();
2993 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2994 "{\n\t0, \"";
2995 Result += PDecl->getNameAsString();
2996 Result += "\", 0, ";
2997 if (PDecl->instmeth_begin(*Context) != PDecl->instmeth_end(*Context)) {
2998 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
2999 Result += PDecl->getNameAsString();
3000 Result += ", ";
3001 }
3002 else
3003 Result += "0, ";
3004 if (PDecl->classmeth_begin(*Context) != PDecl->classmeth_end(*Context)) {
3005 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3006 Result += PDecl->getNameAsString();
3007 Result += "\n";
3008 }
3009 else
3010 Result += "0\n";
3011 Result += "};\n";
3012
3013 // Mark this protocol as having been generated.
3014 if (!ObjCSynthesizedProtocols.insert(PDecl))
3015 assert(false && "protocol already synthesized");
3016
3017}
3018
3019void RewriteObjC::
3020RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3021 const char *prefix, const char *ClassName,
3022 std::string &Result) {
3023 if (Protocols.empty()) return;
3024
3025 for (unsigned i = 0; i != Protocols.size(); i++)
3026 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3027
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003028 // Output the top lovel protocol meta-data for the class.
3029 /* struct _objc_protocol_list {
3030 struct _objc_protocol_list *next;
3031 int protocol_count;
3032 struct _objc_protocol *class_protocols[];
3033 }
3034 */
3035 Result += "\nstatic struct {\n";
3036 Result += "\tstruct _objc_protocol_list *next;\n";
3037 Result += "\tint protocol_count;\n";
3038 Result += "\tstruct _objc_protocol *class_protocols[";
3039 Result += utostr(Protocols.size());
3040 Result += "];\n} _OBJC_";
3041 Result += prefix;
3042 Result += "_PROTOCOLS_";
3043 Result += ClassName;
3044 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3045 "{\n\t0, ";
3046 Result += utostr(Protocols.size());
3047 Result += "\n";
3048
3049 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003050 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003051 Result += " \n";
3052
3053 for (unsigned i = 1; i != Protocols.size(); i++) {
3054 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003055 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003056 Result += "\n";
3057 }
3058 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003059}
3060
Steve Naroff621edce2009-04-29 16:37:50 +00003061
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003062/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003063/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003064void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003065 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003066 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003067 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003068 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003069 for (CDecl = ClassDecl->getCategoryList(); CDecl;
3070 CDecl = CDecl->getNextClassCategory())
3071 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3072 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003073
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003074 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003075 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003076 FullCategoryName += IDecl->getNameAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003077
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003078 // Build _objc_method_list for class's instance methods if needed
Douglas Gregor653f1b12009-04-23 01:02:12 +00003079 llvm::SmallVector<ObjCMethodDecl *, 32>
3080 InstanceMethods(IDecl->instmeth_begin(*Context),
3081 IDecl->instmeth_end(*Context));
3082
3083 // If any of our property implementations have associated getters or
3084 // setters, produce metadata for them as well.
3085 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(*Context),
3086 PropEnd = IDecl->propimpl_end(*Context);
3087 Prop != PropEnd; ++Prop) {
3088 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3089 continue;
3090 if (!(*Prop)->getPropertyIvarDecl())
3091 continue;
3092 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3093 if (!PD)
3094 continue;
3095 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3096 InstanceMethods.push_back(Getter);
3097 if (PD->isReadOnly())
3098 continue;
3099 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3100 InstanceMethods.push_back(Setter);
3101 }
3102 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003103 true, "CATEGORY_", FullCategoryName.c_str(),
3104 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003105
3106 // Build _objc_method_list for class's class methods if needed
Douglas Gregor653f1b12009-04-23 01:02:12 +00003107 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(*Context),
3108 IDecl->classmeth_end(*Context),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003109 false, "CATEGORY_", FullCategoryName.c_str(),
3110 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003111
3112 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003113 // Null CDecl is case of a category implementation with no category interface
3114 if (CDecl)
Steve Naroff621edce2009-04-29 16:37:50 +00003115 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3116 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003117 /* struct _objc_category {
3118 char *category_name;
3119 char *class_name;
3120 struct _objc_method_list *instance_methods;
3121 struct _objc_method_list *class_methods;
3122 struct _objc_protocol_list *protocols;
3123 // Objective-C 1.0 extensions
3124 uint32_t size; // sizeof (struct _objc_category)
3125 struct _objc_property_list *instance_properties; // category's own
3126 // @property decl.
3127 };
3128 */
3129
3130 static bool objc_category = false;
3131 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003132 Result += "\nstruct _objc_category {\n";
3133 Result += "\tchar *category_name;\n";
3134 Result += "\tchar *class_name;\n";
3135 Result += "\tstruct _objc_method_list *instance_methods;\n";
3136 Result += "\tstruct _objc_method_list *class_methods;\n";
3137 Result += "\tstruct _objc_protocol_list *protocols;\n";
3138 Result += "\tunsigned int size;\n";
3139 Result += "\tstruct _objc_property_list *instance_properties;\n";
3140 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003141 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003142 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003143 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3144 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003145 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003146 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003147 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003148 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003149 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003150
Douglas Gregor653f1b12009-04-23 01:02:12 +00003151 if (IDecl->instmeth_begin(*Context) != IDecl->instmeth_end(*Context)) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003152 Result += "\t, (struct _objc_method_list *)"
3153 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3154 Result += FullCategoryName;
3155 Result += "\n";
3156 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003157 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003158 Result += "\t, 0\n";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003159 if (IDecl->classmeth_begin(*Context) != IDecl->classmeth_end(*Context)) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003160 Result += "\t, (struct _objc_method_list *)"
3161 "&_OBJC_CATEGORY_CLASS_METHODS_";
3162 Result += FullCategoryName;
3163 Result += "\n";
3164 }
3165 else
3166 Result += "\t, 0\n";
3167
Chris Lattnercafeb352009-02-20 18:18:36 +00003168 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003169 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
3170 Result += FullCategoryName;
3171 Result += "\n";
3172 }
3173 else
3174 Result += "\t, 0\n";
3175 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003176}
3177
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003178/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3179/// ivar offset.
Steve Naroffb29b4272008-04-14 22:03:09 +00003180void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003181 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003182 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003183 if (ivar->isBitField()) {
3184 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3185 // place all bitfields at offset 0.
3186 Result += "0";
3187 } else {
3188 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003189 Result += IDecl->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003190 if (LangOpts.Microsoft)
3191 Result += "_IMPL";
3192 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003193 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003194 Result += ")";
3195 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003196}
3197
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003198//===----------------------------------------------------------------------===//
3199// Meta Data Emission
3200//===----------------------------------------------------------------------===//
3201
Steve Naroffb29b4272008-04-14 22:03:09 +00003202void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003203 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003204 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003205
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003206 // Explictly declared @interface's are already synthesized.
Steve Naroff33feeb02009-04-20 20:09:33 +00003207 if (CDecl->isImplicitInterfaceDecl()) {
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003208 // FIXME: Implementation of a class with no @interface (legacy) doese not
3209 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003210 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003211 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003212
Chris Lattnerbe6df082007-12-12 07:56:42 +00003213 // Build _objc_ivar_list metadata for classes ivars if needed
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003214 unsigned NumIvars = !IDecl->ivar_empty(*Context)
3215 ? IDecl->ivar_size(*Context)
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003216 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003217 if (NumIvars > 0) {
3218 static bool objc_ivar = false;
3219 if (!objc_ivar) {
3220 /* struct _objc_ivar {
3221 char *ivar_name;
3222 char *ivar_type;
3223 int ivar_offset;
3224 };
3225 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003226 Result += "\nstruct _objc_ivar {\n";
3227 Result += "\tchar *ivar_name;\n";
3228 Result += "\tchar *ivar_type;\n";
3229 Result += "\tint ivar_offset;\n";
3230 Result += "};\n";
3231
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003232 objc_ivar = true;
3233 }
3234
Steve Naroff946a6932008-03-11 00:12:29 +00003235 /* struct {
3236 int ivar_count;
3237 struct _objc_ivar ivar_list[nIvars];
3238 };
3239 */
3240 Result += "\nstatic struct {\n";
3241 Result += "\tint ivar_count;\n";
3242 Result += "\tstruct _objc_ivar ivar_list[";
3243 Result += utostr(NumIvars);
3244 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003245 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003246 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003247 "{\n\t";
3248 Result += utostr(NumIvars);
3249 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003250
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003251 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003252 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
3253 if (!IDecl->ivar_empty(*Context)) {
3254 for (ObjCImplementationDecl::ivar_iterator
3255 IV = IDecl->ivar_begin(*Context),
3256 IVEnd = IDecl->ivar_end(*Context);
3257 IV != IVEnd; ++IV)
3258 IVars.push_back(*IV);
3259 IVI = IVars.begin();
3260 IVE = IVars.end();
Chris Lattnerbe6df082007-12-12 07:56:42 +00003261 } else {
3262 IVI = CDecl->ivar_begin();
3263 IVE = CDecl->ivar_end();
3264 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003265 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003266 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003267 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003268 std::string TmpString, StrEncoding;
3269 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3270 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003271 Result += StrEncoding;
3272 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003273 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003274 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003275 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003276 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003277 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003278 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003279 std::string TmpString, StrEncoding;
3280 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3281 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003282 Result += StrEncoding;
3283 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003284 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003285 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003286 }
3287
3288 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003289 }
3290
3291 // Build _objc_method_list for class's instance methods if needed
Douglas Gregor653f1b12009-04-23 01:02:12 +00003292 llvm::SmallVector<ObjCMethodDecl *, 32>
3293 InstanceMethods(IDecl->instmeth_begin(*Context),
3294 IDecl->instmeth_end(*Context));
3295
3296 // If any of our property implementations have associated getters or
3297 // setters, produce metadata for them as well.
3298 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(*Context),
3299 PropEnd = IDecl->propimpl_end(*Context);
3300 Prop != PropEnd; ++Prop) {
3301 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3302 continue;
3303 if (!(*Prop)->getPropertyIvarDecl())
3304 continue;
3305 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3306 if (!PD)
3307 continue;
3308 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3309 InstanceMethods.push_back(Getter);
3310 if (PD->isReadOnly())
3311 continue;
3312 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3313 InstanceMethods.push_back(Setter);
3314 }
3315 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003316 true, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003317
3318 // Build _objc_method_list for class's class methods if needed
Douglas Gregor653f1b12009-04-23 01:02:12 +00003319 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(*Context),
3320 IDecl->classmeth_end(*Context),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003321 false, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003322
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003323 // Protocols referenced in class declaration?
Steve Naroff621edce2009-04-29 16:37:50 +00003324 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3325 "CLASS", CDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003326
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003327 // Declaration of class/meta-class metadata
3328 /* struct _objc_class {
3329 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003330 const char *super_class_name;
3331 char *name;
3332 long version;
3333 long info;
3334 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003335 struct _objc_ivar_list *ivars;
3336 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003337 struct objc_cache *cache;
3338 struct objc_protocol_list *protocols;
3339 const char *ivar_layout;
3340 struct _objc_class_ext *ext;
3341 };
3342 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003343 static bool objc_class = false;
3344 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003345 Result += "\nstruct _objc_class {\n";
3346 Result += "\tstruct _objc_class *isa;\n";
3347 Result += "\tconst char *super_class_name;\n";
3348 Result += "\tchar *name;\n";
3349 Result += "\tlong version;\n";
3350 Result += "\tlong info;\n";
3351 Result += "\tlong instance_size;\n";
3352 Result += "\tstruct _objc_ivar_list *ivars;\n";
3353 Result += "\tstruct _objc_method_list *methods;\n";
3354 Result += "\tstruct objc_cache *cache;\n";
3355 Result += "\tstruct _objc_protocol_list *protocols;\n";
3356 Result += "\tconst char *ivar_layout;\n";
3357 Result += "\tstruct _objc_class_ext *ext;\n";
3358 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003359 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003360 }
3361
3362 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003363 ObjCInterfaceDecl *RootClass = 0;
3364 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003365 while (SuperClass) {
3366 RootClass = SuperClass;
3367 SuperClass = SuperClass->getSuperClass();
3368 }
3369 SuperClass = CDecl->getSuperClass();
3370
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003371 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003372 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003373 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003374 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003375 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003376 Result += "\"";
3377
3378 if (SuperClass) {
3379 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003380 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003381 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003382 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003383 Result += "\"";
3384 }
3385 else {
3386 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003387 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003388 Result += "\"";
3389 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003390 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003391 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003392 Result += ", 0,2, sizeof(struct _objc_class), 0";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003393 if (IDecl->classmeth_begin(*Context) != IDecl->classmeth_end(*Context)) {
Steve Naroff23f41272008-03-11 18:14:26 +00003394 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003395 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003396 Result += "\n";
3397 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003398 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003399 Result += ", 0\n";
Chris Lattnercafeb352009-02-20 18:18:36 +00003400 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003401 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003402 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003403 Result += ",0,0\n";
3404 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003405 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003406 Result += "\t,0,0,0,0\n";
3407 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003408
3409 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003410 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003411 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003412 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003413 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003414 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003415 if (SuperClass) {
3416 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003417 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003418 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003419 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003420 Result += "\"";
3421 }
3422 else {
3423 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003424 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003425 Result += "\"";
3426 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003427 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003428 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003429 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003430 Result += ",0";
3431 else {
3432 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003433 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003434 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003435 if (LangOpts.Microsoft)
3436 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003437 Result += ")";
3438 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003439 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003440 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003441 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003442 Result += "\n\t";
3443 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003444 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003445 Result += ",0";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003446 if (IDecl->instmeth_begin(*Context) != IDecl->instmeth_end(*Context)) {
Steve Naroff946a6932008-03-11 00:12:29 +00003447 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003448 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003449 Result += ", 0\n\t";
3450 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003451 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003452 Result += ",0,0";
Chris Lattnercafeb352009-02-20 18:18:36 +00003453 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003454 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003455 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003456 Result += ", 0,0\n";
3457 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003458 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003459 Result += ",0,0,0\n";
3460 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003461}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003462
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003463/// RewriteImplementations - This routine rewrites all method implementations
3464/// and emits meta-data.
3465
Steve Narofface66252008-11-13 20:07:04 +00003466void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003467 int ClsDefCount = ClassImplementation.size();
3468 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003469
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003470 // Rewrite implemented methods
3471 for (int i = 0; i < ClsDefCount; i++)
3472 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003473
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003474 for (int i = 0; i < CatDefCount; i++)
3475 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003476}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003477
Steve Narofface66252008-11-13 20:07:04 +00003478void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3479 int ClsDefCount = ClassImplementation.size();
3480 int CatDefCount = CategoryImplementation.size();
3481
Steve Naroff5df5b762008-05-07 21:23:49 +00003482 // This is needed for determining instance variable offsets.
Steve Naroffa11440b2008-08-05 18:47:23 +00003483 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003484 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003485 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003486 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003487
3488 // For each implemented category, write out all its meta data.
3489 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003490 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroff621edce2009-04-29 16:37:50 +00003491
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003492 // Write objc_symtab metadata
3493 /*
3494 struct _objc_symtab
3495 {
3496 long sel_ref_cnt;
3497 SEL *refs;
3498 short cls_def_cnt;
3499 short cat_def_cnt;
3500 void *defs[cls_def_cnt + cat_def_cnt];
3501 };
3502 */
3503
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003504 Result += "\nstruct _objc_symtab {\n";
3505 Result += "\tlong sel_ref_cnt;\n";
3506 Result += "\tSEL *refs;\n";
3507 Result += "\tshort cls_def_cnt;\n";
3508 Result += "\tshort cat_def_cnt;\n";
3509 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3510 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003511
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003512 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003513 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003514 Result += "\t0, 0, " + utostr(ClsDefCount)
3515 + ", " + utostr(CatDefCount) + "\n";
3516 for (int i = 0; i < ClsDefCount; i++) {
3517 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003518 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003519 Result += "\n";
3520 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003521
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003522 for (int i = 0; i < CatDefCount; i++) {
3523 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003524 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003525 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003526 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003527 Result += "\n";
3528 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003529
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003530 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003531
3532 // Write objc_module metadata
3533
3534 /*
3535 struct _objc_module {
3536 long version;
3537 long size;
3538 const char *name;
3539 struct _objc_symtab *symtab;
3540 }
3541 */
3542
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003543 Result += "\nstruct _objc_module {\n";
3544 Result += "\tlong version;\n";
3545 Result += "\tlong size;\n";
3546 Result += "\tconst char *name;\n";
3547 Result += "\tstruct _objc_symtab *symtab;\n";
3548 Result += "};\n\n";
3549 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003550 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003551 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3552 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003553 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003554
3555 if (LangOpts.Microsoft) {
Steve Naroff621edce2009-04-29 16:37:50 +00003556 if (ProtocolExprDecls.size()) {
3557 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
3558 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
3559 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
3560 E = ProtocolExprDecls.end(); I != E; ++I) {
3561 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
3562 Result += (*I)->getNameAsString();
3563 Result += " = &_OBJC_PROTOCOL_";
3564 Result += (*I)->getNameAsString();
3565 Result += ";\n";
3566 }
3567 Result += "#pragma data_seg(pop)\n\n";
3568 }
Steve Naroff4f943c22008-03-10 20:43:59 +00003569 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003570 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003571 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3572 Result += "&_OBJC_MODULES;\n";
3573 Result += "#pragma data_seg(pop)\n\n";
3574 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003575}
Chris Lattner311ff022007-10-16 22:36:42 +00003576
Steve Naroff54055232008-10-27 17:20:55 +00003577std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3578 const char *funcName,
3579 std::string Tag) {
3580 const FunctionType *AFT = CE->getFunctionType();
3581 QualType RT = AFT->getResultType();
3582 std::string StructRef = "struct " + Tag;
3583 std::string S = "static " + RT.getAsString() + " __" +
3584 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003585
Steve Naroff54055232008-10-27 17:20:55 +00003586 BlockDecl *BD = CE->getBlockDecl();
3587
Douglas Gregor72564e72009-02-26 23:50:07 +00003588 if (isa<FunctionNoProtoType>(AFT)) {
Steve Naroffdf8570d2009-02-02 17:19:26 +00003589 // No user-supplied arguments. Still need to pass in a pointer to the
3590 // block (to reference imported block decl refs).
3591 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00003592 } else if (BD->param_empty()) {
3593 S += "(" + StructRef + " *__cself)";
3594 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003595 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00003596 assert(FT && "SynthesizeBlockFunc: No function proto");
3597 S += '(';
3598 // first add the implicit argument.
3599 S += StructRef + " *__cself, ";
3600 std::string ParamStr;
3601 for (BlockDecl::param_iterator AI = BD->param_begin(),
3602 E = BD->param_end(); AI != E; ++AI) {
3603 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003604 ParamStr = (*AI)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003605 (*AI)->getType().getAsStringInternal(ParamStr);
3606 S += ParamStr;
3607 }
3608 if (FT->isVariadic()) {
3609 if (!BD->param_empty()) S += ", ";
3610 S += "...";
3611 }
3612 S += ')';
3613 }
3614 S += " {\n";
3615
3616 // Create local declarations to avoid rewriting all closure decl ref exprs.
3617 // First, emit a declaration for all "by ref" decls.
3618 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3619 E = BlockByRefDecls.end(); I != E; ++I) {
3620 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003621 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003622 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003623 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Steve Naroff54055232008-10-27 17:20:55 +00003624 }
3625 // Next, emit a declaration for all "by copy" declarations.
3626 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3627 E = BlockByCopyDecls.end(); I != E; ++I) {
3628 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003629 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003630 // Handle nested closure invocation. For example:
3631 //
3632 // void (^myImportedClosure)(void);
3633 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3634 //
3635 // void (^anotherClosure)(void);
3636 // anotherClosure = ^(void) {
3637 // myImportedClosure(); // import and invoke the closure
3638 // };
3639 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003640 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003641 S += "struct __block_impl *";
3642 else
3643 (*I)->getType().getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003644 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff54055232008-10-27 17:20:55 +00003645 }
3646 std::string RewrittenStr = RewrittenBlockExprs[CE];
3647 const char *cstr = RewrittenStr.c_str();
3648 while (*cstr++ != '{') ;
3649 S += cstr;
3650 S += "\n";
3651 return S;
3652}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003653
Steve Naroff54055232008-10-27 17:20:55 +00003654std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3655 const char *funcName,
3656 std::string Tag) {
3657 std::string StructRef = "struct " + Tag;
3658 std::string S = "static void __";
3659
3660 S += funcName;
3661 S += "_block_copy_" + utostr(i);
3662 S += "(" + StructRef;
3663 S += "*dst, " + StructRef;
3664 S += "*src) {";
3665 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3666 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00003667 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003668 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00003669 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003670 S += (*I)->getNameAsString();
Steve Naroff5bc60d02008-12-16 15:50:30 +00003671 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);}";
Steve Naroff54055232008-10-27 17:20:55 +00003672 }
3673 S += "\nstatic void __";
3674 S += funcName;
3675 S += "_block_dispose_" + utostr(i);
3676 S += "(" + StructRef;
3677 S += "*src) {";
3678 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3679 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00003680 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003681 S += (*I)->getNameAsString();
Steve Naroff5bc60d02008-12-16 15:50:30 +00003682 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003683 }
3684 S += "}\n";
3685 return S;
3686}
3687
3688std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3689 bool hasCopyDisposeHelpers) {
Steve Naroffced80a82008-10-30 12:09:33 +00003690 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003691 std::string Constructor = " " + Tag;
3692
3693 S += " {\n struct __block_impl impl;\n";
3694
3695 if (hasCopyDisposeHelpers)
3696 S += " void *copy;\n void *dispose;\n";
3697
3698 Constructor += "(void *fp";
3699
3700 if (hasCopyDisposeHelpers)
3701 Constructor += ", void *copyHelp, void *disposeHelp";
3702
3703 if (BlockDeclRefs.size()) {
3704 // Output all "by copy" declarations.
3705 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3706 E = BlockByCopyDecls.end(); I != E; ++I) {
3707 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003708 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003709 std::string ArgName = "_" + FieldName;
3710 // Handle nested closure invocation. For example:
3711 //
3712 // void (^myImportedBlock)(void);
3713 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3714 //
3715 // void (^anotherBlock)(void);
3716 // anotherBlock = ^(void) {
3717 // myImportedBlock(); // import and invoke the closure
3718 // };
3719 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003720 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003721 S += "struct __block_impl *";
3722 Constructor += ", void *" + ArgName;
3723 } else {
3724 (*I)->getType().getAsStringInternal(FieldName);
3725 (*I)->getType().getAsStringInternal(ArgName);
3726 Constructor += ", " + ArgName;
3727 }
3728 S += FieldName + ";\n";
3729 }
3730 // Output all "by ref" declarations.
3731 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3732 E = BlockByRefDecls.end(); I != E; ++I) {
3733 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003734 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003735 std::string ArgName = "_" + FieldName;
3736 // Handle nested closure invocation. For example:
3737 //
3738 // void (^myImportedBlock)(void);
3739 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3740 //
3741 // void (^anotherBlock)(void);
3742 // anotherBlock = ^(void) {
3743 // myImportedBlock(); // import and invoke the closure
3744 // };
3745 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003746 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003747 S += "struct __block_impl *";
3748 Constructor += ", void *" + ArgName;
3749 } else {
3750 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName);
3751 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName);
3752 Constructor += ", " + ArgName;
3753 }
3754 S += FieldName + "; // by ref\n";
3755 }
3756 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00003757 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003758 if (GlobalVarDecl)
3759 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3760 else
3761 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3762 Constructor += " impl.Size = sizeof(";
Steve Naroff54055232008-10-27 17:20:55 +00003763 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3764
3765 if (hasCopyDisposeHelpers)
3766 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3767
3768 // Initialize all "by copy" arguments.
3769 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3770 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003771 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003772 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003773 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003774 Constructor += Name + " = (struct __block_impl *)_";
3775 else
3776 Constructor += Name + " = _";
3777 Constructor += Name + ";\n";
3778 }
3779 // Initialize all "by ref" arguments.
3780 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3781 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003782 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003783 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003784 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003785 Constructor += Name + " = (struct __block_impl *)_";
3786 else
3787 Constructor += Name + " = _";
3788 Constructor += Name + ";\n";
3789 }
3790 } else {
3791 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00003792 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003793 if (GlobalVarDecl)
3794 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3795 else
3796 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3797 Constructor += " impl.Size = sizeof(";
Steve Naroff54055232008-10-27 17:20:55 +00003798 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3799 if (hasCopyDisposeHelpers)
3800 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3801 }
3802 Constructor += " ";
3803 Constructor += "}\n";
3804 S += Constructor;
3805 S += "};\n";
3806 return S;
3807}
3808
3809void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3810 const char *FunName) {
3811 // Insert closures that were part of the function.
3812 for (unsigned i = 0; i < Blocks.size(); i++) {
3813
3814 CollectBlockDeclRefInfo(Blocks[i]);
3815
3816 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3817
3818 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
3819 ImportedBlockDecls.size() > 0);
3820
3821 InsertText(FunLocStart, CI.c_str(), CI.size());
3822
3823 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
3824
3825 InsertText(FunLocStart, CF.c_str(), CF.size());
3826
3827 if (ImportedBlockDecls.size()) {
3828 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3829 InsertText(FunLocStart, HF.c_str(), HF.size());
3830 }
3831
3832 BlockDeclRefs.clear();
3833 BlockByRefDecls.clear();
3834 BlockByCopyDecls.clear();
3835 BlockCallExprs.clear();
3836 ImportedBlockDecls.clear();
3837 }
3838 Blocks.clear();
3839 RewrittenBlockExprs.clear();
3840}
3841
3842void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3843 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner8ec03f52008-11-24 03:54:41 +00003844 const char *FuncName = FD->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003845
3846 SynthesizeBlockLiterals(FunLocStart, FuncName);
3847}
3848
3849void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00003850 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3851 //SourceLocation FunLocStart = MD->getLocStart();
3852 // FIXME: This hack works around a bug in Rewrite.InsertText().
3853 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattner077bf5e2008-11-24 03:33:13 +00003854 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003855 // Convert colons to underscores.
3856 std::string::size_type loc = 0;
3857 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3858 FuncName.replace(loc, 1, "_");
3859
3860 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3861}
3862
3863void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3864 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3865 CI != E; ++CI)
3866 if (*CI) {
3867 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3868 GetBlockDeclRefExprs(CBE->getBody());
3869 else
3870 GetBlockDeclRefExprs(*CI);
3871 }
3872 // Handle specific things.
3873 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3874 // FIXME: Handle enums.
3875 if (!isa<FunctionDecl>(CDRE->getDecl()))
3876 BlockDeclRefs.push_back(CDRE);
3877 return;
3878}
3879
3880void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3881 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3882 CI != E; ++CI)
3883 if (*CI) {
3884 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3885 GetBlockCallExprs(CBE->getBody());
3886 else
3887 GetBlockCallExprs(*CI);
3888 }
3889
3890 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
3891 if (CE->getCallee()->getType()->isBlockPointerType()) {
3892 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
3893 }
3894 }
3895 return;
3896}
3897
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003898Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00003899 // Navigate to relevant type information.
3900 const char *closureName = 0;
3901 const BlockPointerType *CPT = 0;
3902
3903 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003904 closureName = DRE->getDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003905 CPT = DRE->getType()->getAsBlockPointerType();
3906 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003907 closureName = CDRE->getDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003908 CPT = CDRE->getType()->getAsBlockPointerType();
3909 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003910 closureName = MExpr->getMemberDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003911 CPT = MExpr->getType()->getAsBlockPointerType();
3912 } else {
3913 assert(1 && "RewriteBlockClass: Bad type");
3914 }
3915 assert(CPT && "RewriteBlockClass: Bad type");
3916 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
3917 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00003918 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00003919 // FTP will be null for closures that don't take arguments.
3920
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003921 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
3922 SourceLocation(),
3923 &Context->Idents.get("__block_impl"));
3924 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00003925
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003926 // Generate a funky cast.
3927 llvm::SmallVector<QualType, 8> ArgTypes;
3928
3929 // Push the block argument type.
3930 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00003931 if (FTP) {
Douglas Gregor72564e72009-02-26 23:50:07 +00003932 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003933 E = FTP->arg_type_end(); I && (I != E); ++I) {
3934 QualType t = *I;
3935 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003936 if (isTopLevelBlockPointerType(t)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003937 const BlockPointerType *BPT = t->getAsBlockPointerType();
3938 t = Context->getPointerType(BPT->getPointeeType());
3939 }
3940 ArgTypes.push_back(t);
3941 }
Steve Naroff54055232008-10-27 17:20:55 +00003942 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003943 // Now do the pointer to function cast.
3944 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
3945 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
3946
3947 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Steve Naroff54055232008-10-27 17:20:55 +00003948
Ted Kremenek8189cde2009-02-07 01:47:29 +00003949 CastExpr *BlkCast = new (Context) CStyleCastExpr(PtrBlock, Exp->getCallee(),
3950 PtrBlock, SourceLocation(),
3951 SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003952 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003953 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3954 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003955 //PE->dump();
Steve Naroff54055232008-10-27 17:20:55 +00003956
Douglas Gregor44b43212008-12-11 16:49:14 +00003957 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3958 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003959 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek8189cde2009-02-07 01:47:29 +00003960 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
3961 FD->getType());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003962
Ted Kremenek8189cde2009-02-07 01:47:29 +00003963 CastExpr *FunkCast = new (Context) CStyleCastExpr(PtrToFuncCastType, ME,
3964 PtrToFuncCastType,
3965 SourceLocation(),
3966 SourceLocation());
3967 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003968
3969 llvm::SmallVector<Expr*, 8> BlkExprs;
3970 // Add the implicit argument.
3971 BlkExprs.push_back(BlkCast);
3972 // Add the user arguments.
Steve Naroff54055232008-10-27 17:20:55 +00003973 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3974 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003975 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00003976 }
Ted Kremenek668bf912009-02-09 20:51:47 +00003977 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
3978 BlkExprs.size(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00003979 Exp->getType(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003980 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00003981}
3982
3983void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003984 Stmt *BlockCall = SynthesizeBlockCall(Exp);
3985 ReplaceStmt(Exp, BlockCall);
Steve Naroff54055232008-10-27 17:20:55 +00003986}
3987
Steve Naroff621edce2009-04-29 16:37:50 +00003988// We need to return the rewritten expression to handle cases where the
3989// BlockDeclRefExpr is embedded in another expression being rewritten.
3990// For example:
3991//
3992// int main() {
3993// __block Foo *f;
3994// __block int i;
3995//
3996// void (^myblock)() = ^() {
3997// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
3998// i = 77;
3999// };
4000//}
4001Stmt *RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
Steve Naroff54055232008-10-27 17:20:55 +00004002 // FIXME: Add more elaborate code generation required by the ABI.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004003 Expr *DerefExpr = new (Context) UnaryOperator(BDRE, UnaryOperator::Deref,
Steve Naroffdf8570d2009-02-02 17:19:26 +00004004 Context->getPointerType(BDRE->getType()),
4005 SourceLocation());
4006 // Need parens to enforce precedence.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004007 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), DerefExpr);
Steve Naroffdf8570d2009-02-02 17:19:26 +00004008 ReplaceStmt(BDRE, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00004009 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00004010}
4011
Steve Naroffb2f9e512008-11-03 23:29:32 +00004012void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4013 SourceLocation LocStart = CE->getLParenLoc();
4014 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00004015
4016 // Need to avoid trying to rewrite synthesized casts.
4017 if (LocStart.isInvalid())
4018 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00004019 // Need to avoid trying to rewrite casts contained in macros.
4020 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4021 return;
Steve Narofffa15fd92008-10-28 20:29:00 +00004022
Steve Naroff54055232008-10-27 17:20:55 +00004023 const char *startBuf = SM->getCharacterData(LocStart);
4024 const char *endBuf = SM->getCharacterData(LocEnd);
4025
4026 // advance the location to startArgList.
4027 const char *argPtr = startBuf;
4028
4029 while (*argPtr++ && (argPtr < endBuf)) {
4030 switch (*argPtr) {
4031 case '^':
4032 // Replace the '^' with '*'.
4033 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
4034 ReplaceText(LocStart, 1, "*", 1);
4035 break;
4036 }
4037 }
4038 return;
4039}
4040
4041void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4042 SourceLocation DeclLoc = FD->getLocation();
4043 unsigned parenCount = 0;
4044
4045 // We have 1 or more arguments that have closure pointers.
4046 const char *startBuf = SM->getCharacterData(DeclLoc);
4047 const char *startArgList = strchr(startBuf, '(');
4048
4049 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4050
4051 parenCount++;
4052 // advance the location to startArgList.
4053 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4054 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4055
4056 const char *argPtr = startArgList;
4057
4058 while (*argPtr++ && parenCount) {
4059 switch (*argPtr) {
4060 case '^':
4061 // Replace the '^' with '*'.
4062 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
4063 ReplaceText(DeclLoc, 1, "*", 1);
4064 break;
4065 case '(':
4066 parenCount++;
4067 break;
4068 case ')':
4069 parenCount--;
4070 break;
4071 }
4072 }
4073 return;
4074}
4075
4076bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004077 const FunctionProtoType *FTP;
Steve Naroff54055232008-10-27 17:20:55 +00004078 const PointerType *PT = QT->getAsPointerType();
4079 if (PT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004080 FTP = PT->getPointeeType()->getAsFunctionProtoType();
Steve Naroff54055232008-10-27 17:20:55 +00004081 } else {
4082 const BlockPointerType *BPT = QT->getAsBlockPointerType();
4083 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
Douglas Gregor72564e72009-02-26 23:50:07 +00004084 FTP = BPT->getPointeeType()->getAsFunctionProtoType();
Steve Naroff54055232008-10-27 17:20:55 +00004085 }
4086 if (FTP) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004087 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004088 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004089 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004090 return true;
4091 }
4092 return false;
4093}
4094
Ted Kremenek8189cde2009-02-07 01:47:29 +00004095void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4096 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004097 const char *argPtr = strchr(Name, '(');
4098 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4099
4100 LParen = argPtr; // output the start.
4101 argPtr++; // skip past the left paren.
4102 unsigned parenCount = 1;
4103
4104 while (*argPtr && parenCount) {
4105 switch (*argPtr) {
4106 case '(': parenCount++; break;
4107 case ')': parenCount--; break;
4108 default: break;
4109 }
4110 if (parenCount) argPtr++;
4111 }
4112 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4113 RParen = argPtr; // output the end
4114}
4115
4116void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4117 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4118 RewriteBlockPointerFunctionArgs(FD);
4119 return;
4120 }
4121 // Handle Variables and Typedefs.
4122 SourceLocation DeclLoc = ND->getLocation();
4123 QualType DeclT;
4124 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4125 DeclT = VD->getType();
4126 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4127 DeclT = TDD->getUnderlyingType();
4128 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4129 DeclT = FD->getType();
4130 else
4131 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
4132
4133 const char *startBuf = SM->getCharacterData(DeclLoc);
4134 const char *endBuf = startBuf;
4135 // scan backward (from the decl location) for the end of the previous decl.
4136 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4137 startBuf--;
4138
4139 // *startBuf != '^' if we are dealing with a pointer to function that
4140 // may take block argument types (which will be handled below).
4141 if (*startBuf == '^') {
4142 // Replace the '^' with '*', computing a negative offset.
4143 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4144 ReplaceText(DeclLoc, 1, "*", 1);
4145 }
4146 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4147 // Replace the '^' with '*' for arguments.
4148 DeclLoc = ND->getLocation();
4149 startBuf = SM->getCharacterData(DeclLoc);
4150 const char *argListBegin, *argListEnd;
4151 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4152 while (argListBegin < argListEnd) {
4153 if (*argListBegin == '^') {
4154 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
4155 ReplaceText(CaretLoc, 1, "*", 1);
4156 }
4157 argListBegin++;
4158 }
4159 }
4160 return;
4161}
4162
4163void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4164 // Add initializers for any closure decl refs.
4165 GetBlockDeclRefExprs(Exp->getBody());
4166 if (BlockDeclRefs.size()) {
4167 // Unique all "by copy" declarations.
4168 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4169 if (!BlockDeclRefs[i]->isByRef())
4170 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
4171 // Unique all "by ref" declarations.
4172 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4173 if (BlockDeclRefs[i]->isByRef()) {
4174 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
4175 }
4176 // Find any imported blocks...they will need special attention.
4177 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Steve Naroff47a24222008-12-11 20:51:38 +00004178 if (BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroff00072682008-11-13 17:40:07 +00004179 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff54055232008-10-27 17:20:55 +00004180 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4181 }
4182 }
4183}
4184
Steve Narofffa15fd92008-10-28 20:29:00 +00004185FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4186 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00004187 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Steve Narofffa15fd92008-10-28 20:29:00 +00004188 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Douglas Gregor2224f842009-02-25 16:33:18 +00004189 ID, FType, FunctionDecl::Extern, false,
4190 false);
Steve Narofffa15fd92008-10-28 20:29:00 +00004191}
4192
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004193Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004194 Blocks.push_back(Exp);
4195
4196 CollectBlockDeclRefInfo(Exp);
4197 std::string FuncName;
4198
4199 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00004200 FuncName = CurFunctionDef->getNameAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00004201 else if (CurMethodDef) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00004202 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00004203 // Convert colons to underscores.
4204 std::string::size_type loc = 0;
4205 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4206 FuncName.replace(loc, 1, "_");
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004207 } else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004208 FuncName = std::string(GlobalVarDecl->getNameAsString());
Steve Narofffa15fd92008-10-28 20:29:00 +00004209
4210 std::string BlockNumber = utostr(Blocks.size()-1);
4211
4212 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4213 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4214
4215 // Get a pointer to the function type so we can cast appropriately.
4216 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4217
4218 FunctionDecl *FD;
4219 Expr *NewRep;
4220
4221 // Simulate a contructor call...
4222 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004223 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004224
4225 llvm::SmallVector<Expr*, 4> InitExprs;
4226
Steve Narofffdc03722008-10-29 21:23:59 +00004227 // Initialize the block function.
Steve Narofffa15fd92008-10-28 20:29:00 +00004228 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004229 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4230 SourceLocation());
4231 CastExpr *castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4232 Context->VoidPtrTy, SourceLocation(),
4233 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004234 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00004235
4236 if (ImportedBlockDecls.size()) {
4237 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00004238 FD = SynthBlockInitFunctionDecl(Buf.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004239 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4240 castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4241 Context->VoidPtrTy, SourceLocation(),
4242 SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00004243 InitExprs.push_back(castExpr);
4244
Steve Narofffa15fd92008-10-28 20:29:00 +00004245 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00004246 FD = SynthBlockInitFunctionDecl(Buf.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004247 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4248 castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4249 Context->VoidPtrTy, SourceLocation(),
4250 SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00004251 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00004252 }
4253 // Add initializers for any closure decl refs.
4254 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00004255 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00004256 // Output all "by copy" declarations.
4257 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4258 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004259 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00004260 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner8ec03f52008-11-24 03:54:41 +00004261 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004262 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004263 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004264 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004265 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4266 Exp = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4267 Context->VoidPtrTy, SourceLocation(),
4268 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004269 } else {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004270 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004271 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004272 }
Steve Narofffdc03722008-10-29 21:23:59 +00004273 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004274 }
4275 // Output all "by ref" declarations.
4276 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4277 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004278 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004279 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4280 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Steve Narofffdc03722008-10-29 21:23:59 +00004281 Context->getPointerType(Exp->getType()),
4282 SourceLocation());
Steve Naroff707b0fe2008-11-14 21:36:12 +00004283 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004284 }
4285 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004286 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4287 FType, SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004288 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Steve Narofffa15fd92008-10-28 20:29:00 +00004289 Context->getPointerType(NewRep->getType()),
4290 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004291 NewRep = new (Context) CStyleCastExpr(FType, NewRep, FType, SourceLocation(),
4292 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004293 BlockDeclRefs.clear();
4294 BlockByRefDecls.clear();
4295 BlockByCopyDecls.clear();
4296 ImportedBlockDecls.clear();
4297 return NewRep;
4298}
4299
4300//===----------------------------------------------------------------------===//
4301// Function Body / Expression rewriting
4302//===----------------------------------------------------------------------===//
4303
Steve Naroffc77a6362008-12-04 16:24:46 +00004304// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4305// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4306// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4307// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4308// Since the rewriter isn't capable of rewriting rewritten code, it's important
4309// we get this right.
4310void RewriteObjC::CollectPropertySetters(Stmt *S) {
4311 // Perform a bottom up traversal of all children.
4312 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4313 CI != E; ++CI)
4314 if (*CI)
4315 CollectPropertySetters(*CI);
4316
4317 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4318 if (BinOp->isAssignmentOp()) {
4319 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4320 PropSetters[PRE] = BinOp;
4321 }
4322 }
4323}
4324
Steve Narofffa15fd92008-10-28 20:29:00 +00004325Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4326 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4327 isa<DoStmt>(S) || isa<ForStmt>(S))
4328 Stmts.push_back(S);
4329 else if (isa<ObjCForCollectionStmt>(S)) {
4330 Stmts.push_back(S);
4331 ObjCBcLabelNo.push_back(++BcLabelCount);
4332 }
4333
4334 SourceRange OrigStmtRange = S->getSourceRange();
4335
4336 // Perform a bottom up rewrite of all children.
4337 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4338 CI != E; ++CI)
4339 if (*CI) {
4340 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
4341 if (newStmt)
4342 *CI = newStmt;
4343 }
4344
4345 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4346 // Rewrite the block body in place.
4347 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4348
4349 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004350 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
4351 RewrittenBlockExprs[BE] = Str;
Steve Narofffa15fd92008-10-28 20:29:00 +00004352
4353 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4354 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004355 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00004356 return blockTranscribed;
4357 }
4358 // Handle specific things.
4359 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4360 return RewriteAtEncode(AtEncode);
4361
4362 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4363 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4364
Steve Naroffc77a6362008-12-04 16:24:46 +00004365 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4366 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4367 if (BinOp) {
4368 // Because the rewriter doesn't allow us to rewrite rewritten code,
4369 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00004370 DisableReplaceStmt = true;
4371 // Save the source range. Even if we disable the replacement, the
4372 // rewritten node will have been inserted into the tree. If the synthesized
4373 // node is at the 'end', the rewriter will fail. Consider this:
4374 // self.errorHandler = handler ? handler :
4375 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4376 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00004377 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroffb619d952008-12-09 12:56:34 +00004378 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00004379 //
4380 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4381 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4382 // to see the original expression). Consider this example:
4383 //
4384 // Foo *obj1, *obj2;
4385 //
4386 // obj1.i = [obj2 rrrr];
4387 //
4388 // 'BinOp' for the previous expression looks like:
4389 //
4390 // (BinaryOperator 0x231ccf0 'int' '='
4391 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4392 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4393 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4394 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4395 //
4396 // 'newStmt' represents the rewritten message expression. For example:
4397 //
4398 // (CallExpr 0x231d300 'id':'struct objc_object *'
4399 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4400 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4401 // (CStyleCastExpr 0x231d220 'void *'
4402 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4403 //
4404 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4405 // can be used as the setter argument. ReplaceStmt() will still 'see'
4406 // the original RHS (since we haven't altered BinOp).
4407 //
4408 // This implies the Rewrite* routines can no longer delete the original
4409 // node. As a result, we now leak the original AST nodes.
4410 //
Steve Naroffb619d952008-12-09 12:56:34 +00004411 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00004412 } else {
4413 return RewritePropertyGetter(PropRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00004414 }
4415 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004416 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4417 return RewriteAtSelector(AtSelector);
4418
4419 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4420 return RewriteObjCStringLiteral(AtString);
4421
4422 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00004423#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00004424 // Before we rewrite it, put the original message expression in a comment.
4425 SourceLocation startLoc = MessExpr->getLocStart();
4426 SourceLocation endLoc = MessExpr->getLocEnd();
4427
4428 const char *startBuf = SM->getCharacterData(startLoc);
4429 const char *endBuf = SM->getCharacterData(endLoc);
4430
4431 std::string messString;
4432 messString += "// ";
4433 messString.append(startBuf, endBuf-startBuf+1);
4434 messString += "\n";
4435
4436 // FIXME: Missing definition of
4437 // InsertText(clang::SourceLocation, char const*, unsigned int).
4438 // InsertText(startLoc, messString.c_str(), messString.size());
4439 // Tried this, but it didn't work either...
4440 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00004441#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00004442 return RewriteMessageExpr(MessExpr);
4443 }
4444
4445 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4446 return RewriteObjCTryStmt(StmtTry);
4447
4448 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4449 return RewriteObjCSynchronizedStmt(StmtTry);
4450
4451 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4452 return RewriteObjCThrowStmt(StmtThrow);
4453
4454 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4455 return RewriteObjCProtocolExpr(ProtocolExp);
4456
4457 if (ObjCForCollectionStmt *StmtForCollection =
4458 dyn_cast<ObjCForCollectionStmt>(S))
4459 return RewriteObjCForCollectionStmt(StmtForCollection,
4460 OrigStmtRange.getEnd());
4461 if (BreakStmt *StmtBreakStmt =
4462 dyn_cast<BreakStmt>(S))
4463 return RewriteBreakStmt(StmtBreakStmt);
4464 if (ContinueStmt *StmtContinueStmt =
4465 dyn_cast<ContinueStmt>(S))
4466 return RewriteContinueStmt(StmtContinueStmt);
4467
4468 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4469 // and cast exprs.
4470 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4471 // FIXME: What we're doing here is modifying the type-specifier that
4472 // precedes the first Decl. In the future the DeclGroup should have
4473 // a separate type-specifier that we can rewrite.
4474 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4475
4476 // Blocks rewrite rules.
4477 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4478 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004479 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00004480 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004481 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004482 RewriteBlockPointerDecl(ND);
4483 else if (ND->getType()->isFunctionPointerType())
4484 CheckFunctionPointerDecl(ND->getType(), ND);
4485 }
4486 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004487 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004488 RewriteBlockPointerDecl(TD);
4489 else if (TD->getUnderlyingType()->isFunctionPointerType())
4490 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4491 }
4492 }
4493 }
4494
4495 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4496 RewriteObjCQualifiedInterfaceTypes(CE);
4497
4498 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4499 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4500 assert(!Stmts.empty() && "Statement stack is empty");
4501 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4502 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4503 && "Statement stack mismatch");
4504 Stmts.pop_back();
4505 }
4506 // Handle blocks rewriting.
4507 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4508 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00004509 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00004510 }
4511 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004512 if (CE->getCallee()->getType()->isBlockPointerType()) {
4513 Stmt *BlockCall = SynthesizeBlockCall(CE);
4514 ReplaceStmt(S, BlockCall);
4515 return BlockCall;
4516 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004517 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00004518 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004519 RewriteCastExpr(CE);
4520 }
4521#if 0
4522 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00004523 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004524 // Get the new text.
4525 std::string SStr;
4526 llvm::raw_string_ostream Buf(SStr);
4527 Replacement->printPretty(Buf);
4528 const std::string &Str = Buf.str();
4529
4530 printf("CAST = %s\n", &Str[0]);
4531 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4532 delete S;
4533 return Replacement;
4534 }
4535#endif
4536 // Return this stmt unmodified.
4537 return S;
4538}
4539
4540/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4541/// main file of the input.
4542void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4543 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00004544 if (FD->isOverloadedOperator())
4545 return;
4546
Steve Narofffa15fd92008-10-28 20:29:00 +00004547 // Since function prototypes don't have ParmDecl's, we check the function
4548 // prototype. This enables us to rewrite function declarations and
4549 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00004550 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00004551
Sebastian Redld3a413d2009-04-26 20:35:05 +00004552 // FIXME: If this should support Obj-C++, support CXXTryStmt
4553 if (CompoundStmt *Body = FD->getCompoundBody(*Context)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004554 CurFunctionDef = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004555 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00004556 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00004557 Body =
4558 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4559 FD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00004560 CurrentBody = 0;
4561 if (PropParentMap) {
4562 delete PropParentMap;
4563 PropParentMap = 0;
4564 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004565 // This synthesizes and inserts the block "impl" struct, invoke function,
4566 // and any copy/dispose helper functions.
4567 InsertBlockLiteralsWithinFunction(FD);
4568 CurFunctionDef = 0;
4569 }
4570 return;
4571 }
4572 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Ted Kremenekeaab2062009-03-12 18:33:24 +00004573 if (CompoundStmt *Body = MD->getBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004574 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004575 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00004576 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00004577 Body =
4578 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4579 MD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00004580 CurrentBody = 0;
4581 if (PropParentMap) {
4582 delete PropParentMap;
4583 PropParentMap = 0;
4584 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004585 InsertBlockLiteralsWithinMethod(MD);
4586 CurMethodDef = 0;
4587 }
4588 }
4589 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
4590 ClassImplementation.push_back(CI);
4591 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4592 CategoryImplementation.push_back(CI);
4593 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4594 RewriteForwardClassDecl(CD);
4595 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4596 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004597 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004598 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004599 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004600 CheckFunctionPointerDecl(VD->getType(), VD);
4601 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00004602 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004603 RewriteCastExpr(CE);
4604 }
4605 }
4606 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004607 if (VD->getInit()) {
4608 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004609 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00004610 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004611 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00004612 CurrentBody = 0;
4613 if (PropParentMap) {
4614 delete PropParentMap;
4615 PropParentMap = 0;
4616 }
Douglas Gregor2e1cd422008-11-17 14:58:09 +00004617 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00004618 VD->getNameAsCString());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004619 GlobalVarDecl = 0;
4620
4621 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00004622 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004623 RewriteCastExpr(CE);
4624 }
4625 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004626 return;
4627 }
4628 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004629 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004630 RewriteBlockPointerDecl(TD);
4631 else if (TD->getUnderlyingType()->isFunctionPointerType())
4632 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4633 return;
4634 }
4635 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
4636 if (RD->isDefinition()) {
Douglas Gregor6ab35242009-04-09 21:40:53 +00004637 for (RecordDecl::field_iterator i = RD->field_begin(*Context),
4638 e = RD->field_end(*Context); i != e; ++i) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004639 FieldDecl *FD = *i;
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004640 if (isTopLevelBlockPointerType(FD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004641 RewriteBlockPointerDecl(FD);
4642 }
4643 }
4644 return;
4645 }
4646 // Nothing yet.
4647}
4648
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00004649void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004650 // Get the top-level buffer that this corresponds to.
4651
4652 // Rewrite tabs if we care.
4653 //RewriteTabs();
4654
4655 if (Diags.hasErrorOccurred())
4656 return;
Steve Narofffa15fd92008-10-28 20:29:00 +00004657
4658 RewriteInclude();
4659
Steve Naroff621edce2009-04-29 16:37:50 +00004660 // Here's a great place to add any extra declarations that may be needed.
4661 // Write out meta data for each @protocol(<expr>).
4662 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
4663 E = ProtocolExprDecls.end(); I != E; ++I)
4664 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
4665
Chris Lattner2b2453a2009-01-17 06:22:33 +00004666 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Narofffa15fd92008-10-28 20:29:00 +00004667 Preamble.c_str(), Preamble.size(), false);
Steve Naroff0aab7962008-11-14 14:10:01 +00004668 if (ClassImplementation.size() || CategoryImplementation.size())
4669 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00004670
Steve Narofffa15fd92008-10-28 20:29:00 +00004671 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4672 // we are done.
4673 if (const RewriteBuffer *RewriteBuf =
4674 Rewrite.getRewriteBufferFor(MainFileID)) {
4675 //printf("Changed:\n");
4676 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4677 } else {
4678 fprintf(stderr, "No changes\n");
4679 }
Steve Narofface66252008-11-13 20:07:04 +00004680
Steve Naroff621edce2009-04-29 16:37:50 +00004681 if (ClassImplementation.size() || CategoryImplementation.size() ||
4682 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00004683 // Rewrite Objective-c meta data*
4684 std::string ResultStr;
4685 SynthesizeMetaDataIntoBuffer(ResultStr);
4686 // Emit metadata.
4687 *OutFile << ResultStr;
4688 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004689 OutFile->flush();
4690}
4691