blob: a744ff37427b6a2d14c1a7b49d89298f6500fd7d [file] [log] [blame]
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattnere99c8322007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnere99c8322007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Eli Friedman9f30fc32009-05-18 22:50:54 +000014#include "clang/Frontend/ASTConsumers.h"
Chris Lattner16a0de42007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattnere99c8322007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Steve Naroff1042ff32008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.h"
Chris Lattner16a0de42007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner4431a1b2007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattnerf3a59a12007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Benjamin Kramer89b422c2009-08-23 12:08:50 +000023#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
Chris Lattner211f8b82007-10-25 17:07:24 +000025#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian99e96b02007-10-26 19:46:17 +000026#include "llvm/ADT/SmallPtrSet.h"
Ted Kremenek2d470fc2008-09-13 05:16:45 +000027#include "llvm/ADT/OwningPtr.h"
Chris Lattnere99c8322007-10-11 00:43:27 +000028using namespace clang;
Chris Lattner211f8b82007-10-25 17:07:24 +000029using llvm::utostr;
Chris Lattnere99c8322007-10-11 00:43:27 +000030
Chris Lattnere99c8322007-10-11 00:43:27 +000031namespace {
Steve Naroff1dc53ef2008-04-14 22:03:09 +000032 class RewriteObjC : public ASTConsumer {
Chris Lattner0bd1c972007-10-16 21:07:07 +000033 Rewriter Rewrite;
Chris Lattnere9c810c2007-11-30 22:25:36 +000034 Diagnostic &Diags;
Steve Naroff945a3b12008-03-10 20:43:59 +000035 const LangOptions &LangOpts;
Steve Naroff7b3579b2008-01-30 19:17:43 +000036 unsigned RewriteFailedDiag;
Steve Naroff6d6da252008-12-05 17:03:39 +000037 unsigned TryFinallyContainsReturnDiag;
Mike Stump11289f42009-09-09 15:08:12 +000038
Chris Lattnerc6d91c02007-10-17 22:35:30 +000039 ASTContext *Context;
Chris Lattnere99c8322007-10-11 00:43:27 +000040 SourceManager *SM;
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +000041 TranslationUnitDecl *TUDecl;
Chris Lattnerd32480d2009-01-17 06:22:33 +000042 FileID MainFileID;
Chris Lattnerf3a59a12007-12-02 01:13:47 +000043 const char *MainFileStart, *MainFileEnd;
Chris Lattner0bd1c972007-10-16 21:07:07 +000044 SourceLocation LastIncLoc;
Mike Stump11289f42009-09-09 15:08:12 +000045
Ted Kremenek1b0ea822008-01-07 19:49:32 +000046 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
47 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
48 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Naroff13e74872008-05-06 18:26:51 +000049 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremenek1b0ea822008-01-07 19:49:32 +000050 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
51 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +000052 llvm::SmallVector<Stmt *, 32> Stmts;
53 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffd9803712009-04-29 16:37:50 +000054 // Remember all the @protocol(<expr>) expressions.
55 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Mike Stump11289f42009-09-09 15:08:12 +000056
Steve Naroffce8e8862008-03-15 00:55:56 +000057 unsigned NumObjCStringLiterals;
Mike Stump11289f42009-09-09 15:08:12 +000058
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000059 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff7fa2f042007-11-15 10:28:18 +000060 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +000061 FunctionDecl *MsgSendStretFunctionDecl;
62 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanian4f76f222007-12-03 21:26:48 +000063 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000064 FunctionDecl *GetClassFunctionDecl;
Steve Naroffb2f8ff12007-12-07 03:50:46 +000065 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff574440f2007-10-24 22:48:43 +000066 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff265a6b92007-11-08 14:30:50 +000067 FunctionDecl *CFStringFunctionDecl;
Steve Naroff17978c42008-03-11 17:37:02 +000068 FunctionDecl *SuperContructorFunctionDecl;
Mike Stump11289f42009-09-09 15:08:12 +000069
Steve Naroffa397efd2007-11-03 11:27:19 +000070 // ObjC string constant support.
Steve Naroff08899ff2008-04-15 22:42:06 +000071 VarDecl *ConstantStringClassReference;
Steve Naroffa397efd2007-11-03 11:27:19 +000072 RecordDecl *NSStringRecord;
Mike Stump11289f42009-09-09 15:08:12 +000073
Fariborz Jahanian19d42bf2008-01-16 00:09:11 +000074 // ObjC foreach break/continue generation support.
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +000075 int BcLabelCount;
Mike Stump11289f42009-09-09 15:08:12 +000076
Steve Naroff7fa2f042007-11-15 10:28:18 +000077 // Needed for super.
Steve Naroff677ab3a2008-10-27 17:20:55 +000078 ObjCMethodDecl *CurMethodDef;
Steve Naroff7fa2f042007-11-15 10:28:18 +000079 RecordDecl *SuperStructDecl;
Steve Naroffce8e8862008-03-15 00:55:56 +000080 RecordDecl *ConstantStringDecl;
Mike Stump11289f42009-09-09 15:08:12 +000081
Steve Naroffd9803712009-04-29 16:37:50 +000082 TypeDecl *ProtocolTypeDecl;
83 QualType getProtocolType();
Mike Stump11289f42009-09-09 15:08:12 +000084
Fariborz Jahanian159ee392008-01-18 01:15:54 +000085 // Needed for header files being rewritten
86 bool IsHeader;
Mike Stump11289f42009-09-09 15:08:12 +000087
Steve Narofff9e7c902008-03-28 22:26:09 +000088 std::string InFileName;
Eli Friedman94cf21e2009-05-18 22:20:00 +000089 llvm::raw_ostream* OutFile;
Eli Friedmanf22439a2009-05-18 22:39:16 +000090
91 bool SilenceRewriteMacroWarning;
92
Steve Naroff00a31762008-03-27 22:29:16 +000093 std::string Preamble;
Steve Naroff677ab3a2008-10-27 17:20:55 +000094
95 // Block expressions.
96 llvm::SmallVector<BlockExpr *, 32> Blocks;
97 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
98 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Mike Stump11289f42009-09-09 15:08:12 +000099
Steve Naroff677ab3a2008-10-27 17:20:55 +0000100 // Block related declarations.
101 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
102 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
103 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
104
105 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
106
Steve Naroff4588d0f2008-12-04 16:24:46 +0000107 // This maps a property to it's assignment statement.
108 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Naroff1042ff32008-12-08 16:43:47 +0000109 // This maps a property to it's synthesied message expression.
110 // This allows us to rewrite chained getters (e.g. o.a.b.c).
111 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
Mike Stump11289f42009-09-09 15:08:12 +0000112
Steve Naroff22216db2008-12-04 23:50:32 +0000113 // This maps an original source AST to it's rewritten form. This allows
114 // us to avoid rewriting the same node twice (which is very uncommon).
115 // This is needed to support some of the exotic property rewriting.
116 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Narofff326f402008-12-03 00:56:33 +0000117
Steve Naroff677ab3a2008-10-27 17:20:55 +0000118 FunctionDecl *CurFunctionDef;
Steve Naroffd8907b72008-10-29 18:15:37 +0000119 VarDecl *GlobalVarDecl;
Mike Stump11289f42009-09-09 15:08:12 +0000120
Steve Naroff08628db2008-12-09 12:56:34 +0000121 bool DisableReplaceStmt;
Mike Stump11289f42009-09-09 15:08:12 +0000122
Fariborz Jahanian93191af2007-10-18 19:23:00 +0000123 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnere99c8322007-10-11 00:43:27 +0000124 public:
Ted Kremenek380df932008-05-31 20:11:04 +0000125 virtual void Initialize(ASTContext &context);
126
Chris Lattner3c799d72007-10-24 17:06:59 +0000127 // Top Level Driver code.
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000128 virtual void HandleTopLevelDecl(DeclGroupRef D) {
129 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
130 HandleTopLevelSingleDecl(*I);
131 }
132 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000133 void HandleDeclInMainFile(Decl *D);
Eli Friedman94cf21e2009-05-18 22:20:00 +0000134 RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000135 Diagnostic &D, const LangOptions &LOpts,
136 bool silenceMacroWarn);
Ted Kremenek6231e7e2008-08-08 04:15:52 +0000137
138 ~RewriteObjC() {}
Mike Stump11289f42009-09-09 15:08:12 +0000139
Chris Lattnercf169832009-03-28 04:11:33 +0000140 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump11289f42009-09-09 15:08:12 +0000141
Chris Lattner2e0d2602008-01-31 19:37:57 +0000142 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff22216db2008-12-04 23:50:32 +0000143 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump11289f42009-09-09 15:08:12 +0000144
Steve Naroff22216db2008-12-04 23:50:32 +0000145 if (ReplacingStmt)
146 return; // We can't rewrite the same node twice.
Chris Lattner2e0d2602008-01-31 19:37:57 +0000147
Steve Naroff08628db2008-12-09 12:56:34 +0000148 if (DisableReplaceStmt)
149 return; // Used when rewriting the assignment of a property setter.
150
Steve Naroff22216db2008-12-04 23:50:32 +0000151 // If replacement succeeded or warning disabled return with no warning.
152 if (!Rewrite.ReplaceStmt(Old, New)) {
153 ReplacedNodes[Old] = New;
154 return;
155 }
156 if (SilenceRewriteMacroWarning)
157 return;
Chris Lattner8488c822008-11-18 07:04:44 +0000158 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
159 << Old->getSourceRange();
Chris Lattner2e0d2602008-01-31 19:37:57 +0000160 }
Steve Naroff08628db2008-12-09 12:56:34 +0000161
162 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
163 // Measaure the old text.
164 int Size = Rewrite.getRangeSize(SrcRange);
165 if (Size == -1) {
166 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
167 << Old->getSourceRange();
168 return;
169 }
170 // Get the new text.
171 std::string SStr;
172 llvm::raw_string_ostream S(SStr);
Chris Lattnerc61089a2009-06-30 01:26:17 +0000173 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroff08628db2008-12-09 12:56:34 +0000174 const std::string &Str = S.str();
175
176 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000177 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroff08628db2008-12-09 12:56:34 +0000178 ReplacedNodes[Old] = New;
179 return;
180 }
181 if (SilenceRewriteMacroWarning)
182 return;
183 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
184 << Old->getSourceRange();
185 }
186
Steve Naroff00a31762008-03-27 22:29:16 +0000187 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
188 bool InsertAfter = true) {
Chris Lattner9cc55f52008-01-31 19:51:04 +0000189 // If insertion succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000190 if (!Rewrite.InsertText(Loc, llvm::StringRef(StrData, StrLen),
191 InsertAfter) ||
Chris Lattner1780a852008-01-31 19:42:41 +0000192 SilenceRewriteMacroWarning)
193 return;
Mike Stump11289f42009-09-09 15:08:12 +0000194
Chris Lattner1780a852008-01-31 19:42:41 +0000195 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
196 }
Mike Stump11289f42009-09-09 15:08:12 +0000197
Chris Lattner9cc55f52008-01-31 19:51:04 +0000198 void RemoveText(SourceLocation Loc, unsigned StrLen) {
199 // If removal succeeded or warning disabled return with no warning.
200 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
201 return;
Mike Stump11289f42009-09-09 15:08:12 +0000202
Chris Lattner9cc55f52008-01-31 19:51:04 +0000203 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
204 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000205
Chris Lattner9cc55f52008-01-31 19:51:04 +0000206 void ReplaceText(SourceLocation Start, unsigned OrigLength,
207 const char *NewStr, unsigned NewLength) {
208 // If removal succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000209 if (!Rewrite.ReplaceText(Start, OrigLength,
210 llvm::StringRef(NewStr, NewLength)) ||
Chris Lattner9cc55f52008-01-31 19:51:04 +0000211 SilenceRewriteMacroWarning)
212 return;
Mike Stump11289f42009-09-09 15:08:12 +0000213
Chris Lattner9cc55f52008-01-31 19:51:04 +0000214 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
215 }
Mike Stump11289f42009-09-09 15:08:12 +0000216
Chris Lattner3c799d72007-10-24 17:06:59 +0000217 // Syntactic Rewriting.
Steve Narofff36987c2007-11-04 22:37:50 +0000218 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000219 void RewriteInclude();
Chris Lattner3c799d72007-10-24 17:06:59 +0000220 void RewriteTabs();
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000221 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffc038b3a2008-12-02 17:36:43 +0000222 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
223 ObjCImplementationDecl *IMD,
224 ObjCCategoryImplDecl *CID);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000225 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000226 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000227 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
228 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
229 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
230 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
231 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000232 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000233 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000234 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff873bd842008-07-29 18:15:38 +0000235 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroff50d42052007-11-01 13:24:47 +0000236 bool needToScanForQualifiers(QualType T);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000237 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff7fa2f042007-11-15 10:28:18 +0000238 QualType getSuperStructType();
Steve Naroffce8e8862008-03-15 00:55:56 +0000239 QualType getConstantStringStructType();
Steve Naroffcd92aeb2008-05-31 14:15:04 +0000240 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump11289f42009-09-09 15:08:12 +0000241
Chris Lattner3c799d72007-10-24 17:06:59 +0000242 // Expression Rewriting.
Steve Naroff20113382007-11-09 15:20:18 +0000243 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroff4588d0f2008-12-04 16:24:46 +0000244 void CollectPropertySetters(Stmt *S);
Mike Stump11289f42009-09-09 15:08:12 +0000245
Steve Naroff1042ff32008-12-08 16:43:47 +0000246 Stmt *CurrentBody;
247 ParentMap *PropParentMap; // created lazily.
Mike Stump11289f42009-09-09 15:08:12 +0000248
Chris Lattner69534692007-10-24 16:57:36 +0000249 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner37f5b7d2008-05-23 20:40:52 +0000250 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroff4588d0f2008-12-04 16:24:46 +0000251 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Mike Stump11289f42009-09-09 15:08:12 +0000252 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroff08628db2008-12-09 12:56:34 +0000253 SourceRange SrcRange);
Steve Naroffe4f9b232007-11-05 14:50:49 +0000254 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner69534692007-10-24 16:57:36 +0000255 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffa397efd2007-11-03 11:27:19 +0000256 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian33c0e812007-12-07 18:47:10 +0000257 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffec60b432009-12-05 21:43:12 +0000258 void WarnAboutReturnGotoStmts(Stmt *S);
259 void HasReturnStmts(Stmt *S, bool &hasReturns);
260 void RewriteTryReturnStmts(Stmt *S);
261 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000262 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian284011b2008-01-29 22:59:37 +0000263 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000264 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
265 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
266 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattnera779d692008-01-31 05:10:40 +0000267 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
268 SourceLocation OrigEnd);
Mike Stump11289f42009-09-09 15:08:12 +0000269 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Steve Naroff574440f2007-10-24 22:48:43 +0000270 Expr **args, unsigned nargs);
Fariborz Jahanian965a8962008-01-08 22:06:28 +0000271 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +0000272 Stmt *RewriteBreakStmt(BreakStmt *S);
273 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian965a8962008-01-08 22:06:28 +0000274 void SynthCountByEnumWithState(std::string &buf);
Mike Stump11289f42009-09-09 15:08:12 +0000275
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000276 void SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +0000277 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000278 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +0000279 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000280 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000281 void SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +0000282 void SynthGetMetaClassFunctionDecl();
Fariborz Jahanian31e18502007-12-04 21:47:40 +0000283 void SynthSelGetUidFunctionDecl();
Steve Naroff17978c42008-03-11 17:37:02 +0000284 void SynthSuperContructorFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000285
Chris Lattner3c799d72007-10-24 17:06:59 +0000286 // Metadata emission.
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000287 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000288 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000289
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000290 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000291 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000292
Douglas Gregor29bd76f2009-04-23 01:02:12 +0000293 template<typename MethodIterator>
294 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
295 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +0000296 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +0000297 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +0000298 const char *ClassName,
299 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000300
Steve Naroffd9803712009-04-29 16:37:50 +0000301 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
302 const char *prefix,
303 const char *ClassName,
304 std::string &Result);
305 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Mike Stump11289f42009-09-09 15:08:12 +0000306 const char *prefix,
Steve Naroffd9803712009-04-29 16:37:50 +0000307 const char *ClassName,
308 std::string &Result);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000309 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000310 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000311 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
312 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000313 std::string &Result);
Steve Narofff8cfd162008-11-13 20:07:04 +0000314 void RewriteImplementations();
315 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000316
Steve Naroff677ab3a2008-10-27 17:20:55 +0000317 // Block rewriting.
Mike Stump11289f42009-09-09 15:08:12 +0000318 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000319 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump11289f42009-09-09 15:08:12 +0000320
Steve Naroff677ab3a2008-10-27 17:20:55 +0000321 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
322 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump11289f42009-09-09 15:08:12 +0000323
324 // Block specific rewrite rules.
Steve Naroff677ab3a2008-10-27 17:20:55 +0000325 void RewriteBlockCall(CallExpr *Exp);
326 void RewriteBlockPointerDecl(NamedDecl *VD);
Steve Naroffd9803712009-04-29 16:37:50 +0000327 Stmt *RewriteBlockDeclRefExpr(BlockDeclRefExpr *VD);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000328 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump11289f42009-09-09 15:08:12 +0000329
330 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Steve Naroff677ab3a2008-10-27 17:20:55 +0000331 const char *funcName, std::string Tag);
Mike Stump11289f42009-09-09 15:08:12 +0000332 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Steve Naroff677ab3a2008-10-27 17:20:55 +0000333 const char *funcName, std::string Tag);
Mike Stump11289f42009-09-09 15:08:12 +0000334 std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
Steve Naroff677ab3a2008-10-27 17:20:55 +0000335 bool hasCopyDisposeHelpers);
Steve Naroff350b6652008-10-30 10:07:53 +0000336 Stmt *SynthesizeBlockCall(CallExpr *Exp);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000337 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
338 const char *FunName);
Steve Naroffe70a52a2009-12-05 15:55:59 +0000339 void RewriteRecordBody(RecordDecl *RD);
Mike Stump11289f42009-09-09 15:08:12 +0000340
Steve Naroff677ab3a2008-10-27 17:20:55 +0000341 void CollectBlockDeclRefInfo(BlockExpr *Exp);
342 void GetBlockCallExprs(Stmt *S);
343 void GetBlockDeclRefExprs(Stmt *S);
Mike Stump11289f42009-09-09 15:08:12 +0000344
Steve Naroff677ab3a2008-10-27 17:20:55 +0000345 // We avoid calling Type::isBlockPointerType(), since it operates on the
346 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek5a201952009-02-07 01:47:29 +0000347 bool isTopLevelBlockPointerType(QualType T) {
348 return isa<BlockPointerType>(T);
349 }
Mike Stump11289f42009-09-09 15:08:12 +0000350
Steve Naroff677ab3a2008-10-27 17:20:55 +0000351 // FIXME: This predicate seems like it would be useful to add to ASTContext.
352 bool isObjCType(QualType T) {
353 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
354 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000355
Steve Naroff677ab3a2008-10-27 17:20:55 +0000356 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000357
Steve Naroff677ab3a2008-10-27 17:20:55 +0000358 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
359 OCT == Context->getCanonicalType(Context->getObjCClassType()))
360 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000361
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000362 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +0000363 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Narofffb4330f2009-06-17 22:40:22 +0000364 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff677ab3a2008-10-27 17:20:55 +0000365 return true;
366 }
367 return false;
368 }
369 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek5a201952009-02-07 01:47:29 +0000370 void GetExtentOfArgList(const char *Name, const char *&LParen,
371 const char *&RParen);
Steve Naroffc989a7b2008-11-03 23:29:32 +0000372 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump11289f42009-09-09 15:08:12 +0000373
Steve Narofff4b992a2008-10-28 20:29:00 +0000374 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroffd8907b72008-10-29 18:15:37 +0000375 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Mike Stump11289f42009-09-09 15:08:12 +0000376
Steve Naroffd9803712009-04-29 16:37:50 +0000377 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump11289f42009-09-09 15:08:12 +0000378 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroffd9803712009-04-29 16:37:50 +0000379 if (From[i] == '"')
380 To += "\\\"";
381 else
382 To += From[i];
383 }
384 }
Chris Lattnere99c8322007-10-11 00:43:27 +0000385 };
386}
387
Mike Stump11289f42009-09-09 15:08:12 +0000388void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
389 NamedDecl *D) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000390 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000391 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +0000392 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +0000393 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +0000394 // All the args are checked/rewritten. Don't call twice!
395 RewriteBlockPointerDecl(D);
396 break;
397 }
398 }
399}
400
401void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000402 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +0000403 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000404 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000405}
406
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000407static bool IsHeaderFile(const std::string &Filename) {
408 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump11289f42009-09-09 15:08:12 +0000409
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000410 if (DotPos == std::string::npos) {
411 // no file extension
Mike Stump11289f42009-09-09 15:08:12 +0000412 return false;
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000413 }
Mike Stump11289f42009-09-09 15:08:12 +0000414
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000415 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
416 // C header: .h
417 // C++ header: .hh or .H;
418 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump11289f42009-09-09 15:08:12 +0000419}
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000420
Eli Friedman94cf21e2009-05-18 22:20:00 +0000421RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000422 Diagnostic &D, const LangOptions &LOpts,
423 bool silenceMacroWarn)
424 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
425 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Narofff9e7c902008-03-28 22:26:09 +0000426 IsHeader = IsHeaderFile(inFile);
Mike Stump11289f42009-09-09 15:08:12 +0000427 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Narofff9e7c902008-03-28 22:26:09 +0000428 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump11289f42009-09-09 15:08:12 +0000429 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek5a201952009-02-07 01:47:29 +0000430 "rewriter doesn't support user-specified control flow semantics "
431 "for @try/@finally (code may not execute properly)");
Steve Narofff9e7c902008-03-28 22:26:09 +0000432}
433
Eli Friedmana63ab2d2009-05-18 22:29:17 +0000434ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
435 llvm::raw_ostream* OS,
Mike Stump11289f42009-09-09 15:08:12 +0000436 Diagnostic &Diags,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000437 const LangOptions &LOpts,
438 bool SilenceRewriteMacroWarning) {
439 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere9c810c2007-11-30 22:25:36 +0000440}
Chris Lattnere99c8322007-10-11 00:43:27 +0000441
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000442void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner187f6262008-01-31 19:38:44 +0000443 Context = &context;
444 SM = &Context->getSourceManager();
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +0000445 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner187f6262008-01-31 19:38:44 +0000446 MsgSendFunctionDecl = 0;
447 MsgSendSuperFunctionDecl = 0;
448 MsgSendStretFunctionDecl = 0;
449 MsgSendSuperStretFunctionDecl = 0;
450 MsgSendFpretFunctionDecl = 0;
451 GetClassFunctionDecl = 0;
452 GetMetaClassFunctionDecl = 0;
453 SelGetUidFunctionDecl = 0;
454 CFStringFunctionDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000455 ConstantStringClassReference = 0;
456 NSStringRecord = 0;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000457 CurMethodDef = 0;
458 CurFunctionDef = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000459 GlobalVarDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000460 SuperStructDecl = 0;
Steve Naroffd9803712009-04-29 16:37:50 +0000461 ProtocolTypeDecl = 0;
Steve Naroff60a9ef62008-03-27 22:59:54 +0000462 ConstantStringDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000463 BcLabelCount = 0;
Steve Naroff17978c42008-03-11 17:37:02 +0000464 SuperContructorFunctionDecl = 0;
Steve Naroffce8e8862008-03-15 00:55:56 +0000465 NumObjCStringLiterals = 0;
Steve Narofff1ab6002008-12-08 20:01:41 +0000466 PropParentMap = 0;
467 CurrentBody = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000468 DisableReplaceStmt = false;
Mike Stump11289f42009-09-09 15:08:12 +0000469
Chris Lattner187f6262008-01-31 19:38:44 +0000470 // Get the ID and start/end of the main file.
471 MainFileID = SM->getMainFileID();
472 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
473 MainFileStart = MainBuf->getBufferStart();
474 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000475
Chris Lattner184e65d2009-04-14 23:22:57 +0000476 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump11289f42009-09-09 15:08:12 +0000477
Chris Lattner187f6262008-01-31 19:38:44 +0000478 // declaring objc_selector outside the parameter list removes a silly
479 // scope related warning...
Steve Naroff00a31762008-03-27 22:29:16 +0000480 if (IsHeader)
Steve Narofffcc6fd52009-02-03 20:39:18 +0000481 Preamble = "#pragma once\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000482 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff6ab6dc72008-12-23 20:11:22 +0000483 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroff00a31762008-03-27 22:29:16 +0000484 Preamble += "struct objc_object *superClass; ";
Steve Naroff17978c42008-03-11 17:37:02 +0000485 if (LangOpts.Microsoft) {
486 // Add a constructor for creating temporary objects.
Ted Kremenek5a201952009-02-07 01:47:29 +0000487 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
488 ": ";
Steve Naroff00a31762008-03-27 22:29:16 +0000489 Preamble += "object(o), superClass(s) {} ";
Steve Naroff17978c42008-03-11 17:37:02 +0000490 }
Steve Naroff00a31762008-03-27 22:29:16 +0000491 Preamble += "};\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000492 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
493 Preamble += "typedef struct objc_object Protocol;\n";
494 Preamble += "#define _REWRITER_typedef_Protocol\n";
495 Preamble += "#endif\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000496 if (LangOpts.Microsoft) {
497 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
498 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
499 } else
500 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
501 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroff00a31762008-03-27 22:29:16 +0000502 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000503 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroff00a31762008-03-27 22:29:16 +0000504 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000505 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000506 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000507 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000508 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000509 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroff00a31762008-03-27 22:29:16 +0000510 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000511 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000512 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000513 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000514 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000515 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
516 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
517 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
518 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
519 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroffd30f8c52008-05-09 21:17:56 +0000520 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff8dd15252008-07-16 18:58:11 +0000521 // @synchronized hooks.
Steve Narofff122ff02008-12-08 17:30:33 +0000522 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
523 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
524 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000525 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
526 Preamble += "struct __objcFastEnumerationState {\n\t";
527 Preamble += "unsigned long state;\n\t";
Steve Naroff4dbab8a2008-04-04 22:58:22 +0000528 Preamble += "void **itemsPtr;\n\t";
Steve Naroff00a31762008-03-27 22:29:16 +0000529 Preamble += "unsigned long *mutationsPtr;\n\t";
530 Preamble += "unsigned long extra[5];\n};\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000531 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000532 Preamble += "#define __FASTENUMERATIONSTATE\n";
533 Preamble += "#endif\n";
534 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
535 Preamble += "struct __NSConstantStringImpl {\n";
536 Preamble += " int *isa;\n";
537 Preamble += " int flags;\n";
538 Preamble += " char *str;\n";
539 Preamble += " long length;\n";
540 Preamble += "};\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000541 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
542 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
543 Preamble += "#else\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000544 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000545 Preamble += "#endif\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000546 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
547 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000548 // Blocks preamble.
549 Preamble += "#ifndef BLOCK_IMPL\n";
550 Preamble += "#define BLOCK_IMPL\n";
551 Preamble += "struct __block_impl {\n";
552 Preamble += " void *isa;\n";
553 Preamble += " int Flags;\n";
554 Preamble += " int Size;\n";
555 Preamble += " void *FuncPtr;\n";
556 Preamble += "};\n";
Steve Naroff61d879e2008-12-16 15:50:30 +0000557 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroff287a2bf2009-12-06 01:52:22 +0000558 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000559 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_assign(void *, const void *, const int);\n";
560 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
561 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
562 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
563 Preamble += "#else\n";
564 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
565 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
566 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
567 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
568 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000569 Preamble += "#endif\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000570 if (LangOpts.Microsoft) {
Steve Narofff122ff02008-12-08 17:30:33 +0000571 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
572 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000573 Preamble += "#define __attribute__(X)\n";
574 }
Chris Lattner187f6262008-01-31 19:38:44 +0000575}
576
577
Chris Lattner3c799d72007-10-24 17:06:59 +0000578//===----------------------------------------------------------------------===//
579// Top Level Driver Code
580//===----------------------------------------------------------------------===//
581
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000582void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Chris Lattner0bd1c972007-10-16 21:07:07 +0000583 // Two cases: either the decl could be in the main file, or it could be in a
584 // #included file. If the former, rewrite it now. If the later, check to see
585 // if we rewrote the #include/#import.
586 SourceLocation Loc = D->getLocation();
Chris Lattner8a425862009-01-16 07:36:28 +0000587 Loc = SM->getInstantiationLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000588
Chris Lattner0bd1c972007-10-16 21:07:07 +0000589 // If this is for a builtin, ignore it.
590 if (Loc.isInvalid()) return;
591
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000592 // Look for built-in declarations that we need to refer during the rewrite.
593 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000594 RewriteFunctionDecl(FD);
Steve Naroff08899ff2008-04-15 22:42:06 +0000595 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000596 // declared in <Foundation/NSString.h>
Chris Lattner86d7d912008-11-24 03:54:41 +0000597 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000598 ConstantStringClassReference = FVD;
599 return;
600 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000601 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff161a92b2007-10-26 20:53:56 +0000602 RewriteInterfaceDecl(MD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000603 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000604 RewriteCategoryDecl(CD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000605 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff921385f2007-10-30 16:42:30 +0000606 RewriteProtocolDecl(PD);
Mike Stump11289f42009-09-09 15:08:12 +0000607 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000608 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000609 RewriteForwardProtocolDecl(FP);
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000610 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
611 // Recurse into linkage specifications
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000612 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
613 DIEnd = LSD->decls_end();
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000614 DI != DIEnd; ++DI)
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000615 HandleTopLevelSingleDecl(*DI);
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000616 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000617 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekd61ed3b2008-04-14 21:24:13 +0000618 if (SM->isFromMainFile(Loc))
Chris Lattner0bd1c972007-10-16 21:07:07 +0000619 return HandleDeclInMainFile(D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000620}
621
Chris Lattner3c799d72007-10-24 17:06:59 +0000622//===----------------------------------------------------------------------===//
623// Syntactic (non-AST) Rewriting Code
624//===----------------------------------------------------------------------===//
625
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000626void RewriteObjC::RewriteInclude() {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000627 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000628 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
629 const char *MainBufStart = MainBuf.first;
630 const char *MainBufEnd = MainBuf.second;
631 size_t ImportLen = strlen("import");
632 size_t IncludeLen = strlen("include");
Mike Stump11289f42009-09-09 15:08:12 +0000633
Fariborz Jahanian137d6932008-01-19 01:03:17 +0000634 // Loop over the whole file, looking for includes.
Fariborz Jahanian80258362008-01-19 00:30:35 +0000635 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
636 if (*BufPtr == '#') {
637 if (++BufPtr == MainBufEnd)
638 return;
639 while (*BufPtr == ' ' || *BufPtr == '\t')
640 if (++BufPtr == MainBufEnd)
641 return;
642 if (!strncmp(BufPtr, "import", ImportLen)) {
643 // replace import with include
Mike Stump11289f42009-09-09 15:08:12 +0000644 SourceLocation ImportLoc =
Fariborz Jahanian80258362008-01-19 00:30:35 +0000645 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000646 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000647 BufPtr += ImportLen;
648 }
649 }
650 }
Chris Lattner0bd1c972007-10-16 21:07:07 +0000651}
652
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000653void RewriteObjC::RewriteTabs() {
Chris Lattner3c799d72007-10-24 17:06:59 +0000654 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
655 const char *MainBufStart = MainBuf.first;
656 const char *MainBufEnd = MainBuf.second;
Mike Stump11289f42009-09-09 15:08:12 +0000657
Chris Lattner3c799d72007-10-24 17:06:59 +0000658 // Loop over the whole file, looking for tabs.
659 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
660 if (*BufPtr != '\t')
661 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000662
Chris Lattner3c799d72007-10-24 17:06:59 +0000663 // Okay, we found a tab. This tab will turn into at least one character,
664 // but it depends on which 'virtual column' it is in. Compute that now.
665 unsigned VCol = 0;
666 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
667 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
668 ++VCol;
Mike Stump11289f42009-09-09 15:08:12 +0000669
Chris Lattner3c799d72007-10-24 17:06:59 +0000670 // Okay, now that we know the virtual column, we know how many spaces to
671 // insert. We assume 8-character tab-stops.
672 unsigned Spaces = 8-(VCol & 7);
Mike Stump11289f42009-09-09 15:08:12 +0000673
Chris Lattner3c799d72007-10-24 17:06:59 +0000674 // Get the location of the tab.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000675 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
676 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Mike Stump11289f42009-09-09 15:08:12 +0000677
Chris Lattner3c799d72007-10-24 17:06:59 +0000678 // Rewrite the single tab character into a sequence of spaces.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000679 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattner3c799d72007-10-24 17:06:59 +0000680 }
Chris Lattner16a0de42007-10-11 18:38:32 +0000681}
682
Steve Naroff9af94912008-12-02 15:48:25 +0000683static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
684 ObjCIvarDecl *OID) {
685 std::string S;
686 S = "((struct ";
687 S += ClassDecl->getIdentifier()->getName();
688 S += "_IMPL *)self)->";
Daniel Dunbar70e7ead2009-10-18 20:26:27 +0000689 S += OID->getName();
Steve Naroff9af94912008-12-02 15:48:25 +0000690 return S;
691}
692
Steve Naroffc038b3a2008-12-02 17:36:43 +0000693void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
694 ObjCImplementationDecl *IMD,
695 ObjCCategoryImplDecl *CID) {
Steve Naroffe1908e32008-12-01 20:33:01 +0000696 SourceLocation startLoc = PID->getLocStart();
697 InsertText(startLoc, "// ", 3);
Steve Naroff9af94912008-12-02 15:48:25 +0000698 const char *startBuf = SM->getCharacterData(startLoc);
699 assert((*startBuf == '@') && "bogus @synthesize location");
700 const char *semiBuf = strchr(startBuf, ';');
701 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek5a201952009-02-07 01:47:29 +0000702 SourceLocation onePastSemiLoc =
703 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroff9af94912008-12-02 15:48:25 +0000704
705 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
706 return; // FIXME: is this correct?
Mike Stump11289f42009-09-09 15:08:12 +0000707
Steve Naroff9af94912008-12-02 15:48:25 +0000708 // Generate the 'getter' function.
Steve Naroff9af94912008-12-02 15:48:25 +0000709 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroff9af94912008-12-02 15:48:25 +0000710 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroff9af94912008-12-02 15:48:25 +0000711 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000712
Steve Naroff003d00e2008-12-02 16:05:55 +0000713 if (!OID)
714 return;
Mike Stump11289f42009-09-09 15:08:12 +0000715
Steve Naroff003d00e2008-12-02 16:05:55 +0000716 std::string Getr;
717 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
718 Getr += "{ ";
719 // Synthesize an explicit cast to gain access to the ivar.
Mike Stump11289f42009-09-09 15:08:12 +0000720 // FIXME: deal with code generation implications for various property
721 // attributes (copy, retain, nonatomic).
Steve Naroff06297042008-12-02 17:54:50 +0000722 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroff003d00e2008-12-02 16:05:55 +0000723 Getr += "return " + getIvarAccessString(ClassDecl, OID);
724 Getr += "; }";
Steve Naroff9af94912008-12-02 15:48:25 +0000725 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroff9af94912008-12-02 15:48:25 +0000726 if (PD->isReadOnly())
727 return;
Mike Stump11289f42009-09-09 15:08:12 +0000728
Steve Naroff9af94912008-12-02 15:48:25 +0000729 // Generate the 'setter' function.
730 std::string Setr;
731 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroff9af94912008-12-02 15:48:25 +0000732 Setr += "{ ";
Steve Naroff003d00e2008-12-02 16:05:55 +0000733 // Synthesize an explicit cast to initialize the ivar.
Mike Stump11289f42009-09-09 15:08:12 +0000734 // FIXME: deal with code generation implications for various property
735 // attributes (copy, retain, nonatomic).
Steve Narofff326f402008-12-03 00:56:33 +0000736 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroff003d00e2008-12-02 16:05:55 +0000737 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000738 Setr += PD->getNameAsCString();
Steve Naroff003d00e2008-12-02 16:05:55 +0000739 Setr += "; }";
Steve Naroff9af94912008-12-02 15:48:25 +0000740 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffe1908e32008-12-01 20:33:01 +0000741}
Chris Lattner16a0de42007-10-11 18:38:32 +0000742
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000743void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattner3c799d72007-10-24 17:06:59 +0000744 // Get the start location and compute the semi location.
745 SourceLocation startLoc = ClassDecl->getLocation();
746 const char *startBuf = SM->getCharacterData(startLoc);
747 const char *semiPtr = strchr(startBuf, ';');
Mike Stump11289f42009-09-09 15:08:12 +0000748
Chris Lattner3c799d72007-10-24 17:06:59 +0000749 // Translate to typedef's that forward reference structs with the same name
750 // as the class. As a convenience, we include the original declaration
751 // as a comment.
752 std::string typedefString;
753 typedefString += "// ";
Steve Naroff574440f2007-10-24 22:48:43 +0000754 typedefString.append(startBuf, semiPtr-startBuf+1);
755 typedefString += "\n";
Chris Lattner9ee23b72009-02-20 18:04:31 +0000756 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
757 I != E; ++I) {
Ted Kremenek9b124e12009-11-18 00:28:11 +0000758 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff1b232132007-11-09 12:50:28 +0000759 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000760 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000761 typedefString += "\n";
762 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000763 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000764 typedefString += "\n";
Steve Naroff98eb8d12007-11-05 14:36:37 +0000765 typedefString += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000766 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000767 typedefString += ";\n#endif\n";
Steve Naroff574440f2007-10-24 22:48:43 +0000768 }
Mike Stump11289f42009-09-09 15:08:12 +0000769
Steve Naroff574440f2007-10-24 22:48:43 +0000770 // Replace the @class with typedefs corresponding to the classes.
Mike Stump11289f42009-09-09 15:08:12 +0000771 ReplaceText(startLoc, semiPtr-startBuf+1,
Chris Lattner9cc55f52008-01-31 19:51:04 +0000772 typedefString.c_str(), typedefString.size());
Chris Lattner3c799d72007-10-24 17:06:59 +0000773}
774
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000775void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff3ce37a62007-12-14 23:37:57 +0000776 SourceLocation LocStart = Method->getLocStart();
777 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000778
Chris Lattner88ea93e2009-02-04 01:06:56 +0000779 if (SM->getInstantiationLineNumber(LocEnd) >
780 SM->getInstantiationLineNumber(LocStart)) {
Steve Naroffe020fa12008-10-21 13:37:27 +0000781 InsertText(LocStart, "#if 0\n", 6);
782 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff3ce37a62007-12-14 23:37:57 +0000783 } else {
Chris Lattner1780a852008-01-31 19:42:41 +0000784 InsertText(LocStart, "// ", 3);
Steve Naroff5448cf62007-10-30 13:30:57 +0000785 }
786}
787
Mike Stump11289f42009-09-09 15:08:12 +0000788void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000789 SourceLocation Loc = prop->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000790
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000791 ReplaceText(Loc, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000792
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000793 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahaniane8a30162007-11-07 00:09:37 +0000794}
795
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000796void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000797 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000798
Steve Naroff5448cf62007-10-30 13:30:57 +0000799 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000800 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000801
802 for (ObjCCategoryDecl::instmeth_iterator
803 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000804 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000805 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +0000806 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000807 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000808 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000809 RewriteMethodDeclaration(*I);
810
Steve Naroff5448cf62007-10-30 13:30:57 +0000811 // Lastly, comment out the @end.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000812 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff5448cf62007-10-30 13:30:57 +0000813}
814
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000815void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000816 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Mike Stump11289f42009-09-09 15:08:12 +0000817
Steve Narofff921385f2007-10-30 16:42:30 +0000818 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000819
Steve Narofff921385f2007-10-30 16:42:30 +0000820 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000821 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000822
823 for (ObjCProtocolDecl::instmeth_iterator
824 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000825 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000826 RewriteMethodDeclaration(*I);
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000827 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000828 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000829 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000830 RewriteMethodDeclaration(*I);
831
Steve Narofff921385f2007-10-30 16:42:30 +0000832 // Lastly, comment out the @end.
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000833 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattner9cc55f52008-01-31 19:51:04 +0000834 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroffa509f042007-11-14 15:03:57 +0000835
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000836 // Must comment out @optional/@required
837 const char *startBuf = SM->getCharacterData(LocStart);
838 const char *endBuf = SM->getCharacterData(LocEnd);
839 for (const char *p = startBuf; p < endBuf; p++) {
840 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
841 std::string CommentedOptional = "/* @optional */";
Steve Naroffa509f042007-11-14 15:03:57 +0000842 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000843 ReplaceText(OptionalLoc, strlen("@optional"),
844 CommentedOptional.c_str(), CommentedOptional.size());
Mike Stump11289f42009-09-09 15:08:12 +0000845
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000846 }
847 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
848 std::string CommentedRequired = "/* @required */";
Steve Naroffa509f042007-11-14 15:03:57 +0000849 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000850 ReplaceText(OptionalLoc, strlen("@required"),
851 CommentedRequired.c_str(), CommentedRequired.size());
Mike Stump11289f42009-09-09 15:08:12 +0000852
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000853 }
854 }
Steve Narofff921385f2007-10-30 16:42:30 +0000855}
856
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000857void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000858 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffc17b0562007-11-14 03:37:28 +0000859 if (LocStart.isInvalid())
860 assert(false && "Invalid SourceLocation");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000861 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000862 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000863}
864
Mike Stump11289f42009-09-09 15:08:12 +0000865void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000866 std::string &ResultStr) {
Steve Naroff295570a2008-10-30 12:09:33 +0000867 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroffb067bbd2008-07-16 14:40:40 +0000868 const FunctionType *FPRetType = 0;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000869 ResultStr += "\nstatic ";
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000870 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +0000871 ResultStr += "id";
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000872 else if (OMD->getResultType()->isFunctionPointerType() ||
873 OMD->getResultType()->isBlockPointerType()) {
Steve Naroffb067bbd2008-07-16 14:40:40 +0000874 // needs special handling, since pointer-to-functions have special
875 // syntax (where a decaration models use).
876 QualType retType = OMD->getResultType();
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000877 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000878 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000879 PointeeTy = PT->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000880 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000881 PointeeTy = BPT->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +0000882 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000883 ResultStr += FPRetType->getResultType().getAsString();
884 ResultStr += "(*";
Steve Naroffb067bbd2008-07-16 14:40:40 +0000885 }
886 } else
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +0000887 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian7262fca2008-01-10 01:39:52 +0000888 ResultStr += " ";
Mike Stump11289f42009-09-09 15:08:12 +0000889
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000890 // Unique method name
Fariborz Jahanian56338352007-11-13 21:02:00 +0000891 std::string NameStr;
Mike Stump11289f42009-09-09 15:08:12 +0000892
Douglas Gregorffca3a22009-01-09 17:18:27 +0000893 if (OMD->isInstanceMethod())
Fariborz Jahanian56338352007-11-13 21:02:00 +0000894 NameStr += "_I_";
895 else
896 NameStr += "_C_";
Mike Stump11289f42009-09-09 15:08:12 +0000897
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000898 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +0000899 NameStr += "_";
Mike Stump11289f42009-09-09 15:08:12 +0000900
901 if (ObjCCategoryImplDecl *CID =
Steve Naroff11b387f2009-01-08 19:41:02 +0000902 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000903 NameStr += CID->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +0000904 NameStr += "_";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000905 }
Mike Stump11289f42009-09-09 15:08:12 +0000906 // Append selector names, replacing ':' with '_'
Chris Lattnere4b95692008-11-24 03:33:13 +0000907 {
908 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000909 int len = selString.size();
910 for (int i = 0; i < len; i++)
911 if (selString[i] == ':')
912 selString[i] = '_';
Fariborz Jahanian56338352007-11-13 21:02:00 +0000913 NameStr += selString;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000914 }
Fariborz Jahanian56338352007-11-13 21:02:00 +0000915 // Remember this name for metadata emission
916 MethodInternalNames[OMD] = NameStr;
917 ResultStr += NameStr;
Mike Stump11289f42009-09-09 15:08:12 +0000918
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000919 // Rewrite arguments
920 ResultStr += "(";
Mike Stump11289f42009-09-09 15:08:12 +0000921
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000922 // invisible arguments
Douglas Gregorffca3a22009-01-09 17:18:27 +0000923 if (OMD->isInstanceMethod()) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000924 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000925 selfTy = Context->getPointerType(selfTy);
Steve Naroffdc5b6b22008-03-12 00:25:36 +0000926 if (!LangOpts.Microsoft) {
927 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
928 ResultStr += "struct ";
929 }
930 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000931 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +0000932 ResultStr += " *";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000933 }
934 else
Steve Naroffd9803712009-04-29 16:37:50 +0000935 ResultStr += Context->getObjCClassType().getAsString();
Mike Stump11289f42009-09-09 15:08:12 +0000936
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000937 ResultStr += " self, ";
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000938 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000939 ResultStr += " _cmd";
Mike Stump11289f42009-09-09 15:08:12 +0000940
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000941 // Method arguments.
Chris Lattnera4997152009-02-20 18:43:26 +0000942 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
943 E = OMD->param_end(); PI != E; ++PI) {
944 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000945 ResultStr += ", ";
Steve Naroffdcdcdcd2008-04-18 21:13:19 +0000946 if (PDecl->getType()->isObjCQualifiedIdType()) {
947 ResultStr += "id ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000948 ResultStr += PDecl->getNameAsString();
Steve Naroffdcdcdcd2008-04-18 21:13:19 +0000949 } else {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000950 std::string Name = PDecl->getNameAsString();
Steve Naroffa5c0db82008-12-11 21:05:33 +0000951 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroff44df6a22008-10-30 14:45:29 +0000952 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000953 const BlockPointerType *BPT = PDecl->getType()->getAs<BlockPointerType>();
Douglas Gregor7de59662009-05-29 20:38:28 +0000954 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name,
955 Context->PrintingPolicy);
Steve Naroff44df6a22008-10-30 14:45:29 +0000956 } else
Douglas Gregor7de59662009-05-29 20:38:28 +0000957 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroffdcdcdcd2008-04-18 21:13:19 +0000958 ResultStr += Name;
959 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000960 }
Fariborz Jahanianeab81cd2008-01-21 20:14:23 +0000961 if (OMD->isVariadic())
962 ResultStr += ", ...";
Fariborz Jahanian7262fca2008-01-10 01:39:52 +0000963 ResultStr += ") ";
Mike Stump11289f42009-09-09 15:08:12 +0000964
Steve Naroffb067bbd2008-07-16 14:40:40 +0000965 if (FPRetType) {
966 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump11289f42009-09-09 15:08:12 +0000967
Steve Naroffb067bbd2008-07-16 14:40:40 +0000968 // Now, emit the argument types (if any).
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000969 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroffb067bbd2008-07-16 14:40:40 +0000970 ResultStr += "(";
971 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
972 if (i) ResultStr += ", ";
973 std::string ParamStr = FT->getArgType(i).getAsString();
974 ResultStr += ParamStr;
975 }
976 if (FT->isVariadic()) {
977 if (FT->getNumArgs()) ResultStr += ", ";
978 ResultStr += "...";
979 }
980 ResultStr += ")";
981 } else {
982 ResultStr += "()";
983 }
984 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000985}
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000986void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000987 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
988 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump11289f42009-09-09 15:08:12 +0000989
Fariborz Jahanianc54d8462007-11-13 20:04:28 +0000990 if (IMD)
Chris Lattner1780a852008-01-31 19:42:41 +0000991 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanianc54d8462007-11-13 20:04:28 +0000992 else
Chris Lattner1780a852008-01-31 19:42:41 +0000993 InsertText(CID->getLocStart(), "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000994
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000995 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000996 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
997 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +0000998 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000999 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001000 ObjCMethodDecl *OMD = *I;
1001 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001002 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001003 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redla7b98a72009-04-26 20:35:05 +00001004
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001005 const char *startBuf = SM->getCharacterData(LocStart);
1006 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattner9cc55f52008-01-31 19:51:04 +00001007 ReplaceText(LocStart, endBuf-startBuf,
1008 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001009 }
Mike Stump11289f42009-09-09 15:08:12 +00001010
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001011 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001012 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1013 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001014 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001015 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001016 ObjCMethodDecl *OMD = *I;
1017 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001018 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001019 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +00001020
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001021 const char *startBuf = SM->getCharacterData(LocStart);
1022 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattner9cc55f52008-01-31 19:51:04 +00001023 ReplaceText(LocStart, endBuf-startBuf,
Mike Stump11289f42009-09-09 15:08:12 +00001024 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001025 }
Steve Naroffe1908e32008-12-01 20:33:01 +00001026 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001027 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001028 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001029 I != E; ++I) {
Steve Naroffc038b3a2008-12-02 17:36:43 +00001030 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffe1908e32008-12-01 20:33:01 +00001031 }
1032
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001033 if (IMD)
Chris Lattner1780a852008-01-31 19:42:41 +00001034 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001035 else
Mike Stump11289f42009-09-09 15:08:12 +00001036 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001037}
1038
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001039void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffc5484042007-10-30 02:23:23 +00001040 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001041 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff2f55b982007-11-01 03:35:41 +00001042 // we haven't seen a forward decl - generate a typedef.
Steve Naroff03f27672007-11-14 23:02:56 +00001043 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001044 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001045 ResultStr += "\n";
1046 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001047 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001048 ResultStr += "\n";
Steve Naroffa1e115e2008-03-10 23:16:54 +00001049 ResultStr += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001050 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001051 ResultStr += ";\n#endif\n";
Steve Naroff2f55b982007-11-01 03:35:41 +00001052 // Mark this typedef as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001053 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff2f55b982007-11-01 03:35:41 +00001054 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001055 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump11289f42009-09-09 15:08:12 +00001056
1057 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001058 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff0c0f5ba2009-01-11 01:06:09 +00001059 RewriteProperty(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001060 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001061 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001062 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001063 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001064 for (ObjCInterfaceDecl::classmeth_iterator
1065 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001066 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001067 RewriteMethodDeclaration(*I);
1068
Steve Naroff4cd61ac2007-10-30 03:43:13 +00001069 // Lastly, comment out the @end.
Chris Lattner9cc55f52008-01-31 19:51:04 +00001070 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff161a92b2007-10-26 20:53:56 +00001071}
1072
Steve Naroff08628db2008-12-09 12:56:34 +00001073Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1074 SourceRange SrcRange) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00001075 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1076 // This allows us to reuse all the fun and games in SynthMessageExpr().
1077 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1078 ObjCMessageExpr *MsgExpr;
1079 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1080 llvm::SmallVector<Expr *, 1> ExprVec;
1081 ExprVec.push_back(newStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001082
Steve Naroff1042ff32008-12-08 16:43:47 +00001083 Stmt *Receiver = PropRefExpr->getBase();
1084 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1085 if (PRE && PropGetters[PRE]) {
1086 // This allows us to handle chain/nested property getters.
1087 Receiver = PropGetters[PRE];
1088 }
Mike Stump11289f42009-09-09 15:08:12 +00001089 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1090 PDecl->getSetterName(), PDecl->getType(),
1091 PDecl->getSetterMethodDecl(),
1092 SourceLocation(), SourceLocation(),
Steve Naroff4588d0f2008-12-04 16:24:46 +00001093 &ExprVec[0], 1);
1094 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001095
Steve Naroff4588d0f2008-12-04 16:24:46 +00001096 // Now do the actual rewrite.
Steve Naroff08628db2008-12-09 12:56:34 +00001097 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffdf705772008-12-10 14:53:27 +00001098 //delete BinOp;
Ted Kremenek5a201952009-02-07 01:47:29 +00001099 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1100 // to things that stay around.
1101 Context->Deallocate(MsgExpr);
Steve Naroff4588d0f2008-12-04 16:24:46 +00001102 return ReplacingStmt;
Steve Narofff326f402008-12-03 00:56:33 +00001103}
1104
Steve Naroff4588d0f2008-12-04 16:24:46 +00001105Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Narofff326f402008-12-03 00:56:33 +00001106 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1107 // This allows us to reuse all the fun and games in SynthMessageExpr().
1108 ObjCMessageExpr *MsgExpr;
1109 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
Mike Stump11289f42009-09-09 15:08:12 +00001110
Steve Naroff1042ff32008-12-08 16:43:47 +00001111 Stmt *Receiver = PropRefExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00001112
Steve Naroff1042ff32008-12-08 16:43:47 +00001113 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1114 if (PRE && PropGetters[PRE]) {
1115 // This allows us to handle chain/nested property getters.
1116 Receiver = PropGetters[PRE];
1117 }
Mike Stump11289f42009-09-09 15:08:12 +00001118 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1119 PDecl->getGetterName(), PDecl->getType(),
1120 PDecl->getGetterMethodDecl(),
1121 SourceLocation(), SourceLocation(),
Steve Narofff326f402008-12-03 00:56:33 +00001122 0, 0);
1123
Steve Naroff22216db2008-12-04 23:50:32 +00001124 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001125
1126 if (!PropParentMap)
1127 PropParentMap = new ParentMap(CurrentBody);
1128
1129 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1130 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1131 // We stash away the ReplacingStmt since actually doing the
1132 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1133 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek5a201952009-02-07 01:47:29 +00001134 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1135 // to things that stay around.
1136 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001137 return PropRefExpr; // return the original...
1138 } else {
1139 ReplaceStmt(PropRefExpr, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001140 // delete PropRefExpr; elsewhere...
Ted Kremenek5a201952009-02-07 01:47:29 +00001141 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1142 // to things that stay around.
1143 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001144 return ReplacingStmt;
1145 }
Steve Narofff326f402008-12-03 00:56:33 +00001146}
1147
Mike Stump11289f42009-09-09 15:08:12 +00001148Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001149 SourceLocation OrigStart) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001150 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff677ab3a2008-10-27 17:20:55 +00001151 if (CurMethodDef) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001152 if (const PointerType *pType = IV->getBase()->getType()->getAs<PointerType>()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001153 ObjCInterfaceType *iFaceDecl =
1154 dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroffb1c02372008-05-08 17:52:16 +00001155 // lookup which class implements the instance variable.
1156 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001157 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001158 clsDeclared);
Steve Naroffb1c02372008-05-08 17:52:16 +00001159 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001160
Steve Naroffb1c02372008-05-08 17:52:16 +00001161 // Synthesize an explicit cast to gain access to the ivar.
1162 std::string RecName = clsDeclared->getIdentifier()->getName();
1163 RecName += "_IMPL";
1164 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001165 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001166 SourceLocation(), II);
Steve Naroffb1c02372008-05-08 17:52:16 +00001167 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1168 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Mike Stump11289f42009-09-09 15:08:12 +00001169 CastExpr *castExpr = new (Context) CStyleCastExpr(castT,
Anders Carlssona2615922009-07-31 00:48:10 +00001170 CastExpr::CK_Unknown,
1171 IV->getBase(),
1172 castT,SourceLocation(),
1173 SourceLocation());
Steve Naroffb1c02372008-05-08 17:52:16 +00001174 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001175 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1176 IV->getBase()->getLocEnd(),
1177 castExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001178 if (IV->isFreeIvar() &&
Steve Naroff677ab3a2008-10-27 17:20:55 +00001179 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001180 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1181 IV->getLocation(),
1182 D->getType());
Steve Naroffb1c02372008-05-08 17:52:16 +00001183 ReplaceStmt(IV, ME);
Steve Naroff22216db2008-12-04 23:50:32 +00001184 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb1c02372008-05-08 17:52:16 +00001185 return ME;
Steve Naroff05caa482007-11-15 11:33:00 +00001186 }
Mike Stump11289f42009-09-09 15:08:12 +00001187
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001188 ReplaceStmt(IV->getBase(), PE);
1189 // Cannot delete IV->getBase(), since PE points to it.
1190 // Replace the old base with the cast. This is important when doing
1191 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001192 IV->setBase(PE);
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001193 return IV;
Steve Naroff05caa482007-11-15 11:33:00 +00001194 }
Steve Naroff24840f62008-04-18 21:55:08 +00001195 } else { // we are outside a method.
Steve Naroff29ce4e52008-05-06 23:20:07 +00001196 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump11289f42009-09-09 15:08:12 +00001197
Steve Naroff29ce4e52008-05-06 23:20:07 +00001198 // Explicit ivar refs need to have a cast inserted.
1199 // FIXME: consider sharing some of this code with the code above.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001200 if (const PointerType *pType = IV->getBase()->getType()->getAs<PointerType>()) {
Steve Naroffb1c02372008-05-08 17:52:16 +00001201 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001202 // lookup which class implements the instance variable.
1203 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001204 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001205 clsDeclared);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001206 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001207
Steve Naroff29ce4e52008-05-06 23:20:07 +00001208 // Synthesize an explicit cast to gain access to the ivar.
1209 std::string RecName = clsDeclared->getIdentifier()->getName();
1210 RecName += "_IMPL";
1211 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001212 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001213 SourceLocation(), II);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001214 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1215 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Mike Stump11289f42009-09-09 15:08:12 +00001216 CastExpr *castExpr = new (Context) CStyleCastExpr(castT,
Anders Carlssona2615922009-07-31 00:48:10 +00001217 CastExpr::CK_Unknown,
1218 IV->getBase(),
Ted Kremenek5a201952009-02-07 01:47:29 +00001219 castT, SourceLocation(),
1220 SourceLocation());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001221 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001222 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner34873d22008-05-28 16:38:23 +00001223 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001224 ReplaceStmt(IV->getBase(), PE);
1225 // Cannot delete IV->getBase(), since PE points to it.
1226 // Replace the old base with the cast. This is important when doing
1227 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001228 IV->setBase(PE);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001229 return IV;
1230 }
Steve Naroff05caa482007-11-15 11:33:00 +00001231 }
Steve Naroff24840f62008-04-18 21:55:08 +00001232 return IV;
Steve Narofff60782b2007-11-15 02:58:25 +00001233}
1234
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001235/// SynthCountByEnumWithState - To print:
1236/// ((unsigned int (*)
1237/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001238/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001239/// sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001240/// "countByEnumeratingWithState:objects:count:"),
1241/// &enumState,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001242/// (id *)items, (unsigned int)16)
1243///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001244void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001245 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1246 "id *, unsigned int))(void *)objc_msgSend)";
1247 buf += "\n\t\t";
1248 buf += "((id)l_collection,\n\t\t";
1249 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1250 buf += "\n\t\t";
1251 buf += "&enumState, "
1252 "(id *)items, (unsigned int)16)";
1253}
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001254
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001255/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1256/// statement to exit to its outer synthesized loop.
1257///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001258Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001259 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1260 return S;
1261 // replace break with goto __break_label
1262 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001263
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001264 SourceLocation startLoc = S->getLocStart();
1265 buf = "goto __break_label_";
1266 buf += utostr(ObjCBcLabelNo.back());
Chris Lattner9cc55f52008-01-31 19:51:04 +00001267 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001268
1269 return 0;
1270}
1271
1272/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1273/// statement to continue with its inner synthesized loop.
1274///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001275Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001276 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1277 return S;
1278 // replace continue with goto __continue_label
1279 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001280
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001281 SourceLocation startLoc = S->getLocStart();
1282 buf = "goto __continue_label_";
1283 buf += utostr(ObjCBcLabelNo.back());
Chris Lattner9cc55f52008-01-31 19:51:04 +00001284 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001285
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001286 return 0;
1287}
1288
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001289/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001290/// It rewrites:
1291/// for ( type elem in collection) { stmts; }
Mike Stump11289f42009-09-09 15:08:12 +00001292
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001293/// Into:
1294/// {
Mike Stump11289f42009-09-09 15:08:12 +00001295/// type elem;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001296/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001297/// id items[16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001298/// id l_collection = (id)collection;
Mike Stump11289f42009-09-09 15:08:12 +00001299/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001300/// objects:items count:16];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001301/// if (limit) {
1302/// unsigned long startMutations = *enumState.mutationsPtr;
1303/// do {
1304/// unsigned long counter = 0;
1305/// do {
Mike Stump11289f42009-09-09 15:08:12 +00001306/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001307/// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001308/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001309/// stmts;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001310/// __continue_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001311/// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001312/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001313/// objects:items count:16]);
1314/// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001315/// __break_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001316/// }
1317/// else
1318/// elem = nil;
1319/// }
1320///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001321Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattnera779d692008-01-31 05:10:40 +00001322 SourceLocation OrigEnd) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001323 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001324 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001325 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump11289f42009-09-09 15:08:12 +00001326 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001327 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001328
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001329 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001330 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001331 const char *elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001332 std::string elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001333 std::string buf;
1334 buf = "\n{\n\t";
1335 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1336 // type elem;
Chris Lattner529efc72009-03-28 06:33:19 +00001337 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek292b3842008-10-06 22:16:13 +00001338 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001339 if (ElementType->isObjCQualifiedIdType() ||
1340 ElementType->isObjCQualifiedInterfaceType())
1341 // Simply use 'id' for all qualified types.
1342 elementTypeAsString = "id";
1343 else
1344 elementTypeAsString = ElementType.getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001345 buf += elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001346 buf += " ";
Chris Lattner86d7d912008-11-24 03:54:41 +00001347 elementName = D->getNameAsCString();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001348 buf += elementName;
1349 buf += ";\n\t";
1350 }
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001351 else {
1352 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner86d7d912008-11-24 03:54:41 +00001353 elementName = DR->getDecl()->getNameAsCString();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001354 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1355 if (VD->getType()->isObjCQualifiedIdType() ||
1356 VD->getType()->isObjCQualifiedInterfaceType())
1357 // Simply use 'id' for all qualified types.
1358 elementTypeAsString = "id";
1359 else
1360 elementTypeAsString = VD->getType().getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001361 }
Mike Stump11289f42009-09-09 15:08:12 +00001362
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001363 // struct __objcFastEnumerationState enumState = { 0 };
1364 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1365 // id items[16];
1366 buf += "id items[16];\n\t";
1367 // id l_collection = (id)
1368 buf += "id l_collection = (id)";
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001369 // Find start location of 'collection' the hard way!
1370 const char *startCollectionBuf = startBuf;
1371 startCollectionBuf += 3; // skip 'for'
1372 startCollectionBuf = strchr(startCollectionBuf, '(');
1373 startCollectionBuf++; // skip '('
1374 // find 'in' and skip it.
1375 while (*startCollectionBuf != ' ' ||
1376 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1377 (*(startCollectionBuf+3) != ' ' &&
1378 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1379 startCollectionBuf++;
1380 startCollectionBuf += 3;
Mike Stump11289f42009-09-09 15:08:12 +00001381
1382 // Replace: "for (type element in" with string constructed thus far.
Chris Lattner9cc55f52008-01-31 19:51:04 +00001383 ReplaceText(startLoc, startCollectionBuf - startBuf,
1384 buf.c_str(), buf.size());
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001385 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001386 SourceLocation rightParenLoc = S->getRParenLoc();
1387 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1388 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001389 buf = ";\n\t";
Mike Stump11289f42009-09-09 15:08:12 +00001390
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001391 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1392 // objects:items count:16];
1393 // which is synthesized into:
Mike Stump11289f42009-09-09 15:08:12 +00001394 // unsigned int limit =
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001395 // ((unsigned int (*)
1396 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001397 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001398 // sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001399 // "countByEnumeratingWithState:objects:count:"),
1400 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001401 // (id *)items, (unsigned int)16);
1402 buf += "unsigned long limit =\n\t\t";
1403 SynthCountByEnumWithState(buf);
1404 buf += ";\n\t";
1405 /// if (limit) {
1406 /// unsigned long startMutations = *enumState.mutationsPtr;
1407 /// do {
1408 /// unsigned long counter = 0;
1409 /// do {
Mike Stump11289f42009-09-09 15:08:12 +00001410 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001411 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001412 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001413 buf += "if (limit) {\n\t";
1414 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1415 buf += "do {\n\t\t";
1416 buf += "unsigned long counter = 0;\n\t\t";
1417 buf += "do {\n\t\t\t";
1418 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1419 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1420 buf += elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001421 buf += " = (";
1422 buf += elementTypeAsString;
1423 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001424 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattner9cc55f52008-01-31 19:51:04 +00001425 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001426
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001427 /// __continue_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001428 /// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001429 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001430 /// objects:items count:16]);
1431 /// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001432 /// __break_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001433 /// }
1434 /// else
1435 /// elem = nil;
1436 /// }
Mike Stump11289f42009-09-09 15:08:12 +00001437 ///
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001438 buf = ";\n\t";
1439 buf += "__continue_label_";
1440 buf += utostr(ObjCBcLabelNo.back());
1441 buf += ": ;";
1442 buf += "\n\t\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001443 buf += "} while (counter < limit);\n\t";
1444 buf += "} while (limit = ";
1445 SynthCountByEnumWithState(buf);
1446 buf += ");\n\t";
1447 buf += elementName;
Steve Naroffd1a36792008-12-17 14:24:39 +00001448 buf += " = ((id)0);\n\t";
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001449 buf += "__break_label_";
1450 buf += utostr(ObjCBcLabelNo.back());
1451 buf += ": ;\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001452 buf += "}\n\t";
1453 buf += "else\n\t\t";
1454 buf += elementName;
Steve Naroffd1a36792008-12-17 14:24:39 +00001455 buf += " = ((id)0);\n";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001456 buf += "}\n";
Mike Stump11289f42009-09-09 15:08:12 +00001457
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001458 // Insert all these *after* the statement body.
Sebastian Redla7b98a72009-04-26 20:35:05 +00001459 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Narofff0ff8792008-07-21 18:26:02 +00001460 if (isa<CompoundStmt>(S->getBody())) {
1461 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1462 InsertText(endBodyLoc, buf.c_str(), buf.size());
1463 } else {
1464 /* Need to treat single statements specially. For example:
1465 *
1466 * for (A *a in b) if (stuff()) break;
1467 * for (A *a in b) xxxyy;
1468 *
1469 * The following code simply scans ahead to the semi to find the actual end.
1470 */
1471 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1472 const char *semiBuf = strchr(stmtBuf, ';');
1473 assert(semiBuf && "Can't find ';'");
1474 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1475 InsertText(endBodyLoc, buf.c_str(), buf.size());
1476 }
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001477 Stmts.pop_back();
1478 ObjCBcLabelNo.pop_back();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001479 return 0;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001480}
1481
Mike Stump11289f42009-09-09 15:08:12 +00001482/// RewriteObjCSynchronizedStmt -
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001483/// This routine rewrites @synchronized(expr) stmt;
1484/// into:
1485/// objc_sync_enter(expr);
1486/// @try stmt @finally { objc_sync_exit(expr); }
1487///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001488Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001489 // Get the start location and compute the semi location.
1490 SourceLocation startLoc = S->getLocStart();
1491 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001492
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001493 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump11289f42009-09-09 15:08:12 +00001494
1495 std::string buf;
Steve Naroffb2fc0522008-08-21 13:03:03 +00001496 buf = "objc_sync_enter((id)";
1497 const char *lparenBuf = startBuf;
1498 while (*lparenBuf != '(') lparenBuf++;
1499 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001500 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1501 // the sync expression is typically a message expression that's already
Steve Naroffad7013b2008-08-19 13:04:19 +00001502 // been rewritten! (which implies the SourceLocation's are invalid).
1503 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001504 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffad7013b2008-08-19 13:04:19 +00001505 while (*endBuf != ')') endBuf--;
1506 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001507 buf = ");\n";
1508 // declare a new scope with two variables, _stack and _rethrow.
1509 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1510 buf += "int buf[18/*32-bit i386*/];\n";
1511 buf += "char *pointers[4];} _stack;\n";
1512 buf += "id volatile _rethrow = 0;\n";
1513 buf += "objc_exception_try_enter(&_stack);\n";
1514 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001515 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001516 startLoc = S->getSynchBody()->getLocEnd();
1517 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001518
Steve Naroffad7013b2008-08-19 13:04:19 +00001519 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001520 SourceLocation lastCurlyLoc = startLoc;
1521 buf = "}\nelse {\n";
1522 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroffd9803712009-04-29 16:37:50 +00001523 buf += "}\n";
1524 buf += "{ /* implicit finally clause */\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001525 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffec60b432009-12-05 21:43:12 +00001526
1527 std::string syncBuf;
1528 syncBuf += " objc_sync_exit(";
Mike Stump11289f42009-09-09 15:08:12 +00001529 Expr *syncExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00001530 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00001531 S->getSynchExpr(),
Ted Kremenek5a201952009-02-07 01:47:29 +00001532 Context->getObjCIdType(),
1533 SourceLocation(),
1534 SourceLocation());
Ted Kremenek2d470fc2008-09-13 05:16:45 +00001535 std::string syncExprBufS;
1536 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00001537 syncExpr->printPretty(syncExprBuf, *Context, 0,
1538 PrintingPolicy(LangOpts));
Steve Naroffec60b432009-12-05 21:43:12 +00001539 syncBuf += syncExprBuf.str();
1540 syncBuf += ");";
1541
1542 buf += syncBuf;
1543 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001544 buf += "}\n";
1545 buf += "}";
Mike Stump11289f42009-09-09 15:08:12 +00001546
Chris Lattner9cc55f52008-01-31 19:51:04 +00001547 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffec60b432009-12-05 21:43:12 +00001548
1549 bool hasReturns = false;
1550 HasReturnStmts(S->getSynchBody(), hasReturns);
1551 if (hasReturns)
1552 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1553
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001554 return 0;
1555}
1556
Steve Naroffec60b432009-12-05 21:43:12 +00001557void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1558{
Steve Naroff6d6da252008-12-05 17:03:39 +00001559 // Perform a bottom up traversal of all children.
1560 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1561 CI != E; ++CI)
1562 if (*CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001563 WarnAboutReturnGotoStmts(*CI);
Steve Naroff6d6da252008-12-05 17:03:39 +00001564
Steve Naroffec60b432009-12-05 21:43:12 +00001565 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump11289f42009-09-09 15:08:12 +00001566 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff6d6da252008-12-05 17:03:39 +00001567 TryFinallyContainsReturnDiag);
1568 }
1569 return;
1570}
1571
Steve Naroffec60b432009-12-05 21:43:12 +00001572void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1573{
1574 // Perform a bottom up traversal of all children.
1575 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1576 CI != E; ++CI)
1577 if (*CI)
1578 HasReturnStmts(*CI, hasReturns);
1579
1580 if (isa<ReturnStmt>(S))
1581 hasReturns = true;
1582 return;
1583}
1584
1585void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1586 // Perform a bottom up traversal of all children.
1587 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1588 CI != E; ++CI)
1589 if (*CI) {
1590 RewriteTryReturnStmts(*CI);
1591 }
1592 if (isa<ReturnStmt>(S)) {
1593 SourceLocation startLoc = S->getLocStart();
1594 const char *startBuf = SM->getCharacterData(startLoc);
1595
1596 const char *semiBuf = strchr(startBuf, ';');
1597 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1598 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1599
1600 std::string buf;
1601 buf = "{ objc_exception_try_exit(&_stack); return";
1602
1603 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1604 InsertText(onePastSemiLoc, "}", 1);
1605 }
1606 return;
1607}
1608
1609void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1610 // Perform a bottom up traversal of all children.
1611 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1612 CI != E; ++CI)
1613 if (*CI) {
1614 RewriteSyncReturnStmts(*CI, syncExitBuf);
1615 }
1616 if (isa<ReturnStmt>(S)) {
1617 SourceLocation startLoc = S->getLocStart();
1618 const char *startBuf = SM->getCharacterData(startLoc);
1619
1620 const char *semiBuf = strchr(startBuf, ';');
1621 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1622 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1623
1624 std::string buf;
1625 buf = "{ objc_exception_try_exit(&_stack);";
1626 buf += syncExitBuf;
1627 buf += " return";
1628
1629 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1630 InsertText(onePastSemiLoc, "}", 1);
1631 }
1632 return;
1633}
1634
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001635Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001636 // Get the start location and compute the semi location.
1637 SourceLocation startLoc = S->getLocStart();
1638 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001639
Steve Naroffbf478ec2007-11-07 04:08:17 +00001640 assert((*startBuf == '@') && "bogus @try location");
1641
1642 std::string buf;
1643 // declare a new scope with two variables, _stack and _rethrow.
1644 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1645 buf += "int buf[18/*32-bit i386*/];\n";
1646 buf += "char *pointers[4];} _stack;\n";
1647 buf += "id volatile _rethrow = 0;\n";
1648 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff16018582007-11-07 18:43:40 +00001649 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffbf478ec2007-11-07 04:08:17 +00001650
Chris Lattner9cc55f52008-01-31 19:51:04 +00001651 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001652
Steve Naroffbf478ec2007-11-07 04:08:17 +00001653 startLoc = S->getTryBody()->getLocEnd();
1654 startBuf = SM->getCharacterData(startLoc);
1655
1656 assert((*startBuf == '}') && "bogus @try block");
Mike Stump11289f42009-09-09 15:08:12 +00001657
Steve Naroffbf478ec2007-11-07 04:08:17 +00001658 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffce2dca12008-07-16 15:31:30 +00001659 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1660 if (catchList) {
1661 startLoc = startLoc.getFileLocWithOffset(1);
1662 buf = " /* @catch begin */ else {\n";
1663 buf += " id _caught = objc_exception_extract(&_stack);\n";
1664 buf += " objc_exception_try_enter (&_stack);\n";
1665 buf += " if (_setjmp(_stack.buf))\n";
1666 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1667 buf += " else { /* @catch continue */";
Mike Stump11289f42009-09-09 15:08:12 +00001668
Steve Naroffce2dca12008-07-16 15:31:30 +00001669 InsertText(startLoc, buf.c_str(), buf.size());
Steve Narofffac18fe2008-09-09 19:59:12 +00001670 } else { /* no catch list */
1671 buf = "}\nelse {\n";
1672 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1673 buf += "}";
1674 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffce2dca12008-07-16 15:31:30 +00001675 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001676 bool sawIdTypedCatch = false;
1677 Stmt *lastCatchBody = 0;
Steve Naroffbf478ec2007-11-07 04:08:17 +00001678 while (catchList) {
Steve Naroff371b8fb2009-03-03 19:52:17 +00001679 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001680
Mike Stump11289f42009-09-09 15:08:12 +00001681 if (catchList == S->getCatchStmts())
Steve Naroffbf478ec2007-11-07 04:08:17 +00001682 buf = "if ("; // we are generating code for the first catch clause
1683 else
1684 buf = "else if (";
1685 startLoc = catchList->getLocStart();
1686 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001687
Steve Naroffbf478ec2007-11-07 04:08:17 +00001688 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump11289f42009-09-09 15:08:12 +00001689
Steve Naroffbf478ec2007-11-07 04:08:17 +00001690 const char *lParenLoc = strchr(startBuf, '(');
1691
Steve Naroffe6b7ffd2008-02-01 22:08:12 +00001692 if (catchList->hasEllipsis()) {
Steve Naroffedb5bc62008-02-01 20:02:07 +00001693 // Now rewrite the body...
1694 lastCatchBody = catchList->getCatchBody();
Steve Naroffedb5bc62008-02-01 20:02:07 +00001695 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1696 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001697 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1698 "bogus @catch paren location");
Steve Naroffedb5bc62008-02-01 20:02:07 +00001699 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001700
Steve Naroffedb5bc62008-02-01 20:02:07 +00001701 buf += "1) { id _tmp = _caught;";
Daniel Dunbardec484a2009-08-19 19:10:30 +00001702 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff371b8fb2009-03-03 19:52:17 +00001703 } else if (catchDecl) {
1704 QualType t = catchDecl->getType();
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001705 if (t == Context->getObjCIdType()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001706 buf += "1) { ";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001707 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001708 sawIdTypedCatch = true;
Mike Stump11289f42009-09-09 15:08:12 +00001709 } else if (const PointerType *pType = t->getAs<PointerType>()) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001710 ObjCInterfaceType *cls; // Should be a pointer to a class.
Mike Stump11289f42009-09-09 15:08:12 +00001711
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001712 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001713 if (cls) {
Steve Naroff16018582007-11-07 18:43:40 +00001714 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001715 buf += cls->getDecl()->getNameAsString();
Steve Naroff16018582007-11-07 18:43:40 +00001716 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001717 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001718 }
1719 }
1720 // Now rewrite the body...
1721 lastCatchBody = catchList->getCatchBody();
1722 SourceLocation rParenLoc = catchList->getRParenLoc();
1723 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1724 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1725 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1726 assert((*rParenBuf == ')') && "bogus @catch paren location");
1727 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001728
Steve Naroffbf478ec2007-11-07 04:08:17 +00001729 buf = " = _caught;";
Mike Stump11289f42009-09-09 15:08:12 +00001730 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroffbf478ec2007-11-07 04:08:17 +00001731 // declares the @catch parameter).
Chris Lattner9cc55f52008-01-31 19:51:04 +00001732 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff371b8fb2009-03-03 19:52:17 +00001733 } else {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001734 assert(false && "@catch rewrite bug");
Steve Naroffa733c7f2007-11-07 15:32:26 +00001735 }
Steve Naroffedb5bc62008-02-01 20:02:07 +00001736 // make sure all the catch bodies get rewritten!
Steve Naroffbf478ec2007-11-07 04:08:17 +00001737 catchList = catchList->getNextCatchStmt();
1738 }
1739 // Complete the catch list...
1740 if (lastCatchBody) {
1741 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001742 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1743 "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001744
Steve Naroff4adbe312008-09-11 15:29:03 +00001745 // Insert the last (implicit) else clause *before* the right curly brace.
1746 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1747 buf = "} /* last catch end */\n";
1748 buf += "else {\n";
1749 buf += " _rethrow = _caught;\n";
1750 buf += " objc_exception_try_exit(&_stack);\n";
1751 buf += "} } /* @catch end */\n";
1752 if (!S->getFinallyStmt())
1753 buf += "}\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001754 InsertText(bodyLoc, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001755
Steve Naroffbf478ec2007-11-07 04:08:17 +00001756 // Set lastCurlyLoc
1757 lastCurlyLoc = lastCatchBody->getLocEnd();
1758 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001759 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001760 startLoc = finalStmt->getLocStart();
1761 startBuf = SM->getCharacterData(startLoc);
1762 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump11289f42009-09-09 15:08:12 +00001763
Steve Naroffbf478ec2007-11-07 04:08:17 +00001764 buf = "/* @finally */";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001765 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001766
Steve Naroffbf478ec2007-11-07 04:08:17 +00001767 Stmt *body = finalStmt->getFinallyBody();
1768 SourceLocation startLoc = body->getLocStart();
1769 SourceLocation endLoc = body->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001770 assert(*SM->getCharacterData(startLoc) == '{' &&
1771 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001772 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001773 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001774
Steve Naroffbf478ec2007-11-07 04:08:17 +00001775 startLoc = startLoc.getFileLocWithOffset(1);
1776 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001777 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001778 endLoc = endLoc.getFileLocWithOffset(-1);
1779 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001780 InsertText(endLoc, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001781
Steve Naroffbf478ec2007-11-07 04:08:17 +00001782 // Set lastCurlyLoc
1783 lastCurlyLoc = body->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00001784
Steve Naroff6d6da252008-12-05 17:03:39 +00001785 // Now check for any return/continue/go statements within the @try.
Steve Naroffec60b432009-12-05 21:43:12 +00001786 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff4adbe312008-09-11 15:29:03 +00001787 } else { /* no finally clause - make sure we synthesize an implicit one */
1788 buf = "{ /* implicit finally clause */\n";
1789 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1790 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1791 buf += "}";
1792 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffec60b432009-12-05 21:43:12 +00001793
1794 // Now check for any return/continue/go statements within the @try.
1795 // The implicit finally clause won't called if the @try contains any
1796 // jump statements.
1797 bool hasReturns = false;
1798 HasReturnStmts(S->getTryBody(), hasReturns);
1799 if (hasReturns)
1800 RewriteTryReturnStmts(S->getTryBody());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001801 }
1802 // Now emit the final closing curly brace...
1803 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1804 buf = " } /* @try scope end */\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001805 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001806 return 0;
1807}
1808
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001809Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001810 return 0;
1811}
1812
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001813Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001814 return 0;
1815}
1816
Mike Stump11289f42009-09-09 15:08:12 +00001817// This can't be done with ReplaceStmt(S, ThrowExpr), since
1818// the throw expression is typically a message expression that's already
Steve Naroffa733c7f2007-11-07 15:32:26 +00001819// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001820Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroffa733c7f2007-11-07 15:32:26 +00001821 // Get the start location and compute the semi location.
1822 SourceLocation startLoc = S->getLocStart();
1823 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001824
Steve Naroffa733c7f2007-11-07 15:32:26 +00001825 assert((*startBuf == '@') && "bogus @throw location");
1826
1827 std::string buf;
1828 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffc7d2df22008-01-19 00:42:38 +00001829 if (S->getThrowExpr())
1830 buf = "objc_exception_throw(";
1831 else // add an implicit argument
1832 buf = "objc_exception_throw(_caught";
Mike Stump11289f42009-09-09 15:08:12 +00001833
Steve Naroff29788342008-07-25 15:41:30 +00001834 // handle "@ throw" correctly.
1835 const char *wBuf = strchr(startBuf, 'w');
1836 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1837 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001838
Steve Naroffa733c7f2007-11-07 15:32:26 +00001839 const char *semiBuf = strchr(startBuf, ';');
1840 assert((*semiBuf == ';') && "@throw: can't find ';'");
1841 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1842 buf = ");";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001843 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroffa733c7f2007-11-07 15:32:26 +00001844 return 0;
1845}
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001846
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001847Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerc6d91c02007-10-17 22:35:30 +00001848 // Create a new string expression.
1849 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlssond8499822007-10-29 05:01:08 +00001850 std::string StrEncoding;
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00001851 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00001852 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
1853 StrEncoding.length(), false,StrType,
1854 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00001855 ReplaceStmt(Exp, Replacement);
Mike Stump11289f42009-09-09 15:08:12 +00001856
Chris Lattner4431a1b2007-11-30 22:53:43 +00001857 // Replace this subexpr in the parent.
Steve Naroff22216db2008-12-04 23:50:32 +00001858 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattner69534692007-10-24 16:57:36 +00001859 return Replacement;
Chris Lattnera7c19fe2007-10-16 22:36:42 +00001860}
1861
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001862Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff2654e182008-12-22 22:16:07 +00001863 if (!SelGetUidFunctionDecl)
1864 SynthSelGetUidFunctionDecl();
Steve Naroffe4f9b232007-11-05 14:50:49 +00001865 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1866 // Create a call to sel_registerName("selName").
1867 llvm::SmallVector<Expr*, 8> SelExprs;
1868 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00001869 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00001870 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00001871 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00001872 false, argType, SourceLocation()));
Steve Naroffe4f9b232007-11-05 14:50:49 +00001873 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1874 &SelExprs[0], SelExprs.size());
Chris Lattner2e0d2602008-01-31 19:37:57 +00001875 ReplaceStmt(Exp, SelExp);
Steve Naroff22216db2008-12-04 23:50:32 +00001876 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffe4f9b232007-11-05 14:50:49 +00001877 return SelExp;
1878}
1879
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001880CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff574440f2007-10-24 22:48:43 +00001881 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001882 // Get the type, we will need to reference it in a couple spots.
Steve Naroff574440f2007-10-24 22:48:43 +00001883 QualType msgSendType = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001884
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001885 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek5a201952009-02-07 01:47:29 +00001886 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001887
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001888 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattner3c799d72007-10-24 17:06:59 +00001889 QualType pToFunc = Context->getPointerType(msgSendType);
Mike Stump11289f42009-09-09 15:08:12 +00001890 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc,
Anders Carlssona2615922009-07-31 00:48:10 +00001891 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00001892 DRE,
Douglas Gregora11693b2008-11-12 17:17:38 +00001893 /*isLvalue=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001894
John McCall9dd450b2009-09-21 23:43:11 +00001895 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00001896
Ted Kremenekd7b4f402009-02-09 20:51:47 +00001897 return new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
1898 SourceLocation());
Steve Naroff574440f2007-10-24 22:48:43 +00001899}
1900
Steve Naroff50d42052007-11-01 13:24:47 +00001901static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1902 const char *&startRef, const char *&endRef) {
1903 while (startBuf < endBuf) {
1904 if (*startBuf == '<')
1905 startRef = startBuf; // mark the start.
1906 if (*startBuf == '>') {
Steve Naroff1b232132007-11-09 12:50:28 +00001907 if (startRef && *startRef == '<') {
1908 endRef = startBuf; // mark the end.
1909 return true;
1910 }
1911 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00001912 }
1913 startBuf++;
1914 }
1915 return false;
1916}
1917
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001918static void scanToNextArgument(const char *&argRef) {
1919 int angle = 0;
1920 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1921 if (*argRef == '<')
1922 angle++;
1923 else if (*argRef == '>')
1924 angle--;
1925 argRef++;
1926 }
1927 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1928}
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00001929
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001930bool RewriteObjC::needToScanForQualifiers(QualType T) {
Steve Naroffc277ad12009-07-18 15:33:26 +00001931 return T->isObjCQualifiedIdType() || T->isObjCQualifiedInterfaceType();
Steve Naroff50d42052007-11-01 13:24:47 +00001932}
1933
Steve Naroff873bd842008-07-29 18:15:38 +00001934void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1935 QualType Type = E->getType();
1936 if (needToScanForQualifiers(Type)) {
Steve Naroffdbfc6932008-11-19 21:15:47 +00001937 SourceLocation Loc, EndLoc;
Mike Stump11289f42009-09-09 15:08:12 +00001938
Steve Naroffdbfc6932008-11-19 21:15:47 +00001939 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1940 Loc = ECE->getLParenLoc();
1941 EndLoc = ECE->getRParenLoc();
1942 } else {
1943 Loc = E->getLocStart();
1944 EndLoc = E->getLocEnd();
1945 }
1946 // This will defend against trying to rewrite synthesized expressions.
1947 if (Loc.isInvalid() || EndLoc.isInvalid())
1948 return;
1949
Steve Naroff873bd842008-07-29 18:15:38 +00001950 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffdbfc6932008-11-19 21:15:47 +00001951 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff873bd842008-07-29 18:15:38 +00001952 const char *startRef = 0, *endRef = 0;
1953 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1954 // Get the locations of the startRef, endRef.
1955 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1956 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1957 // Comment out the protocol references.
1958 InsertText(LessLoc, "/*", 2);
1959 InsertText(GreaterLoc, "*/", 2);
1960 }
1961 }
1962}
1963
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001964void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001965 SourceLocation Loc;
1966 QualType Type;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001967 const FunctionProtoType *proto = 0;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001968 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1969 Loc = VD->getLocation();
1970 Type = VD->getType();
1971 }
1972 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1973 Loc = FD->getLocation();
1974 // Check for ObjC 'id' and class types that have been adorned with protocol
1975 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall9dd450b2009-09-21 23:43:11 +00001976 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001977 assert(funcType && "missing function type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001978 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001979 if (!proto)
1980 return;
1981 Type = proto->getResultType();
1982 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00001983 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
1984 Loc = FD->getLocation();
1985 Type = FD->getType();
1986 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001987 else
1988 return;
Mike Stump11289f42009-09-09 15:08:12 +00001989
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001990 if (needToScanForQualifiers(Type)) {
Steve Naroff50d42052007-11-01 13:24:47 +00001991 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00001992
Steve Naroff50d42052007-11-01 13:24:47 +00001993 const char *endBuf = SM->getCharacterData(Loc);
1994 const char *startBuf = endBuf;
Steve Naroff930e0992008-05-31 05:02:17 +00001995 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroff50d42052007-11-01 13:24:47 +00001996 startBuf--; // scan backward (from the decl location) for return type.
1997 const char *startRef = 0, *endRef = 0;
1998 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1999 // Get the locations of the startRef, endRef.
2000 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2001 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2002 // Comment out the protocol references.
Chris Lattner1780a852008-01-31 19:42:41 +00002003 InsertText(LessLoc, "/*", 2);
2004 InsertText(GreaterLoc, "*/", 2);
Steve Naroff37e011c2007-10-31 04:38:33 +00002005 }
2006 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002007 if (!proto)
2008 return; // most likely, was a variable
Steve Naroff50d42052007-11-01 13:24:47 +00002009 // Now check arguments.
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002010 const char *startBuf = SM->getCharacterData(Loc);
2011 const char *startFuncBuf = startBuf;
Steve Naroff50d42052007-11-01 13:24:47 +00002012 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2013 if (needToScanForQualifiers(proto->getArgType(i))) {
2014 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002015
Steve Naroff50d42052007-11-01 13:24:47 +00002016 const char *endBuf = startBuf;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002017 // scan forward (from the decl location) for argument types.
2018 scanToNextArgument(endBuf);
Steve Naroff50d42052007-11-01 13:24:47 +00002019 const char *startRef = 0, *endRef = 0;
2020 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2021 // Get the locations of the startRef, endRef.
Mike Stump11289f42009-09-09 15:08:12 +00002022 SourceLocation LessLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002023 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump11289f42009-09-09 15:08:12 +00002024 SourceLocation GreaterLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002025 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002026 // Comment out the protocol references.
Chris Lattner1780a852008-01-31 19:42:41 +00002027 InsertText(LessLoc, "/*", 2);
2028 InsertText(GreaterLoc, "*/", 2);
Steve Naroff50d42052007-11-01 13:24:47 +00002029 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002030 startBuf = ++endBuf;
2031 }
2032 else {
Steve Naroffc884aa82008-08-06 15:58:23 +00002033 // If the function name is derived from a macro expansion, then the
2034 // argument buffer will not follow the name. Need to speak with Chris.
2035 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002036 startBuf++; // scan forward (from the decl location) for argument types.
2037 startBuf++;
2038 }
Steve Naroff50d42052007-11-01 13:24:47 +00002039 }
Steve Naroff37e011c2007-10-31 04:38:33 +00002040}
2041
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002042// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002043void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002044 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2045 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002046 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002047 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002048 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002049 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002050 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002051 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002052 SelGetUidIdent, getFuncType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002053 FunctionDecl::Extern, false);
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002054}
2055
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002056void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002057 // declared in <objc/objc.h>
Douglas Gregor1e21c192009-01-09 01:47:02 +00002058 if (FD->getIdentifier() &&
2059 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002060 SelGetUidFunctionDecl = FD;
Steve Naroff37e011c2007-10-31 04:38:33 +00002061 return;
2062 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002063 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002064}
2065
Steve Naroff17978c42008-03-11 17:37:02 +00002066// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002067void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroff17978c42008-03-11 17:37:02 +00002068 if (SuperContructorFunctionDecl)
2069 return;
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002070 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroff17978c42008-03-11 17:37:02 +00002071 llvm::SmallVector<QualType, 16> ArgTys;
2072 QualType argT = Context->getObjCIdType();
2073 assert(!argT.isNull() && "Can't find 'id' type");
2074 ArgTys.push_back(argT);
2075 ArgTys.push_back(argT);
2076 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2077 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002078 false, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002079 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002080 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002081 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002082 FunctionDecl::Extern, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002083}
2084
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002085// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002086void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002087 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2088 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002089 QualType argT = Context->getObjCIdType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002090 assert(!argT.isNull() && "Can't find 'id' type");
2091 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002092 argT = Context->getObjCSelType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002093 assert(!argT.isNull() && "Can't find 'SEL' type");
2094 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002095 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002096 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002097 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002098 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002099 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002100 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002101 FunctionDecl::Extern, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002102}
2103
Steve Naroff7fa2f042007-11-15 10:28:18 +00002104// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002105void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002106 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2107 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002108 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002109 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002110 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002111 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2112 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2113 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002114 argT = Context->getObjCSelType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002115 assert(!argT.isNull() && "Can't find 'SEL' type");
2116 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002117 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff7fa2f042007-11-15 10:28:18 +00002118 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002119 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002120 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002121 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002122 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002123 FunctionDecl::Extern, false);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002124}
2125
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002126// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002127void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002128 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2129 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002130 QualType argT = Context->getObjCIdType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002131 assert(!argT.isNull() && "Can't find 'id' type");
2132 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002133 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002134 assert(!argT.isNull() && "Can't find 'SEL' type");
2135 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002136 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002137 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002138 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002139 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002140 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002141 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002142 FunctionDecl::Extern, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002143}
2144
Mike Stump11289f42009-09-09 15:08:12 +00002145// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002146// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002147void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump11289f42009-09-09 15:08:12 +00002148 IdentifierInfo *msgSendIdent =
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002149 &Context->Idents.get("objc_msgSendSuper_stret");
2150 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002151 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002152 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002153 &Context->Idents.get("objc_super"));
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002154 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2155 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2156 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002157 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002158 assert(!argT.isNull() && "Can't find 'SEL' type");
2159 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002160 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002161 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002162 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002163 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002164 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002165 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002166 FunctionDecl::Extern, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002167}
2168
Steve Naroff2e4e3852008-05-08 22:02:18 +00002169// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002170void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002171 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2172 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002173 QualType argT = Context->getObjCIdType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002174 assert(!argT.isNull() && "Can't find 'id' type");
2175 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002176 argT = Context->getObjCSelType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002177 assert(!argT.isNull() && "Can't find 'SEL' type");
2178 ArgTys.push_back(argT);
Steve Naroff2e4e3852008-05-08 22:02:18 +00002179 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002180 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002181 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002182 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002183 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002184 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002185 FunctionDecl::Extern, false);
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002186}
2187
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002188// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002189void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002190 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2191 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002192 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002193 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002194 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002195 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002196 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002197 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002198 getClassIdent, getClassType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002199 FunctionDecl::Extern, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002200}
2201
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002202// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002203void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002204 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2205 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002206 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002207 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002208 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002209 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002210 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002211 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002212 getClassIdent, getClassType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002213 FunctionDecl::Extern, false);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002214}
2215
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002216Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffce8e8862008-03-15 00:55:56 +00002217 QualType strType = getConstantStringStructType();
2218
2219 std::string S = "__NSConstantStringImpl_";
Steve Naroffa6141f02008-05-31 03:35:42 +00002220
2221 std::string tmpName = InFileName;
2222 unsigned i;
2223 for (i=0; i < tmpName.length(); i++) {
2224 char c = tmpName.at(i);
2225 // replace any non alphanumeric characters with '_'.
2226 if (!isalpha(c) && (c < '0' || c > '9'))
2227 tmpName[i] = '_';
2228 }
2229 S += tmpName;
2230 S += "_";
Steve Naroffce8e8862008-03-15 00:55:56 +00002231 S += utostr(NumObjCStringLiterals++);
2232
Steve Naroff00a31762008-03-27 22:29:16 +00002233 Preamble += "static __NSConstantStringImpl " + S;
2234 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2235 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffce8e8862008-03-15 00:55:56 +00002236 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek2d470fc2008-09-13 05:16:45 +00002237 std::string prettyBufS;
2238 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00002239 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2240 PrintingPolicy(LangOpts));
Steve Naroff00a31762008-03-27 22:29:16 +00002241 Preamble += prettyBuf.str();
2242 Preamble += ",";
Steve Naroff94ed6dc2009-12-06 01:48:44 +00002243 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002244
2245 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2246 &Context->Idents.get(S.c_str()), strType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002247 VarDecl::Static);
Ted Kremenek5a201952009-02-07 01:47:29 +00002248 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2249 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002250 Context->getPointerType(DRE->getType()),
Steve Naroffce8e8862008-03-15 00:55:56 +00002251 SourceLocation());
Steve Naroff265a6b92007-11-08 14:30:50 +00002252 // cast to NSConstantString *
Mike Stump11289f42009-09-09 15:08:12 +00002253 CastExpr *cast = new (Context) CStyleCastExpr(Exp->getType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002254 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002255 Unop, Exp->getType(),
2256 SourceLocation(),
Anders Carlssona2615922009-07-31 00:48:10 +00002257 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002258 ReplaceStmt(Exp, cast);
Steve Naroff22216db2008-12-04 23:50:32 +00002259 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff265a6b92007-11-08 14:30:50 +00002260 return cast;
Steve Naroffa397efd2007-11-03 11:27:19 +00002261}
2262
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002263ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002264 // check if we are sending a message to 'super'
Douglas Gregorffca3a22009-01-09 17:18:27 +00002265 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002266
Douglas Gregor8ea1f532008-11-04 14:56:14 +00002267 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
Mike Stump11289f42009-09-09 15:08:12 +00002268 const ObjCObjectPointerType *OPT =
John McCall9dd450b2009-09-21 23:43:11 +00002269 Super->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00002270 assert(OPT);
2271 const ObjCInterfaceType *IT = OPT->getInterfaceType();
Chris Lattnera9b3cae2008-06-21 18:04:54 +00002272 return IT->getDecl();
2273 }
2274 return 0;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002275}
2276
2277// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002278QualType RewriteObjC::getSuperStructType() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002279 if (!SuperStructDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002280 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002281 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002282 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002283 QualType FieldTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002284
Steve Naroff7fa2f042007-11-15 10:28:18 +00002285 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002286 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002287 // struct objc_class *super;
Mike Stump11289f42009-09-09 15:08:12 +00002288 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor91f84212008-12-11 16:49:14 +00002289
Steve Naroff7fa2f042007-11-15 10:28:18 +00002290 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002291 for (unsigned i = 0; i < 2; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002292 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2293 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002294 FieldTypes[i], 0,
2295 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002296 /*Mutable=*/false));
Douglas Gregor91f84212008-12-11 16:49:14 +00002297 }
Mike Stump11289f42009-09-09 15:08:12 +00002298
Douglas Gregor91f84212008-12-11 16:49:14 +00002299 SuperStructDecl->completeDefinition(*Context);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002300 }
2301 return Context->getTagDeclType(SuperStructDecl);
2302}
2303
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002304QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffce8e8862008-03-15 00:55:56 +00002305 if (!ConstantStringDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002306 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002307 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002308 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffce8e8862008-03-15 00:55:56 +00002309 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002310
Steve Naroffce8e8862008-03-15 00:55:56 +00002311 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002312 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffce8e8862008-03-15 00:55:56 +00002313 // int flags;
Mike Stump11289f42009-09-09 15:08:12 +00002314 FieldTypes[1] = Context->IntTy;
Steve Naroffce8e8862008-03-15 00:55:56 +00002315 // char *str;
Mike Stump11289f42009-09-09 15:08:12 +00002316 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffce8e8862008-03-15 00:55:56 +00002317 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002318 FieldTypes[3] = Context->LongTy;
Douglas Gregor91f84212008-12-11 16:49:14 +00002319
Steve Naroffce8e8862008-03-15 00:55:56 +00002320 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002321 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002322 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2323 ConstantStringDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002324 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002325 FieldTypes[i], 0,
Douglas Gregor91f84212008-12-11 16:49:14 +00002326 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002327 /*Mutable=*/true));
Douglas Gregor91f84212008-12-11 16:49:14 +00002328 }
2329
2330 ConstantStringDecl->completeDefinition(*Context);
Steve Naroffce8e8862008-03-15 00:55:56 +00002331 }
2332 return Context->getTagDeclType(ConstantStringDecl);
2333}
2334
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002335Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002336 if (!SelGetUidFunctionDecl)
2337 SynthSelGetUidFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002338 if (!MsgSendFunctionDecl)
2339 SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002340 if (!MsgSendSuperFunctionDecl)
2341 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002342 if (!MsgSendStretFunctionDecl)
2343 SynthMsgSendStretFunctionDecl();
2344 if (!MsgSendSuperStretFunctionDecl)
2345 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002346 if (!MsgSendFpretFunctionDecl)
2347 SynthMsgSendFpretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002348 if (!GetClassFunctionDecl)
2349 SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002350 if (!GetMetaClassFunctionDecl)
2351 SynthGetMetaClassFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002352
Steve Naroff7fa2f042007-11-15 10:28:18 +00002353 // default to objc_msgSend().
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002354 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2355 // May need to use objc_msgSend_stret() as well.
2356 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroffd9803712009-04-29 16:37:50 +00002357 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2358 QualType resultType = mDecl->getResultType();
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002359 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002360 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002361 else if (resultType->isRealFloatingType())
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002362 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002363 }
Mike Stump11289f42009-09-09 15:08:12 +00002364
Steve Naroff574440f2007-10-24 22:48:43 +00002365 // Synthesize a call to objc_msgSend().
2366 llvm::SmallVector<Expr*, 8> MsgExprs;
2367 IdentifierInfo *clsName = Exp->getClassName();
Mike Stump11289f42009-09-09 15:08:12 +00002368
Steve Naroff574440f2007-10-24 22:48:43 +00002369 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2370 if (clsName) { // class message.
Steve Naroff6c79f972008-07-24 19:44:33 +00002371 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2372 // the 'super' idiom within a class method.
Daniel Dunbar07d07852009-10-18 21:17:35 +00002373 if (clsName->getName() == "super") {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002374 MsgSendFlavor = MsgSendSuperFunctionDecl;
2375 if (MsgSendStretFlavor)
2376 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2377 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002378
2379 ObjCInterfaceDecl *SuperDecl =
Steve Naroff677ab3a2008-10-27 17:20:55 +00002380 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002381
2382 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002383
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002384 // set the receiver to self, the first argument to all methods.
Steve Naroffd9803712009-04-29 16:37:50 +00002385 InitExprs.push_back(
Mike Stump11289f42009-09-09 15:08:12 +00002386 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002387 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002388 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroffd9803712009-04-29 16:37:50 +00002389 Context->getObjCIdType(),
2390 SourceLocation()),
2391 Context->getObjCIdType(),
2392 SourceLocation(), SourceLocation())); // set the 'receiver'.
2393
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002394 llvm::SmallVector<Expr*, 8> ClsExprs;
2395 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002396 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002397 SuperDecl->getIdentifier()->getNameStart(),
2398 SuperDecl->getIdentifier()->getLength(),
2399 false, argType, SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002400 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002401 &ClsExprs[0],
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002402 ClsExprs.size());
2403 // To turn off a warning, type-cast to 'id'
Douglas Gregore200adc2008-10-27 19:41:14 +00002404 InitExprs.push_back( // set 'super class', using objc_getClass().
Mike Stump11289f42009-09-09 15:08:12 +00002405 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002406 CastExpr::CK_Unknown,
Douglas Gregore200adc2008-10-27 19:41:14 +00002407 Cls, Context->getObjCIdType(),
Mike Stump11289f42009-09-09 15:08:12 +00002408 SourceLocation(), SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002409 // struct objc_super
2410 QualType superType = getSuperStructType();
Steve Naroff0b844f02008-03-11 18:14:26 +00002411 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002412
Steve Naroff0b844f02008-03-11 18:14:26 +00002413 if (LangOpts.Microsoft) {
2414 SynthSuperContructorFunctionDecl();
2415 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002416 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff0b844f02008-03-11 18:14:26 +00002417 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002418 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002419 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002420 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002421 // The code for super is a little tricky to prevent collision with
2422 // the structure definition in the header. The rewriter has it's own
2423 // internal definition (__rw_objc_super) that is uses. This is why
2424 // we need the cast below. For example:
2425 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2426 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002427 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002428 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002429 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002430 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
2431 CastExpr::CK_Unknown, SuperRep,
Anders Carlssona2615922009-07-31 00:48:10 +00002432 Context->getPointerType(superType),
Mike Stump11289f42009-09-09 15:08:12 +00002433 SourceLocation(), SourceLocation());
2434 } else {
Steve Naroff0b844f02008-03-11 18:14:26 +00002435 // (struct objc_super) { <exprs from above> }
Mike Stump11289f42009-09-09 15:08:12 +00002436 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2437 &InitExprs[0], InitExprs.size(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002438 SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00002439 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE,
Chris Lattner07d754a2008-10-26 23:43:26 +00002440 false);
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002441 // struct objc_super *
Ted Kremenek5a201952009-02-07 01:47:29 +00002442 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002443 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002444 SourceLocation());
Steve Naroff0b844f02008-03-11 18:14:26 +00002445 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002446 MsgExprs.push_back(SuperRep);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002447 } else {
2448 llvm::SmallVector<Expr*, 8> ClsExprs;
2449 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002450 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002451 clsName->getNameStart(),
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002452 clsName->getLength(),
2453 false, argType,
2454 SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002455 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002456 &ClsExprs[0],
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002457 ClsExprs.size());
2458 MsgExprs.push_back(Cls);
2459 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002460 } else { // instance message.
2461 Expr *recExpr = Exp->getReceiver();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002462
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002463 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002464 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002465 if (MsgSendStretFlavor)
2466 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002467 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002468
Steve Naroff7fa2f042007-11-15 10:28:18 +00002469 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002470
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002471 InitExprs.push_back(
Mike Stump11289f42009-09-09 15:08:12 +00002472 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002473 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002474 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff97adf602008-07-16 22:35:27 +00002475 Context->getObjCIdType(),
Douglas Gregore200adc2008-10-27 19:41:14 +00002476 SourceLocation()),
2477 Context->getObjCIdType(),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002478 SourceLocation(), SourceLocation())); // set the 'receiver'.
Mike Stump11289f42009-09-09 15:08:12 +00002479
Steve Naroff7fa2f042007-11-15 10:28:18 +00002480 llvm::SmallVector<Expr*, 8> ClsExprs;
2481 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002482 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002483 SuperDecl->getIdentifier()->getNameStart(),
2484 SuperDecl->getIdentifier()->getLength(),
2485 false, argType, SourceLocation()));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002486 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002487 &ClsExprs[0],
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002488 ClsExprs.size());
Fariborz Jahaniand5db92b2007-12-05 17:29:46 +00002489 // To turn off a warning, type-cast to 'id'
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002490 InitExprs.push_back(
Douglas Gregore200adc2008-10-27 19:41:14 +00002491 // set 'super class', using objc_getClass().
Mike Stump11289f42009-09-09 15:08:12 +00002492 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002493 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002494 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002495 // struct objc_super
2496 QualType superType = getSuperStructType();
Steve Naroff17978c42008-03-11 17:37:02 +00002497 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002498
Steve Naroff17978c42008-03-11 17:37:02 +00002499 if (LangOpts.Microsoft) {
2500 SynthSuperContructorFunctionDecl();
2501 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002502 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff17978c42008-03-11 17:37:02 +00002503 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002504 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002505 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002506 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002507 // The code for super is a little tricky to prevent collision with
2508 // the structure definition in the header. The rewriter has it's own
2509 // internal definition (__rw_objc_super) that is uses. This is why
2510 // we need the cast below. For example:
2511 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2512 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002513 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002514 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002515 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002516 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Anders Carlssona2615922009-07-31 00:48:10 +00002517 CastExpr::CK_Unknown,
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002518 SuperRep, Context->getPointerType(superType),
Mike Stump11289f42009-09-09 15:08:12 +00002519 SourceLocation(), SourceLocation());
Steve Naroff17978c42008-03-11 17:37:02 +00002520 } else {
2521 // (struct objc_super) { <exprs from above> }
Mike Stump11289f42009-09-09 15:08:12 +00002522 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2523 &InitExprs[0], InitExprs.size(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002524 SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00002525 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002526 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002527 MsgExprs.push_back(SuperRep);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002528 } else {
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002529 // Remove all type-casts because it may contain objc-style types; e.g.
2530 // Foo<Proto> *.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002531 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002532 recExpr = CE->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002533 recExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002534 CastExpr::CK_Unknown, recExpr,
Mike Stump11289f42009-09-09 15:08:12 +00002535 Context->getObjCIdType(),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002536 SourceLocation(), SourceLocation());
Steve Naroff7fa2f042007-11-15 10:28:18 +00002537 MsgExprs.push_back(recExpr);
2538 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002539 }
Steve Naroffa397efd2007-11-03 11:27:19 +00002540 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff574440f2007-10-24 22:48:43 +00002541 llvm::SmallVector<Expr*, 8> SelExprs;
2542 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002543 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002544 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002545 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00002546 false, argType, SourceLocation()));
Steve Naroff574440f2007-10-24 22:48:43 +00002547 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2548 &SelExprs[0], SelExprs.size());
2549 MsgExprs.push_back(SelExp);
Mike Stump11289f42009-09-09 15:08:12 +00002550
Steve Naroff574440f2007-10-24 22:48:43 +00002551 // Now push any user supplied arguments.
2552 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroffe7f18192007-11-14 23:54:14 +00002553 Expr *userExpr = Exp->getArg(i);
Steve Narofff60782b2007-11-15 02:58:25 +00002554 // Make all implicit casts explicit...ICE comes in handy:-)
2555 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2556 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregore200adc2008-10-27 19:41:14 +00002557 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002558 ? Context->getObjCIdType()
Douglas Gregore200adc2008-10-27 19:41:14 +00002559 : ICE->getType();
Anders Carlssona2615922009-07-31 00:48:10 +00002560 userExpr = new (Context) CStyleCastExpr(type, CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002561 userExpr, type, SourceLocation(),
Anders Carlssona2615922009-07-31 00:48:10 +00002562 SourceLocation());
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002563 }
2564 // Make id<P...> cast into an 'id' cast.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002565 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002566 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregorf19b2312008-10-28 15:36:24 +00002567 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002568 userExpr = CE->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002569 userExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002570 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002571 userExpr, Context->getObjCIdType(),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002572 SourceLocation(), SourceLocation());
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002573 }
Mike Stump11289f42009-09-09 15:08:12 +00002574 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002575 MsgExprs.push_back(userExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00002576 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2577 // out the argument in the original expression (since we aren't deleting
2578 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2579 //Exp->setArg(i, 0);
Steve Naroff574440f2007-10-24 22:48:43 +00002580 }
Steve Narofff36987c2007-11-04 22:37:50 +00002581 // Generate the funky cast.
2582 CastExpr *cast;
2583 llvm::SmallVector<QualType, 8> ArgTypes;
2584 QualType returnType;
Mike Stump11289f42009-09-09 15:08:12 +00002585
Steve Narofff36987c2007-11-04 22:37:50 +00002586 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff44864e42007-11-15 10:43:57 +00002587 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2588 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2589 else
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002590 ArgTypes.push_back(Context->getObjCIdType());
2591 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattnera4997152009-02-20 18:43:26 +00002592 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Narofff36987c2007-11-04 22:37:50 +00002593 // Push any user argument types.
Chris Lattnera4997152009-02-20 18:43:26 +00002594 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2595 E = OMD->param_end(); PI != E; ++PI) {
2596 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump11289f42009-09-09 15:08:12 +00002597 ? Context->getObjCIdType()
Chris Lattnera4997152009-02-20 18:43:26 +00002598 : (*PI)->getType();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002599 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00002600 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002601 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002602 t = Context->getPointerType(BPT->getPointeeType());
2603 }
Steve Naroff98eb8d12007-11-05 14:36:37 +00002604 ArgTypes.push_back(t);
2605 }
Chris Lattnera4997152009-02-20 18:43:26 +00002606 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2607 ? Context->getObjCIdType() : OMD->getResultType();
Steve Narofff36987c2007-11-04 22:37:50 +00002608 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002609 returnType = Context->getObjCIdType();
Steve Narofff36987c2007-11-04 22:37:50 +00002610 }
2611 // Get the type, we will need to reference it in a couple spots.
Steve Naroff7fa2f042007-11-15 10:28:18 +00002612 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002613
Steve Narofff36987c2007-11-04 22:37:50 +00002614 // Create a reference to the objc_msgSend() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002615 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002616 SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002617
Mike Stump11289f42009-09-09 15:08:12 +00002618 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Narofff36987c2007-11-04 22:37:50 +00002619 // If we don't do this cast, we get the following bizarre warning/note:
2620 // xx.m:13: warning: function called through a non-compatible type
2621 // xx.m:13: note: if this code is reached, the program will abort
Mike Stump11289f42009-09-09 15:08:12 +00002622 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy),
2623 CastExpr::CK_Unknown, DRE,
Douglas Gregore200adc2008-10-27 19:41:14 +00002624 Context->getPointerType(Context->VoidTy),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002625 SourceLocation(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002626
Steve Narofff36987c2007-11-04 22:37:50 +00002627 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002628 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002629 &ArgTypes[0], ArgTypes.size(),
Steve Naroff327f0f42008-03-18 02:02:04 +00002630 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002631 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Narofff36987c2007-11-04 22:37:50 +00002632 castType = Context->getPointerType(castType);
Mike Stump11289f42009-09-09 15:08:12 +00002633 cast = new (Context) CStyleCastExpr(castType, CastExpr::CK_Unknown, cast,
2634 castType, SourceLocation(),
Anders Carlssona2615922009-07-31 00:48:10 +00002635 SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002636
2637 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00002638 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00002639
John McCall9dd450b2009-09-21 23:43:11 +00002640 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002641 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002642 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002643 FT->getResultType(), SourceLocation());
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002644 Stmt *ReplacingStmt = CE;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002645 if (MsgSendStretFlavor) {
2646 // We have the method which returns a struct/union. Must also generate
2647 // call to objc_msgSend_stret and hang both varieties on a conditional
2648 // expression which dictate which one to envoke depending on size of
2649 // method's return type.
Mike Stump11289f42009-09-09 15:08:12 +00002650
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002651 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002652 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002653 SourceLocation());
2654 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Mike Stump11289f42009-09-09 15:08:12 +00002655 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy),
2656 CastExpr::CK_Unknown, STDRE,
Douglas Gregore200adc2008-10-27 19:41:14 +00002657 Context->getPointerType(Context->VoidTy),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002658 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002659 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002660 castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002661 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002662 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002663 castType = Context->getPointerType(castType);
Anders Carlssona2615922009-07-31 00:48:10 +00002664 cast = new (Context) CStyleCastExpr(castType, CastExpr::CK_Unknown,
2665 cast, castType, SourceLocation(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002666
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002667 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00002668 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00002669
John McCall9dd450b2009-09-21 23:43:11 +00002670 FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002671 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002672 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002673 FT->getResultType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002674
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002675 // Build sizeof(returnType)
Mike Stump11289f42009-09-09 15:08:12 +00002676 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCall4c98fd82009-11-04 07:28:41 +00002677 Context->getTrivialDeclaratorInfo(returnType),
Sebastian Redl6f282892008-11-11 17:56:53 +00002678 Context->getSizeType(),
2679 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002680 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2681 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2682 // For X86 it is more complicated and some kind of target specific routine
2683 // is needed to decide what to do.
Mike Stump11289f42009-09-09 15:08:12 +00002684 unsigned IntSize =
Chris Lattner37e05872008-03-05 18:54:05 +00002685 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Mike Stump11289f42009-09-09 15:08:12 +00002686 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002687 Context->IntTy,
2688 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002689 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
2690 BinaryOperator::LE,
2691 Context->IntTy,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002692 SourceLocation());
2693 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump11289f42009-09-09 15:08:12 +00002694 ConditionalOperator *CondExpr =
Douglas Gregor7e112b02009-08-26 14:37:04 +00002695 new (Context) ConditionalOperator(lessThanExpr,
2696 SourceLocation(), CE,
2697 SourceLocation(), STCE, returnType);
Ted Kremenek5a201952009-02-07 01:47:29 +00002698 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002699 }
Mike Stump11289f42009-09-09 15:08:12 +00002700 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002701 return ReplacingStmt;
2702}
2703
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002704Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002705 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Mike Stump11289f42009-09-09 15:08:12 +00002706
Steve Naroff574440f2007-10-24 22:48:43 +00002707 // Now do the actual rewrite.
Chris Lattner2e0d2602008-01-31 19:37:57 +00002708 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00002709
2710 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002711 return ReplacingStmt;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002712}
2713
Steve Naroffd9803712009-04-29 16:37:50 +00002714// typedef struct objc_object Protocol;
2715QualType RewriteObjC::getProtocolType() {
2716 if (!ProtocolTypeDecl) {
John McCall703a3f82009-10-24 08:00:42 +00002717 DeclaratorInfo *DInfo
2718 = Context->getTrivialDeclaratorInfo(Context->getObjCIdType());
Steve Naroffd9803712009-04-29 16:37:50 +00002719 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002720 SourceLocation(),
Steve Naroffd9803712009-04-29 16:37:50 +00002721 &Context->Idents.get("Protocol"),
John McCall703a3f82009-10-24 08:00:42 +00002722 DInfo);
Steve Naroffd9803712009-04-29 16:37:50 +00002723 }
2724 return Context->getTypeDeclType(ProtocolTypeDecl);
2725}
2726
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00002727/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroffd9803712009-04-29 16:37:50 +00002728/// a synthesized/forward data reference (to the protocol's metadata).
2729/// The forward references (and metadata) are generated in
2730/// RewriteObjC::HandleTranslationUnit().
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002731Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroffd9803712009-04-29 16:37:50 +00002732 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
2733 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump11289f42009-09-09 15:08:12 +00002734 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregored6c7442009-11-23 11:41:28 +00002735 ID, getProtocolType(), 0, VarDecl::Extern);
Steve Naroffd9803712009-04-29 16:37:50 +00002736 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
2737 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
2738 Context->getPointerType(DRE->getType()),
2739 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002740 CastExpr *castExpr = new (Context) CStyleCastExpr(DerefExpr->getType(),
2741 CastExpr::CK_Unknown,
2742 DerefExpr, DerefExpr->getType(),
Steve Naroffd9803712009-04-29 16:37:50 +00002743 SourceLocation(), SourceLocation());
2744 ReplaceStmt(Exp, castExpr);
2745 ProtocolExprDecls.insert(Exp->getProtocol());
Mike Stump11289f42009-09-09 15:08:12 +00002746 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00002747 return castExpr;
Mike Stump11289f42009-09-09 15:08:12 +00002748
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00002749}
2750
Mike Stump11289f42009-09-09 15:08:12 +00002751bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002752 const char *endBuf) {
2753 while (startBuf < endBuf) {
2754 if (*startBuf == '#') {
2755 // Skip whitespace.
2756 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2757 ;
2758 if (!strncmp(startBuf, "if", strlen("if")) ||
2759 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2760 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2761 !strncmp(startBuf, "define", strlen("define")) ||
2762 !strncmp(startBuf, "undef", strlen("undef")) ||
2763 !strncmp(startBuf, "else", strlen("else")) ||
2764 !strncmp(startBuf, "elif", strlen("elif")) ||
2765 !strncmp(startBuf, "endif", strlen("endif")) ||
2766 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2767 !strncmp(startBuf, "include", strlen("include")) ||
2768 !strncmp(startBuf, "import", strlen("import")) ||
2769 !strncmp(startBuf, "include_next", strlen("include_next")))
2770 return true;
2771 }
2772 startBuf++;
2773 }
2774 return false;
2775}
2776
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002777/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002778/// an objective-c class with ivars.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002779void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002780 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002781 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Mike Stump11289f42009-09-09 15:08:12 +00002782 assert(CDecl->getNameAsCString() &&
Douglas Gregor77324f32008-11-17 14:58:09 +00002783 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00002784 // Do not synthesize more than once.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002785 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00002786 return;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002787 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattner8d1c04f2008-03-16 21:08:55 +00002788 int NumIvars = CDecl->ivar_size();
Steve Naroffdde78982007-11-14 19:25:57 +00002789 SourceLocation LocStart = CDecl->getLocStart();
2790 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00002791
Steve Naroffdde78982007-11-14 19:25:57 +00002792 const char *startBuf = SM->getCharacterData(LocStart);
2793 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00002794
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002795 // If no ivars and no root or if its root, directly or indirectly,
2796 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattner8d1c04f2008-03-16 21:08:55 +00002797 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2798 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner184e65d2009-04-14 23:22:57 +00002799 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Chris Lattner9cc55f52008-01-31 19:51:04 +00002800 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002801 return;
2802 }
Mike Stump11289f42009-09-09 15:08:12 +00002803
2804 // FIXME: This has potential of causing problem. If
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002805 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002806 Result += "\nstruct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002807 Result += CDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00002808 if (LangOpts.Microsoft)
2809 Result += "_IMPL";
Steve Naroffdc5b6b22008-03-12 00:25:36 +00002810
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002811 if (NumIvars > 0) {
Steve Naroffdde78982007-11-14 19:25:57 +00002812 const char *cursor = strchr(startBuf, '{');
Mike Stump11289f42009-09-09 15:08:12 +00002813 assert((cursor && endBuf)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002814 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002815 // If the buffer contains preprocessor directives, we do more fine-grained
2816 // rewrites. This is intended to fix code that looks like (which occurs in
2817 // NSURL.h, for example):
2818 //
2819 // #ifdef XYZ
2820 // @interface Foo : NSObject
2821 // #else
2822 // @interface FooBar : NSObject
2823 // #endif
2824 // {
2825 // int i;
2826 // }
2827 // @end
2828 //
2829 // This clause is segregated to avoid breaking the common case.
2830 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump11289f42009-09-09 15:08:12 +00002831 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002832 CDecl->getClassLoc();
2833 const char *endHeader = SM->getCharacterData(L);
Chris Lattner184e65d2009-04-14 23:22:57 +00002834 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002835
Chris Lattnerf5b77512009-02-20 18:18:36 +00002836 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002837 // advance to the end of the referenced protocols.
2838 while (endHeader < cursor && *endHeader != '>') endHeader++;
2839 endHeader++;
2840 }
2841 // rewrite the original header
2842 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2843 } else {
2844 // rewrite the original header *without* disturbing the '{'
Steve Naroffb0e33902009-12-04 21:36:32 +00002845 ReplaceText(LocStart, cursor-startBuf, Result.c_str(), Result.size());
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002846 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002847 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroffdde78982007-11-14 19:25:57 +00002848 Result = "\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002849 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00002850 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002851 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00002852 Result += "_IVARS;\n";
Mike Stump11289f42009-09-09 15:08:12 +00002853
Steve Naroffdde78982007-11-14 19:25:57 +00002854 // insert the super class structure definition.
Chris Lattner1780a852008-01-31 19:42:41 +00002855 SourceLocation OnePastCurly =
2856 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2857 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Naroffdde78982007-11-14 19:25:57 +00002858 }
2859 cursor++; // past '{'
Mike Stump11289f42009-09-09 15:08:12 +00002860
Steve Naroffdde78982007-11-14 19:25:57 +00002861 // Now comment out any visibility specifiers.
2862 while (cursor < endBuf) {
2863 if (*cursor == '@') {
2864 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner174a8252007-11-14 22:57:51 +00002865 // Skip whitespace.
2866 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2867 /*scan*/;
2868
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002869 // FIXME: presence of @public, etc. inside comment results in
2870 // this transformation as well, which is still correct c-code.
Steve Naroffdde78982007-11-14 19:25:57 +00002871 if (!strncmp(cursor, "public", strlen("public")) ||
2872 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffaf91b9a2008-04-04 22:34:24 +00002873 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002874 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattner1780a852008-01-31 19:42:41 +00002875 InsertText(atLoc, "// ", 3);
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002876 }
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002877 // FIXME: If there are cases where '<' is used in ivar declaration part
2878 // of user code, then scan the ivar list and use needToScanForQualifiers
2879 // for type checking.
2880 else if (*cursor == '<') {
2881 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner1780a852008-01-31 19:42:41 +00002882 InsertText(atLoc, "/* ", 3);
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002883 cursor = strchr(cursor, '>');
2884 cursor++;
2885 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner1780a852008-01-31 19:42:41 +00002886 InsertText(atLoc, " */", 3);
Steve Naroff295570a2008-10-30 12:09:33 +00002887 } else if (*cursor == '^') { // rewrite block specifier.
2888 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2889 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002890 }
Steve Naroffdde78982007-11-14 19:25:57 +00002891 cursor++;
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002892 }
Steve Naroffdde78982007-11-14 19:25:57 +00002893 // Don't forget to add a ';'!!
Chris Lattner1780a852008-01-31 19:42:41 +00002894 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Naroffdde78982007-11-14 19:25:57 +00002895 } else { // we don't have any instance variables - insert super struct.
Chris Lattner184e65d2009-04-14 23:22:57 +00002896 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroffdde78982007-11-14 19:25:57 +00002897 Result += " {\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002898 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00002899 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002900 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00002901 Result += "_IVARS;\n};\n";
Chris Lattner9cc55f52008-01-31 19:51:04 +00002902 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002903 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002904 // Mark this struct as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002905 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff13e74872008-05-06 18:26:51 +00002906 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002907}
2908
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002909// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002910/// class methods.
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002911template<typename MethodIterator>
2912void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
2913 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +00002914 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002915 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +00002916 const char *ClassName,
2917 std::string &Result) {
Chris Lattner31bc07e2007-12-12 07:46:12 +00002918 if (MethodBegin == MethodEnd) return;
Mike Stump11289f42009-09-09 15:08:12 +00002919
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00002920 static bool objc_impl_method = false;
Chris Lattner31bc07e2007-12-12 07:46:12 +00002921 if (!objc_impl_method) {
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002922 /* struct _objc_method {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00002923 SEL _cmd;
2924 char *method_types;
2925 void *_imp;
2926 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002927 */
Chris Lattner211f8b82007-10-25 17:07:24 +00002928 Result += "\nstruct _objc_method {\n";
2929 Result += "\tSEL _cmd;\n";
2930 Result += "\tchar *method_types;\n";
2931 Result += "\tvoid *_imp;\n";
2932 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002933
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002934 objc_impl_method = true;
Fariborz Jahanian74a1cfa2007-10-19 00:36:46 +00002935 }
Mike Stump11289f42009-09-09 15:08:12 +00002936
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002937 // Build _objc_method_list for class's methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00002938
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002939 /* struct {
2940 struct _objc_method_list *next_method;
2941 int method_count;
2942 struct _objc_method method_list[];
2943 }
2944 */
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002945 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002946 Result += "\nstatic struct {\n";
2947 Result += "\tstruct _objc_method_list *next_method;\n";
2948 Result += "\tint method_count;\n";
2949 Result += "\tstruct _objc_method method_list[";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002950 Result += utostr(NumMethods);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002951 Result += "];\n} _OBJC_";
Chris Lattner31bc07e2007-12-12 07:46:12 +00002952 Result += prefix;
2953 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2954 Result += "_METHODS_";
2955 Result += ClassName;
Steve Naroffb327e492008-03-12 17:18:30 +00002956 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattner31bc07e2007-12-12 07:46:12 +00002957 Result += IsInstanceMethod ? "inst" : "cls";
2958 Result += "_meth\")))= ";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002959 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00002960
Chris Lattner31bc07e2007-12-12 07:46:12 +00002961 Result += "\t,{{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00002962 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattner31bc07e2007-12-12 07:46:12 +00002963 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002964 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattner31bc07e2007-12-12 07:46:12 +00002965 Result += "\", \"";
2966 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002967 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00002968 Result += MethodInternalNames[*MethodBegin];
2969 Result += "}\n";
2970 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2971 Result += "\t ,{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00002972 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00002973 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002974 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00002975 Result += "\", \"";
2976 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002977 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00002978 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanian56338352007-11-13 21:02:00 +00002979 Result += "}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00002980 }
Chris Lattner31bc07e2007-12-12 07:46:12 +00002981 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002982}
2983
Steve Naroffd9803712009-04-29 16:37:50 +00002984/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner390d39a2008-07-21 21:32:27 +00002985void RewriteObjC::
Steve Naroffd9803712009-04-29 16:37:50 +00002986RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
2987 const char *ClassName, std::string &Result) {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00002988 static bool objc_protocol_methods = false;
Steve Naroffd9803712009-04-29 16:37:50 +00002989
2990 // Output struct protocol_methods holder of method selector and type.
2991 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2992 /* struct protocol_methods {
2993 SEL _cmd;
2994 char *method_types;
2995 }
2996 */
2997 Result += "\nstruct _protocol_methods {\n";
2998 Result += "\tstruct objc_selector *_cmd;\n";
2999 Result += "\tchar *method_types;\n";
3000 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003001
Steve Naroffd9803712009-04-29 16:37:50 +00003002 objc_protocol_methods = true;
3003 }
3004 // Do not synthesize the protocol more than once.
3005 if (ObjCSynthesizedProtocols.count(PDecl))
3006 return;
Mike Stump11289f42009-09-09 15:08:12 +00003007
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003008 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3009 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3010 PDecl->instmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003011 /* struct _objc_protocol_method_list {
3012 int protocol_method_count;
3013 struct protocol_methods protocols[];
3014 }
Steve Naroff251084d2008-03-12 01:06:30 +00003015 */
Steve Naroffd9803712009-04-29 16:37:50 +00003016 Result += "\nstatic struct {\n";
3017 Result += "\tint protocol_method_count;\n";
3018 Result += "\tstruct _protocol_methods protocol_methods[";
3019 Result += utostr(NumMethods);
3020 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3021 Result += PDecl->getNameAsString();
3022 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3023 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003024
Steve Naroffd9803712009-04-29 16:37:50 +00003025 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003026 for (ObjCProtocolDecl::instmeth_iterator
3027 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003028 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003029 if (I == PDecl->instmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003030 Result += "\t ,{{(struct objc_selector *)\"";
3031 else
3032 Result += "\t ,{(struct objc_selector *)\"";
3033 Result += (*I)->getSelector().getAsString().c_str();
3034 std::string MethodTypeString;
3035 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3036 Result += "\", \"";
3037 Result += MethodTypeString;
3038 Result += "\"}\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003039 }
Steve Naroffd9803712009-04-29 16:37:50 +00003040 Result += "\t }\n};\n";
3041 }
Mike Stump11289f42009-09-09 15:08:12 +00003042
Steve Naroffd9803712009-04-29 16:37:50 +00003043 // Output class methods declared in this protocol.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003044 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3045 PDecl->classmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003046 if (NumMethods > 0) {
3047 /* struct _objc_protocol_method_list {
3048 int protocol_method_count;
3049 struct protocol_methods protocols[];
3050 }
3051 */
3052 Result += "\nstatic struct {\n";
3053 Result += "\tint protocol_method_count;\n";
3054 Result += "\tstruct _protocol_methods protocol_methods[";
3055 Result += utostr(NumMethods);
3056 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3057 Result += PDecl->getNameAsString();
3058 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3059 "{\n\t";
3060 Result += utostr(NumMethods);
3061 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003062
Steve Naroffd9803712009-04-29 16:37:50 +00003063 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003064 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003065 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003066 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003067 if (I == PDecl->classmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003068 Result += "\t ,{{(struct objc_selector *)\"";
3069 else
3070 Result += "\t ,{(struct objc_selector *)\"";
3071 Result += (*I)->getSelector().getAsString().c_str();
3072 std::string MethodTypeString;
3073 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3074 Result += "\", \"";
3075 Result += MethodTypeString;
3076 Result += "\"}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003077 }
Steve Naroffd9803712009-04-29 16:37:50 +00003078 Result += "\t }\n};\n";
3079 }
3080
3081 // Output:
3082 /* struct _objc_protocol {
3083 // Objective-C 1.0 extensions
3084 struct _objc_protocol_extension *isa;
3085 char *protocol_name;
3086 struct _objc_protocol **protocol_list;
3087 struct _objc_protocol_method_list *instance_methods;
3088 struct _objc_protocol_method_list *class_methods;
Mike Stump11289f42009-09-09 15:08:12 +00003089 };
Steve Naroffd9803712009-04-29 16:37:50 +00003090 */
3091 static bool objc_protocol = false;
3092 if (!objc_protocol) {
3093 Result += "\nstruct _objc_protocol {\n";
3094 Result += "\tstruct _objc_protocol_extension *isa;\n";
3095 Result += "\tchar *protocol_name;\n";
3096 Result += "\tstruct _objc_protocol **protocol_list;\n";
3097 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3098 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003099 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003100
Steve Naroffd9803712009-04-29 16:37:50 +00003101 objc_protocol = true;
Chris Lattner388f6e92008-07-21 21:33:21 +00003102 }
Mike Stump11289f42009-09-09 15:08:12 +00003103
Steve Naroffd9803712009-04-29 16:37:50 +00003104 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3105 Result += PDecl->getNameAsString();
3106 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3107 "{\n\t0, \"";
3108 Result += PDecl->getNameAsString();
3109 Result += "\", 0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003110 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003111 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3112 Result += PDecl->getNameAsString();
3113 Result += ", ";
3114 }
3115 else
3116 Result += "0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003117 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003118 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3119 Result += PDecl->getNameAsString();
3120 Result += "\n";
3121 }
3122 else
3123 Result += "0\n";
3124 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003125
Steve Naroffd9803712009-04-29 16:37:50 +00003126 // Mark this protocol as having been generated.
3127 if (!ObjCSynthesizedProtocols.insert(PDecl))
3128 assert(false && "protocol already synthesized");
3129
3130}
3131
3132void RewriteObjC::
3133RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3134 const char *prefix, const char *ClassName,
3135 std::string &Result) {
3136 if (Protocols.empty()) return;
Mike Stump11289f42009-09-09 15:08:12 +00003137
Steve Naroffd9803712009-04-29 16:37:50 +00003138 for (unsigned i = 0; i != Protocols.size(); i++)
3139 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3140
Chris Lattner388f6e92008-07-21 21:33:21 +00003141 // Output the top lovel protocol meta-data for the class.
3142 /* struct _objc_protocol_list {
3143 struct _objc_protocol_list *next;
3144 int protocol_count;
3145 struct _objc_protocol *class_protocols[];
3146 }
3147 */
3148 Result += "\nstatic struct {\n";
3149 Result += "\tstruct _objc_protocol_list *next;\n";
3150 Result += "\tint protocol_count;\n";
3151 Result += "\tstruct _objc_protocol *class_protocols[";
3152 Result += utostr(Protocols.size());
3153 Result += "];\n} _OBJC_";
3154 Result += prefix;
3155 Result += "_PROTOCOLS_";
3156 Result += ClassName;
3157 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3158 "{\n\t0, ";
3159 Result += utostr(Protocols.size());
3160 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003161
Chris Lattner388f6e92008-07-21 21:33:21 +00003162 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003163 Result += Protocols[0]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003164 Result += " \n";
Mike Stump11289f42009-09-09 15:08:12 +00003165
Chris Lattner388f6e92008-07-21 21:33:21 +00003166 for (unsigned i = 1; i != Protocols.size(); i++) {
3167 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003168 Result += Protocols[i]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003169 Result += "\n";
3170 }
3171 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003172}
3173
Steve Naroffd9803712009-04-29 16:37:50 +00003174
Mike Stump11289f42009-09-09 15:08:12 +00003175/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003176/// implementation.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003177void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003178 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003179 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003180 // Find category declaration for this implementation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003181 ObjCCategoryDecl *CDecl;
Mike Stump11289f42009-09-09 15:08:12 +00003182 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003183 CDecl = CDecl->getNextClassCategory())
3184 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3185 break;
Mike Stump11289f42009-09-09 15:08:12 +00003186
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003187 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003188 FullCategoryName += '_';
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003189 FullCategoryName += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003190
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003191 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003192 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003193 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003194
3195 // If any of our property implementations have associated getters or
3196 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003197 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3198 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003199 Prop != PropEnd; ++Prop) {
3200 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3201 continue;
3202 if (!(*Prop)->getPropertyIvarDecl())
3203 continue;
3204 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3205 if (!PD)
3206 continue;
3207 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3208 InstanceMethods.push_back(Getter);
3209 if (PD->isReadOnly())
3210 continue;
3211 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3212 InstanceMethods.push_back(Setter);
3213 }
3214 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003215 true, "CATEGORY_", FullCategoryName.c_str(),
3216 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003217
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003218 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003219 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003220 false, "CATEGORY_", FullCategoryName.c_str(),
3221 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003222
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003223 // Protocols referenced in class declaration?
Fariborz Jahanian989e0392007-11-13 22:09:49 +00003224 // Null CDecl is case of a category implementation with no category interface
3225 if (CDecl)
Steve Naroffd9803712009-04-29 16:37:50 +00003226 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3227 FullCategoryName.c_str(), Result);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003228 /* struct _objc_category {
3229 char *category_name;
3230 char *class_name;
3231 struct _objc_method_list *instance_methods;
3232 struct _objc_method_list *class_methods;
3233 struct _objc_protocol_list *protocols;
3234 // Objective-C 1.0 extensions
3235 uint32_t size; // sizeof (struct _objc_category)
Mike Stump11289f42009-09-09 15:08:12 +00003236 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003237 // @property decl.
Mike Stump11289f42009-09-09 15:08:12 +00003238 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003239 */
Mike Stump11289f42009-09-09 15:08:12 +00003240
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003241 static bool objc_category = false;
3242 if (!objc_category) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003243 Result += "\nstruct _objc_category {\n";
3244 Result += "\tchar *category_name;\n";
3245 Result += "\tchar *class_name;\n";
3246 Result += "\tstruct _objc_method_list *instance_methods;\n";
3247 Result += "\tstruct _objc_method_list *class_methods;\n";
3248 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003249 Result += "\tunsigned int size;\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003250 Result += "\tstruct _objc_property_list *instance_properties;\n";
3251 Result += "};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003252 objc_category = true;
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003253 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003254 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3255 Result += FullCategoryName;
Steve Naroffb327e492008-03-12 17:18:30 +00003256 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003257 Result += IDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003258 Result += "\"\n\t, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003259 Result += ClassDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003260 Result += "\"\n";
Mike Stump11289f42009-09-09 15:08:12 +00003261
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003262 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003263 Result += "\t, (struct _objc_method_list *)"
3264 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3265 Result += FullCategoryName;
3266 Result += "\n";
3267 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003268 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003269 Result += "\t, 0\n";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003270 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003271 Result += "\t, (struct _objc_method_list *)"
3272 "&_OBJC_CATEGORY_CLASS_METHODS_";
3273 Result += FullCategoryName;
3274 Result += "\n";
3275 }
3276 else
3277 Result += "\t, 0\n";
Mike Stump11289f42009-09-09 15:08:12 +00003278
Chris Lattnerf5b77512009-02-20 18:18:36 +00003279 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump11289f42009-09-09 15:08:12 +00003280 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003281 Result += FullCategoryName;
3282 Result += "\n";
3283 }
3284 else
3285 Result += "\t, 0\n";
3286 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003287}
3288
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003289/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3290/// ivar offset.
Mike Stump11289f42009-09-09 15:08:12 +00003291void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
3292 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003293 std::string &Result) {
Steve Naroffde7d0f62008-07-16 18:22:22 +00003294 if (ivar->isBitField()) {
3295 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3296 // place all bitfields at offset 0.
3297 Result += "0";
3298 } else {
3299 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003300 Result += IDecl->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003301 if (LangOpts.Microsoft)
3302 Result += "_IMPL";
3303 Result += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003304 Result += ivar->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003305 Result += ")";
3306 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003307}
3308
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003309//===----------------------------------------------------------------------===//
3310// Meta Data Emission
3311//===----------------------------------------------------------------------===//
3312
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003313void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003314 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003315 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00003316
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003317 // Explictly declared @interface's are already synthesized.
Steve Naroffaac654a2009-04-20 20:09:33 +00003318 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump11289f42009-09-09 15:08:12 +00003319 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003320 // produce correct synthesis as yet.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003321 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003322 }
Mike Stump11289f42009-09-09 15:08:12 +00003323
Chris Lattner30d23e82007-12-12 07:56:42 +00003324 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003325 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump11289f42009-09-09 15:08:12 +00003326 ? IDecl->ivar_size()
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003327 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003328 if (NumIvars > 0) {
3329 static bool objc_ivar = false;
3330 if (!objc_ivar) {
3331 /* struct _objc_ivar {
3332 char *ivar_name;
3333 char *ivar_type;
3334 int ivar_offset;
Mike Stump11289f42009-09-09 15:08:12 +00003335 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003336 */
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003337 Result += "\nstruct _objc_ivar {\n";
3338 Result += "\tchar *ivar_name;\n";
3339 Result += "\tchar *ivar_type;\n";
3340 Result += "\tint ivar_offset;\n";
3341 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003342
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003343 objc_ivar = true;
3344 }
3345
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003346 /* struct {
3347 int ivar_count;
3348 struct _objc_ivar ivar_list[nIvars];
Mike Stump11289f42009-09-09 15:08:12 +00003349 };
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003350 */
Mike Stump11289f42009-09-09 15:08:12 +00003351 Result += "\nstatic struct {\n";
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003352 Result += "\tint ivar_count;\n";
3353 Result += "\tstruct _objc_ivar ivar_list[";
3354 Result += utostr(NumIvars);
3355 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003356 Result += IDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003357 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003358 "{\n\t";
3359 Result += utostr(NumIvars);
3360 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003361
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003362 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor5f662052009-04-23 03:23:08 +00003363 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003364 if (!IDecl->ivar_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00003365 for (ObjCImplementationDecl::ivar_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003366 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor5f662052009-04-23 03:23:08 +00003367 IV != IVEnd; ++IV)
3368 IVars.push_back(*IV);
3369 IVI = IVars.begin();
3370 IVE = IVars.end();
Chris Lattner30d23e82007-12-12 07:56:42 +00003371 } else {
3372 IVI = CDecl->ivar_begin();
3373 IVE = CDecl->ivar_end();
3374 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003375 Result += "\t,{{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003376 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003377 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003378 std::string TmpString, StrEncoding;
3379 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3380 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003381 Result += StrEncoding;
3382 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003383 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003384 Result += "}\n";
Chris Lattner30d23e82007-12-12 07:56:42 +00003385 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003386 Result += "\t ,{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003387 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003388 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003389 std::string TmpString, StrEncoding;
3390 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3391 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003392 Result += StrEncoding;
3393 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003394 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003395 Result += "}\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003396 }
Mike Stump11289f42009-09-09 15:08:12 +00003397
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003398 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003399 }
Mike Stump11289f42009-09-09 15:08:12 +00003400
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003401 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003402 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003403 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003404
3405 // If any of our property implementations have associated getters or
3406 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003407 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3408 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003409 Prop != PropEnd; ++Prop) {
3410 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3411 continue;
3412 if (!(*Prop)->getPropertyIvarDecl())
3413 continue;
3414 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3415 if (!PD)
3416 continue;
3417 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3418 InstanceMethods.push_back(Getter);
3419 if (PD->isReadOnly())
3420 continue;
3421 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3422 InstanceMethods.push_back(Setter);
3423 }
3424 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003425 true, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003426
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003427 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003428 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003429 false, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003430
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003431 // Protocols referenced in class declaration?
Steve Naroffd9803712009-04-29 16:37:50 +00003432 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3433 "CLASS", CDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003434
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003435 // Declaration of class/meta-class metadata
3436 /* struct _objc_class {
3437 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003438 const char *super_class_name;
3439 char *name;
3440 long version;
3441 long info;
3442 long instance_size;
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003443 struct _objc_ivar_list *ivars;
3444 struct _objc_method_list *methods;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003445 struct objc_cache *cache;
3446 struct objc_protocol_list *protocols;
3447 const char *ivar_layout;
3448 struct _objc_class_ext *ext;
Mike Stump11289f42009-09-09 15:08:12 +00003449 };
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003450 */
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003451 static bool objc_class = false;
3452 if (!objc_class) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003453 Result += "\nstruct _objc_class {\n";
3454 Result += "\tstruct _objc_class *isa;\n";
3455 Result += "\tconst char *super_class_name;\n";
3456 Result += "\tchar *name;\n";
3457 Result += "\tlong version;\n";
3458 Result += "\tlong info;\n";
3459 Result += "\tlong instance_size;\n";
3460 Result += "\tstruct _objc_ivar_list *ivars;\n";
3461 Result += "\tstruct _objc_method_list *methods;\n";
3462 Result += "\tstruct objc_cache *cache;\n";
3463 Result += "\tstruct _objc_protocol_list *protocols;\n";
3464 Result += "\tconst char *ivar_layout;\n";
3465 Result += "\tstruct _objc_class_ext *ext;\n";
3466 Result += "};\n";
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003467 objc_class = true;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003468 }
Mike Stump11289f42009-09-09 15:08:12 +00003469
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003470 // Meta-class metadata generation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003471 ObjCInterfaceDecl *RootClass = 0;
3472 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003473 while (SuperClass) {
3474 RootClass = SuperClass;
3475 SuperClass = SuperClass->getSuperClass();
3476 }
3477 SuperClass = CDecl->getSuperClass();
Mike Stump11289f42009-09-09 15:08:12 +00003478
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003479 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003480 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003481 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003482 "{\n\t(struct _objc_class *)\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003483 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003484 Result += "\"";
3485
3486 if (SuperClass) {
3487 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003488 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003489 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003490 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003491 Result += "\"";
3492 }
3493 else {
3494 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003495 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003496 Result += "\"";
3497 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003498 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003499 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003500 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003501 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff0b844f02008-03-11 18:14:26 +00003502 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003503 Result += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003504 Result += "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003505 }
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003506 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003507 Result += ", 0\n";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003508 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003509 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003510 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003511 Result += ",0,0\n";
3512 }
Fariborz Jahanian486f7182007-10-24 20:54:23 +00003513 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003514 Result += "\t,0,0,0,0\n";
3515 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003516
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003517 // class metadata generation.
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003518 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003519 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003520 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003521 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003522 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003523 if (SuperClass) {
3524 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003525 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003526 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003527 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003528 Result += "\"";
3529 }
3530 else {
3531 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003532 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003533 Result += "\"";
3534 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003535 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003536 Result += ", 0,1";
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003537 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003538 Result += ",0";
3539 else {
3540 // class has size. Must synthesize its size.
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00003541 Result += ",sizeof(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003542 Result += CDecl->getNameAsString();
Steve Naroff14a07462008-03-10 23:33:22 +00003543 if (LangOpts.Microsoft)
3544 Result += "_IMPL";
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003545 Result += ")";
3546 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003547 if (NumIvars > 0) {
Steve Naroff17978c42008-03-11 17:37:02 +00003548 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003549 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003550 Result += "\n\t";
3551 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003552 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003553 Result += ",0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003554 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003555 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003556 Result += CDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003557 Result += ", 0\n\t";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003558 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003559 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003560 Result += ",0,0";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003561 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003562 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003563 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003564 Result += ", 0,0\n";
3565 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003566 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003567 Result += ",0,0,0\n";
3568 Result += "};\n";
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003569}
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003570
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003571/// RewriteImplementations - This routine rewrites all method implementations
3572/// and emits meta-data.
3573
Steve Narofff8cfd162008-11-13 20:07:04 +00003574void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003575 int ClsDefCount = ClassImplementation.size();
3576 int CatDefCount = CategoryImplementation.size();
Mike Stump11289f42009-09-09 15:08:12 +00003577
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003578 // Rewrite implemented methods
3579 for (int i = 0; i < ClsDefCount; i++)
3580 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003581
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00003582 for (int i = 0; i < CatDefCount; i++)
3583 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofff8cfd162008-11-13 20:07:04 +00003584}
Mike Stump11289f42009-09-09 15:08:12 +00003585
Steve Narofff8cfd162008-11-13 20:07:04 +00003586void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3587 int ClsDefCount = ClassImplementation.size();
3588 int CatDefCount = CategoryImplementation.size();
3589
Steve Naroff30ac2222008-05-07 21:23:49 +00003590 // This is needed for determining instance variable offsets.
Mike Stump11289f42009-09-09 15:08:12 +00003591 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003592 // For each implemented class, write out all its meta data.
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003593 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003594 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump11289f42009-09-09 15:08:12 +00003595
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003596 // For each implemented category, write out all its meta data.
3597 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003598 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroffd9803712009-04-29 16:37:50 +00003599
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003600 // Write objc_symtab metadata
3601 /*
3602 struct _objc_symtab
3603 {
3604 long sel_ref_cnt;
3605 SEL *refs;
3606 short cls_def_cnt;
3607 short cat_def_cnt;
3608 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump11289f42009-09-09 15:08:12 +00003609 };
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003610 */
Mike Stump11289f42009-09-09 15:08:12 +00003611
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003612 Result += "\nstruct _objc_symtab {\n";
3613 Result += "\tlong sel_ref_cnt;\n";
3614 Result += "\tSEL *refs;\n";
3615 Result += "\tshort cls_def_cnt;\n";
3616 Result += "\tshort cat_def_cnt;\n";
3617 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3618 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003619
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003620 Result += "static struct _objc_symtab "
Steve Naroffb327e492008-03-12 17:18:30 +00003621 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003622 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003623 + ", " + utostr(CatDefCount) + "\n";
3624 for (int i = 0; i < ClsDefCount; i++) {
3625 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003626 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003627 Result += "\n";
3628 }
Mike Stump11289f42009-09-09 15:08:12 +00003629
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003630 for (int i = 0; i < CatDefCount; i++) {
3631 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003632 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003633 Result += "_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003634 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003635 Result += "\n";
3636 }
Mike Stump11289f42009-09-09 15:08:12 +00003637
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003638 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003639
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003640 // Write objc_module metadata
Mike Stump11289f42009-09-09 15:08:12 +00003641
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003642 /*
3643 struct _objc_module {
3644 long version;
3645 long size;
3646 const char *name;
3647 struct _objc_symtab *symtab;
3648 }
3649 */
Mike Stump11289f42009-09-09 15:08:12 +00003650
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003651 Result += "\nstruct _objc_module {\n";
3652 Result += "\tlong version;\n";
3653 Result += "\tlong size;\n";
3654 Result += "\tconst char *name;\n";
3655 Result += "\tstruct _objc_symtab *symtab;\n";
3656 Result += "};\n\n";
3657 Result += "static struct _objc_module "
Steve Naroffb327e492008-03-12 17:18:30 +00003658 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003659 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003660 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003661 Result += "};\n\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003662
3663 if (LangOpts.Microsoft) {
Steve Naroffd9803712009-04-29 16:37:50 +00003664 if (ProtocolExprDecls.size()) {
3665 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
3666 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump11289f42009-09-09 15:08:12 +00003667 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00003668 E = ProtocolExprDecls.end(); I != E; ++I) {
3669 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
3670 Result += (*I)->getNameAsString();
3671 Result += " = &_OBJC_PROTOCOL_";
3672 Result += (*I)->getNameAsString();
3673 Result += ";\n";
3674 }
3675 Result += "#pragma data_seg(pop)\n\n";
3676 }
Steve Naroff945a3b12008-03-10 20:43:59 +00003677 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffcab93d52008-05-07 00:06:16 +00003678 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003679 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3680 Result += "&_OBJC_MODULES;\n";
3681 Result += "#pragma data_seg(pop)\n\n";
3682 }
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003683}
Chris Lattnera7c19fe2007-10-16 22:36:42 +00003684
Steve Naroff677ab3a2008-10-27 17:20:55 +00003685std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3686 const char *funcName,
3687 std::string Tag) {
3688 const FunctionType *AFT = CE->getFunctionType();
3689 QualType RT = AFT->getResultType();
3690 std::string StructRef = "struct " + Tag;
3691 std::string S = "static " + RT.getAsString() + " __" +
3692 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00003693
Steve Naroff677ab3a2008-10-27 17:20:55 +00003694 BlockDecl *BD = CE->getBlockDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003695
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003696 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump11289f42009-09-09 15:08:12 +00003697 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Narofff26a1d42009-02-02 17:19:26 +00003698 // block (to reference imported block decl refs).
3699 S += "(" + StructRef + " *__cself)";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003700 } else if (BD->param_empty()) {
3701 S += "(" + StructRef + " *__cself)";
3702 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003703 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003704 assert(FT && "SynthesizeBlockFunc: No function proto");
3705 S += '(';
3706 // first add the implicit argument.
3707 S += StructRef + " *__cself, ";
3708 std::string ParamStr;
3709 for (BlockDecl::param_iterator AI = BD->param_begin(),
3710 E = BD->param_end(); AI != E; ++AI) {
3711 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003712 ParamStr = (*AI)->getNameAsString();
Douglas Gregor7de59662009-05-29 20:38:28 +00003713 (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003714 S += ParamStr;
3715 }
3716 if (FT->isVariadic()) {
3717 if (!BD->param_empty()) S += ", ";
3718 S += "...";
3719 }
3720 S += ')';
3721 }
3722 S += " {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003723
Steve Naroff677ab3a2008-10-27 17:20:55 +00003724 // Create local declarations to avoid rewriting all closure decl ref exprs.
3725 // First, emit a declaration for all "by ref" decls.
Mike Stump11289f42009-09-09 15:08:12 +00003726 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003727 E = BlockByRefDecls.end(); I != E; ++I) {
3728 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003729 std::string Name = (*I)->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003730 Context->getPointerType((*I)->getType()).getAsStringInternal(Name,
Douglas Gregor7de59662009-05-29 20:38:28 +00003731 Context->PrintingPolicy);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003732 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump11289f42009-09-09 15:08:12 +00003733 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003734 // Next, emit a declaration for all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003735 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003736 E = BlockByCopyDecls.end(); I != E; ++I) {
3737 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003738 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003739 // Handle nested closure invocation. For example:
3740 //
3741 // void (^myImportedClosure)(void);
3742 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003743 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003744 // void (^anotherClosure)(void);
3745 // anotherClosure = ^(void) {
3746 // myImportedClosure(); // import and invoke the closure
3747 // };
3748 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003749 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003750 S += "struct __block_impl *";
3751 else
Douglas Gregor7de59662009-05-29 20:38:28 +00003752 (*I)->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003753 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003754 }
3755 std::string RewrittenStr = RewrittenBlockExprs[CE];
3756 const char *cstr = RewrittenStr.c_str();
3757 while (*cstr++ != '{') ;
3758 S += cstr;
3759 S += "\n";
3760 return S;
3761}
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00003762
Steve Naroff677ab3a2008-10-27 17:20:55 +00003763std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3764 const char *funcName,
3765 std::string Tag) {
3766 std::string StructRef = "struct " + Tag;
3767 std::string S = "static void __";
Mike Stump11289f42009-09-09 15:08:12 +00003768
Steve Naroff677ab3a2008-10-27 17:20:55 +00003769 S += funcName;
3770 S += "_block_copy_" + utostr(i);
3771 S += "(" + StructRef;
3772 S += "*dst, " + StructRef;
3773 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003774 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003775 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003776 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003777 S += (*I)->getNameAsString();
Steve Naroff5ac4eac2008-12-11 20:51:38 +00003778 S += ", (void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003779 S += (*I)->getNameAsString();
Steve Naroff61d879e2008-12-16 15:50:30 +00003780 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);}";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003781 }
3782 S += "\nstatic void __";
3783 S += funcName;
3784 S += "_block_dispose_" + utostr(i);
3785 S += "(" + StructRef;
3786 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003787 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003788 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003789 S += "_Block_object_dispose((void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003790 S += (*I)->getNameAsString();
Steve Naroff61d879e2008-12-16 15:50:30 +00003791 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003792 }
Mike Stump11289f42009-09-09 15:08:12 +00003793 S += "}\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003794 return S;
3795}
3796
3797std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3798 bool hasCopyDisposeHelpers) {
Steve Naroff295570a2008-10-30 12:09:33 +00003799 std::string S = "\nstruct " + Tag;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003800 std::string Constructor = " " + Tag;
Mike Stump11289f42009-09-09 15:08:12 +00003801
Steve Naroff677ab3a2008-10-27 17:20:55 +00003802 S += " {\n struct __block_impl impl;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003803
Steve Naroff677ab3a2008-10-27 17:20:55 +00003804 if (hasCopyDisposeHelpers)
3805 S += " void *copy;\n void *dispose;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003806
Steve Naroff677ab3a2008-10-27 17:20:55 +00003807 Constructor += "(void *fp";
Mike Stump11289f42009-09-09 15:08:12 +00003808
Steve Naroff677ab3a2008-10-27 17:20:55 +00003809 if (hasCopyDisposeHelpers)
3810 Constructor += ", void *copyHelp, void *disposeHelp";
Mike Stump11289f42009-09-09 15:08:12 +00003811
Steve Naroff677ab3a2008-10-27 17:20:55 +00003812 if (BlockDeclRefs.size()) {
3813 // Output all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003814 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003815 E = BlockByCopyDecls.end(); I != E; ++I) {
3816 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003817 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003818 std::string ArgName = "_" + FieldName;
3819 // Handle nested closure invocation. For example:
3820 //
3821 // void (^myImportedBlock)(void);
3822 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003823 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003824 // void (^anotherBlock)(void);
3825 // anotherBlock = ^(void) {
3826 // myImportedBlock(); // import and invoke the closure
3827 // };
3828 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003829 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003830 S += "struct __block_impl *";
3831 Constructor += ", void *" + ArgName;
3832 } else {
Douglas Gregor7de59662009-05-29 20:38:28 +00003833 (*I)->getType().getAsStringInternal(FieldName, Context->PrintingPolicy);
3834 (*I)->getType().getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003835 Constructor += ", " + ArgName;
3836 }
3837 S += FieldName + ";\n";
3838 }
3839 // Output all "by ref" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003840 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003841 E = BlockByRefDecls.end(); I != E; ++I) {
3842 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003843 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003844 std::string ArgName = "_" + FieldName;
3845 // Handle nested closure invocation. For example:
3846 //
3847 // void (^myImportedBlock)(void);
3848 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003849 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003850 // void (^anotherBlock)(void);
3851 // anotherBlock = ^(void) {
3852 // myImportedBlock(); // import and invoke the closure
3853 // };
3854 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003855 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003856 S += "struct __block_impl *";
3857 Constructor += ", void *" + ArgName;
3858 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003859 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName,
Douglas Gregor7de59662009-05-29 20:38:28 +00003860 Context->PrintingPolicy);
Mike Stump11289f42009-09-09 15:08:12 +00003861 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName,
Douglas Gregor7de59662009-05-29 20:38:28 +00003862 Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003863 Constructor += ", " + ArgName;
3864 }
3865 S += FieldName + "; // by ref\n";
3866 }
3867 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00003868 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00003869 if (GlobalVarDecl)
3870 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3871 else
3872 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3873 Constructor += " impl.Size = sizeof(";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003874 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003875
Steve Naroff677ab3a2008-10-27 17:20:55 +00003876 if (hasCopyDisposeHelpers)
3877 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003878
Steve Naroff677ab3a2008-10-27 17:20:55 +00003879 // Initialize all "by copy" arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003880 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003881 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003882 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003883 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00003884 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003885 Constructor += Name + " = (struct __block_impl *)_";
3886 else
3887 Constructor += Name + " = _";
3888 Constructor += Name + ";\n";
3889 }
3890 // Initialize all "by ref" arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003891 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003892 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003893 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003894 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00003895 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003896 Constructor += Name + " = (struct __block_impl *)_";
3897 else
3898 Constructor += Name + " = _";
3899 Constructor += Name + ";\n";
3900 }
3901 } else {
3902 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00003903 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00003904 if (GlobalVarDecl)
3905 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3906 else
3907 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3908 Constructor += " impl.Size = sizeof(";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003909 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3910 if (hasCopyDisposeHelpers)
3911 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3912 }
3913 Constructor += " ";
3914 Constructor += "}\n";
3915 S += Constructor;
3916 S += "};\n";
3917 return S;
3918}
3919
3920void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3921 const char *FunName) {
3922 // Insert closures that were part of the function.
3923 for (unsigned i = 0; i < Blocks.size(); i++) {
3924
3925 CollectBlockDeclRefInfo(Blocks[i]);
3926
3927 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
Mike Stump11289f42009-09-09 15:08:12 +00003928
3929 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
Steve Naroff677ab3a2008-10-27 17:20:55 +00003930 ImportedBlockDecls.size() > 0);
3931
3932 InsertText(FunLocStart, CI.c_str(), CI.size());
3933
3934 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
Mike Stump11289f42009-09-09 15:08:12 +00003935
Steve Naroff677ab3a2008-10-27 17:20:55 +00003936 InsertText(FunLocStart, CF.c_str(), CF.size());
3937
3938 if (ImportedBlockDecls.size()) {
3939 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3940 InsertText(FunLocStart, HF.c_str(), HF.size());
3941 }
Mike Stump11289f42009-09-09 15:08:12 +00003942
Steve Naroff677ab3a2008-10-27 17:20:55 +00003943 BlockDeclRefs.clear();
3944 BlockByRefDecls.clear();
3945 BlockByCopyDecls.clear();
3946 BlockCallExprs.clear();
3947 ImportedBlockDecls.clear();
3948 }
3949 Blocks.clear();
3950 RewrittenBlockExprs.clear();
3951}
3952
3953void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3954 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner86d7d912008-11-24 03:54:41 +00003955 const char *FuncName = FD->getNameAsCString();
Mike Stump11289f42009-09-09 15:08:12 +00003956
Steve Naroff677ab3a2008-10-27 17:20:55 +00003957 SynthesizeBlockLiterals(FunLocStart, FuncName);
3958}
3959
3960void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff295570a2008-10-30 12:09:33 +00003961 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3962 //SourceLocation FunLocStart = MD->getLocStart();
3963 // FIXME: This hack works around a bug in Rewrite.InsertText().
3964 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattnere4b95692008-11-24 03:33:13 +00003965 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003966 // Convert colons to underscores.
3967 std::string::size_type loc = 0;
3968 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3969 FuncName.replace(loc, 1, "_");
Mike Stump11289f42009-09-09 15:08:12 +00003970
Steve Naroff677ab3a2008-10-27 17:20:55 +00003971 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3972}
3973
3974void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3975 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3976 CI != E; ++CI)
3977 if (*CI) {
3978 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3979 GetBlockDeclRefExprs(CBE->getBody());
3980 else
3981 GetBlockDeclRefExprs(*CI);
3982 }
3983 // Handle specific things.
3984 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3985 // FIXME: Handle enums.
3986 if (!isa<FunctionDecl>(CDRE->getDecl()))
3987 BlockDeclRefs.push_back(CDRE);
3988 return;
3989}
3990
3991void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3992 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3993 CI != E; ++CI)
3994 if (*CI) {
3995 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3996 GetBlockCallExprs(CBE->getBody());
3997 else
3998 GetBlockCallExprs(*CI);
3999 }
Mike Stump11289f42009-09-09 15:08:12 +00004000
Steve Naroff677ab3a2008-10-27 17:20:55 +00004001 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4002 if (CE->getCallee()->getType()->isBlockPointerType()) {
4003 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
4004 }
4005 }
4006 return;
4007}
4008
Steve Naroff350b6652008-10-30 10:07:53 +00004009Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004010 // Navigate to relevant type information.
4011 const char *closureName = 0;
4012 const BlockPointerType *CPT = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004013
Steve Naroff677ab3a2008-10-27 17:20:55 +00004014 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004015 closureName = DRE->getDecl()->getNameAsCString();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004016 CPT = DRE->getType()->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004017 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004018 closureName = CDRE->getDecl()->getNameAsCString();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004019 CPT = CDRE->getType()->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004020 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004021 closureName = MExpr->getMemberDecl()->getNameAsCString();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004022 CPT = MExpr->getType()->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004023 } else {
4024 assert(1 && "RewriteBlockClass: Bad type");
4025 }
4026 assert(CPT && "RewriteBlockClass: Bad type");
John McCall9dd450b2009-09-21 23:43:11 +00004027 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004028 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004029 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004030 // FTP will be null for closures that don't take arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004031
Steve Naroff350b6652008-10-30 10:07:53 +00004032 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
4033 SourceLocation(),
4034 &Context->Idents.get("__block_impl"));
4035 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff677ab3a2008-10-27 17:20:55 +00004036
Steve Naroff350b6652008-10-30 10:07:53 +00004037 // Generate a funky cast.
4038 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00004039
Steve Naroff350b6652008-10-30 10:07:53 +00004040 // Push the block argument type.
4041 ArgTypes.push_back(PtrBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004042 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004043 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff350b6652008-10-30 10:07:53 +00004044 E = FTP->arg_type_end(); I && (I != E); ++I) {
4045 QualType t = *I;
4046 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00004047 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004048 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff350b6652008-10-30 10:07:53 +00004049 t = Context->getPointerType(BPT->getPointeeType());
4050 }
4051 ArgTypes.push_back(t);
4052 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004053 }
Steve Naroff350b6652008-10-30 10:07:53 +00004054 // Now do the pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00004055 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Steve Naroff350b6652008-10-30 10:07:53 +00004056 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004057
Steve Naroff350b6652008-10-30 10:07:53 +00004058 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump11289f42009-09-09 15:08:12 +00004059
4060 CastExpr *BlkCast = new (Context) CStyleCastExpr(PtrBlock,
Anders Carlssona2615922009-07-31 00:48:10 +00004061 CastExpr::CK_Unknown,
4062 Exp->getCallee(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004063 PtrBlock, SourceLocation(),
4064 SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004065 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00004066 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4067 BlkCast);
Steve Naroff350b6652008-10-30 10:07:53 +00004068 //PE->dump();
Mike Stump11289f42009-09-09 15:08:12 +00004069
Douglas Gregor91f84212008-12-11 16:49:14 +00004070 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00004071 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004072 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek5a201952009-02-07 01:47:29 +00004073 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4074 FD->getType());
Mike Stump11289f42009-09-09 15:08:12 +00004075
Anders Carlssona2615922009-07-31 00:48:10 +00004076 CastExpr *FunkCast = new (Context) CStyleCastExpr(PtrToFuncCastType,
4077 CastExpr::CK_Unknown, ME,
Ted Kremenek5a201952009-02-07 01:47:29 +00004078 PtrToFuncCastType,
4079 SourceLocation(),
4080 SourceLocation());
4081 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump11289f42009-09-09 15:08:12 +00004082
Steve Naroff350b6652008-10-30 10:07:53 +00004083 llvm::SmallVector<Expr*, 8> BlkExprs;
4084 // Add the implicit argument.
4085 BlkExprs.push_back(BlkCast);
4086 // Add the user arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004087 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004088 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00004089 BlkExprs.push_back(*I);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004090 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004091 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4092 BlkExprs.size(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004093 Exp->getType(), SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004094 return CE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004095}
4096
4097void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Steve Naroff350b6652008-10-30 10:07:53 +00004098 Stmt *BlockCall = SynthesizeBlockCall(Exp);
4099 ReplaceStmt(Exp, BlockCall);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004100}
4101
Steve Naroffd9803712009-04-29 16:37:50 +00004102// We need to return the rewritten expression to handle cases where the
4103// BlockDeclRefExpr is embedded in another expression being rewritten.
4104// For example:
4105//
4106// int main() {
4107// __block Foo *f;
4108// __block int i;
Mike Stump11289f42009-09-09 15:08:12 +00004109//
Steve Naroffd9803712009-04-29 16:37:50 +00004110// void (^myblock)() = ^() {
4111// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4112// i = 77;
4113// };
4114//}
4115Stmt *RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004116 // FIXME: Add more elaborate code generation required by the ABI.
Ted Kremenek5a201952009-02-07 01:47:29 +00004117 Expr *DerefExpr = new (Context) UnaryOperator(BDRE, UnaryOperator::Deref,
Steve Narofff26a1d42009-02-02 17:19:26 +00004118 Context->getPointerType(BDRE->getType()),
4119 SourceLocation());
4120 // Need parens to enforce precedence.
Ted Kremenek5a201952009-02-07 01:47:29 +00004121 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), DerefExpr);
Steve Narofff26a1d42009-02-02 17:19:26 +00004122 ReplaceStmt(BDRE, PE);
Steve Naroffd9803712009-04-29 16:37:50 +00004123 return PE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004124}
4125
Steve Naroffc989a7b2008-11-03 23:29:32 +00004126void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4127 SourceLocation LocStart = CE->getLParenLoc();
4128 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofff4b992a2008-10-28 20:29:00 +00004129
4130 // Need to avoid trying to rewrite synthesized casts.
4131 if (LocStart.isInvalid())
4132 return;
Steve Naroff3e7ced12008-11-03 11:20:24 +00004133 // Need to avoid trying to rewrite casts contained in macros.
4134 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4135 return;
Mike Stump11289f42009-09-09 15:08:12 +00004136
Steve Naroff677ab3a2008-10-27 17:20:55 +00004137 const char *startBuf = SM->getCharacterData(LocStart);
4138 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00004139
Steve Naroff677ab3a2008-10-27 17:20:55 +00004140 // advance the location to startArgList.
4141 const char *argPtr = startBuf;
Mike Stump11289f42009-09-09 15:08:12 +00004142
Steve Naroff677ab3a2008-10-27 17:20:55 +00004143 while (*argPtr++ && (argPtr < endBuf)) {
4144 switch (*argPtr) {
Mike Stump11289f42009-09-09 15:08:12 +00004145 case '^':
Steve Naroff677ab3a2008-10-27 17:20:55 +00004146 // Replace the '^' with '*'.
4147 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
4148 ReplaceText(LocStart, 1, "*", 1);
4149 break;
4150 }
4151 }
4152 return;
4153}
4154
4155void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4156 SourceLocation DeclLoc = FD->getLocation();
4157 unsigned parenCount = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004158
Steve Naroff677ab3a2008-10-27 17:20:55 +00004159 // We have 1 or more arguments that have closure pointers.
4160 const char *startBuf = SM->getCharacterData(DeclLoc);
4161 const char *startArgList = strchr(startBuf, '(');
Mike Stump11289f42009-09-09 15:08:12 +00004162
Steve Naroff677ab3a2008-10-27 17:20:55 +00004163 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004164
Steve Naroff677ab3a2008-10-27 17:20:55 +00004165 parenCount++;
4166 // advance the location to startArgList.
4167 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4168 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump11289f42009-09-09 15:08:12 +00004169
Steve Naroff677ab3a2008-10-27 17:20:55 +00004170 const char *argPtr = startArgList;
Mike Stump11289f42009-09-09 15:08:12 +00004171
Steve Naroff677ab3a2008-10-27 17:20:55 +00004172 while (*argPtr++ && parenCount) {
4173 switch (*argPtr) {
Mike Stump11289f42009-09-09 15:08:12 +00004174 case '^':
Steve Naroff677ab3a2008-10-27 17:20:55 +00004175 // Replace the '^' with '*'.
4176 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
4177 ReplaceText(DeclLoc, 1, "*", 1);
4178 break;
Mike Stump11289f42009-09-09 15:08:12 +00004179 case '(':
4180 parenCount++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004181 break;
Mike Stump11289f42009-09-09 15:08:12 +00004182 case ')':
Steve Naroff677ab3a2008-10-27 17:20:55 +00004183 parenCount--;
4184 break;
4185 }
4186 }
4187 return;
4188}
4189
4190bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004191 const FunctionProtoType *FTP;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004192 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004193 if (PT) {
John McCall9dd450b2009-09-21 23:43:11 +00004194 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004195 } else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004196 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004197 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall9dd450b2009-09-21 23:43:11 +00004198 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004199 }
4200 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004201 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004202 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +00004203 if (isTopLevelBlockPointerType(*I))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004204 return true;
4205 }
4206 return false;
4207}
4208
Ted Kremenek5a201952009-02-07 01:47:29 +00004209void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4210 const char *&RParen) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004211 const char *argPtr = strchr(Name, '(');
4212 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004213
Steve Naroff677ab3a2008-10-27 17:20:55 +00004214 LParen = argPtr; // output the start.
4215 argPtr++; // skip past the left paren.
4216 unsigned parenCount = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004217
Steve Naroff677ab3a2008-10-27 17:20:55 +00004218 while (*argPtr && parenCount) {
4219 switch (*argPtr) {
4220 case '(': parenCount++; break;
4221 case ')': parenCount--; break;
4222 default: break;
4223 }
4224 if (parenCount) argPtr++;
4225 }
4226 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4227 RParen = argPtr; // output the end
4228}
4229
4230void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4231 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4232 RewriteBlockPointerFunctionArgs(FD);
4233 return;
Mike Stump11289f42009-09-09 15:08:12 +00004234 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004235 // Handle Variables and Typedefs.
4236 SourceLocation DeclLoc = ND->getLocation();
4237 QualType DeclT;
4238 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4239 DeclT = VD->getType();
4240 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4241 DeclT = TDD->getUnderlyingType();
4242 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4243 DeclT = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004244 else
Steve Naroff677ab3a2008-10-27 17:20:55 +00004245 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump11289f42009-09-09 15:08:12 +00004246
Steve Naroff677ab3a2008-10-27 17:20:55 +00004247 const char *startBuf = SM->getCharacterData(DeclLoc);
4248 const char *endBuf = startBuf;
4249 // scan backward (from the decl location) for the end of the previous decl.
4250 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4251 startBuf--;
Mike Stump11289f42009-09-09 15:08:12 +00004252
Steve Naroff677ab3a2008-10-27 17:20:55 +00004253 // *startBuf != '^' if we are dealing with a pointer to function that
4254 // may take block argument types (which will be handled below).
4255 if (*startBuf == '^') {
4256 // Replace the '^' with '*', computing a negative offset.
4257 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4258 ReplaceText(DeclLoc, 1, "*", 1);
4259 }
4260 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4261 // Replace the '^' with '*' for arguments.
4262 DeclLoc = ND->getLocation();
4263 startBuf = SM->getCharacterData(DeclLoc);
4264 const char *argListBegin, *argListEnd;
4265 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4266 while (argListBegin < argListEnd) {
4267 if (*argListBegin == '^') {
4268 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
4269 ReplaceText(CaretLoc, 1, "*", 1);
4270 }
4271 argListBegin++;
4272 }
4273 }
4274 return;
4275}
4276
Mike Stump11289f42009-09-09 15:08:12 +00004277void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004278 // Add initializers for any closure decl refs.
4279 GetBlockDeclRefExprs(Exp->getBody());
4280 if (BlockDeclRefs.size()) {
4281 // Unique all "by copy" declarations.
4282 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4283 if (!BlockDeclRefs[i]->isByRef())
4284 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
4285 // Unique all "by ref" declarations.
4286 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4287 if (BlockDeclRefs[i]->isByRef()) {
4288 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
4289 }
4290 // Find any imported blocks...they will need special attention.
4291 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Steve Naroff5ac4eac2008-12-11 20:51:38 +00004292 if (BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroff832d8902008-11-13 17:40:07 +00004293 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004294 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4295 }
4296 }
4297}
4298
Steve Narofff4b992a2008-10-28 20:29:00 +00004299FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4300 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004301 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump11289f42009-09-09 15:08:12 +00004302 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004303 ID, FType, 0, FunctionDecl::Extern, false,
Douglas Gregor739ef0c2009-02-25 16:33:18 +00004304 false);
Steve Narofff4b992a2008-10-28 20:29:00 +00004305}
4306
Steve Naroffd8907b72008-10-29 18:15:37 +00004307Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004308 Blocks.push_back(Exp);
4309
4310 CollectBlockDeclRefInfo(Exp);
4311 std::string FuncName;
Mike Stump11289f42009-09-09 15:08:12 +00004312
Steve Narofff4b992a2008-10-28 20:29:00 +00004313 if (CurFunctionDef)
Chris Lattnere4b95692008-11-24 03:33:13 +00004314 FuncName = CurFunctionDef->getNameAsString();
Steve Narofff4b992a2008-10-28 20:29:00 +00004315 else if (CurMethodDef) {
Chris Lattnere4b95692008-11-24 03:33:13 +00004316 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofff4b992a2008-10-28 20:29:00 +00004317 // Convert colons to underscores.
4318 std::string::size_type loc = 0;
4319 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4320 FuncName.replace(loc, 1, "_");
Steve Naroffd8907b72008-10-29 18:15:37 +00004321 } else if (GlobalVarDecl)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004322 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump11289f42009-09-09 15:08:12 +00004323
Steve Narofff4b992a2008-10-28 20:29:00 +00004324 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump11289f42009-09-09 15:08:12 +00004325
Steve Narofff4b992a2008-10-28 20:29:00 +00004326 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4327 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump11289f42009-09-09 15:08:12 +00004328
Steve Narofff4b992a2008-10-28 20:29:00 +00004329 // Get a pointer to the function type so we can cast appropriately.
4330 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4331
4332 FunctionDecl *FD;
4333 Expr *NewRep;
Mike Stump11289f42009-09-09 15:08:12 +00004334
Steve Narofff4b992a2008-10-28 20:29:00 +00004335 // Simulate a contructor call...
4336 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004337 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004338
Steve Narofff4b992a2008-10-28 20:29:00 +00004339 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00004340
Steve Naroffe2514232008-10-29 21:23:59 +00004341 // Initialize the block function.
Steve Narofff4b992a2008-10-28 20:29:00 +00004342 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004343 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4344 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004345 CastExpr *castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4346 CastExpr::CK_Unknown, Arg,
Ted Kremenek5a201952009-02-07 01:47:29 +00004347 Context->VoidPtrTy, SourceLocation(),
4348 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004349 InitExprs.push_back(castExpr);
4350
Steve Narofff4b992a2008-10-28 20:29:00 +00004351 if (ImportedBlockDecls.size()) {
4352 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
Steve Naroffe2514232008-10-29 21:23:59 +00004353 FD = SynthBlockInitFunctionDecl(Buf.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004354 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004355 castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4356 CastExpr::CK_Unknown, Arg,
Ted Kremenek5a201952009-02-07 01:47:29 +00004357 Context->VoidPtrTy, SourceLocation(),
4358 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004359 InitExprs.push_back(castExpr);
4360
Steve Narofff4b992a2008-10-28 20:29:00 +00004361 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
Steve Naroffe2514232008-10-29 21:23:59 +00004362 FD = SynthBlockInitFunctionDecl(Buf.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004363 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004364 castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4365 CastExpr::CK_Unknown, Arg,
Ted Kremenek5a201952009-02-07 01:47:29 +00004366 Context->VoidPtrTy, SourceLocation(),
4367 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004368 InitExprs.push_back(castExpr);
Steve Narofff4b992a2008-10-28 20:29:00 +00004369 }
4370 // Add initializers for any closure decl refs.
4371 if (BlockDeclRefs.size()) {
Steve Naroffe2514232008-10-29 21:23:59 +00004372 Expr *Exp;
Steve Narofff4b992a2008-10-28 20:29:00 +00004373 // Output all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004374 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004375 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004376 if (isObjCType((*I)->getType())) {
Steve Naroffe2514232008-10-29 21:23:59 +00004377 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner86d7d912008-11-24 03:54:41 +00004378 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004379 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroffa5c0db82008-12-11 21:05:33 +00004380 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004381 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004382 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004383 Exp = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4384 CastExpr::CK_Unknown, Arg,
4385 Context->VoidPtrTy,
Anders Carlssona2615922009-07-31 00:48:10 +00004386 SourceLocation(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004387 SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004388 } else {
Chris Lattner86d7d912008-11-24 03:54:41 +00004389 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004390 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004391 }
Mike Stump11289f42009-09-09 15:08:12 +00004392 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004393 }
4394 // Output all "by ref" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004395 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004396 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004397 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004398 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4399 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004400 Context->getPointerType(Exp->getType()),
Steve Naroffe2514232008-10-29 21:23:59 +00004401 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004402 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004403 }
4404 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004405 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4406 FType, SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00004407 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004408 Context->getPointerType(NewRep->getType()),
Steve Narofff4b992a2008-10-28 20:29:00 +00004409 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004410 NewRep = new (Context) CStyleCastExpr(FType, CastExpr::CK_Unknown, NewRep,
Anders Carlssona2615922009-07-31 00:48:10 +00004411 FType, SourceLocation(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004412 SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004413 BlockDeclRefs.clear();
4414 BlockByRefDecls.clear();
4415 BlockByCopyDecls.clear();
4416 ImportedBlockDecls.clear();
4417 return NewRep;
4418}
4419
4420//===----------------------------------------------------------------------===//
4421// Function Body / Expression rewriting
4422//===----------------------------------------------------------------------===//
4423
Steve Naroff4588d0f2008-12-04 16:24:46 +00004424// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4425// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4426// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4427// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4428// Since the rewriter isn't capable of rewriting rewritten code, it's important
4429// we get this right.
4430void RewriteObjC::CollectPropertySetters(Stmt *S) {
4431 // Perform a bottom up traversal of all children.
4432 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4433 CI != E; ++CI)
4434 if (*CI)
4435 CollectPropertySetters(*CI);
4436
4437 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4438 if (BinOp->isAssignmentOp()) {
4439 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4440 PropSetters[PRE] = BinOp;
4441 }
4442 }
4443}
4444
Steve Narofff4b992a2008-10-28 20:29:00 +00004445Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump11289f42009-09-09 15:08:12 +00004446 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004447 isa<DoStmt>(S) || isa<ForStmt>(S))
4448 Stmts.push_back(S);
4449 else if (isa<ObjCForCollectionStmt>(S)) {
4450 Stmts.push_back(S);
4451 ObjCBcLabelNo.push_back(++BcLabelCount);
4452 }
Mike Stump11289f42009-09-09 15:08:12 +00004453
Steve Narofff4b992a2008-10-28 20:29:00 +00004454 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004455
Steve Narofff4b992a2008-10-28 20:29:00 +00004456 // Perform a bottom up rewrite of all children.
4457 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4458 CI != E; ++CI)
4459 if (*CI) {
4460 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Mike Stump11289f42009-09-09 15:08:12 +00004461 if (newStmt)
Steve Narofff4b992a2008-10-28 20:29:00 +00004462 *CI = newStmt;
4463 }
Mike Stump11289f42009-09-09 15:08:12 +00004464
Steve Narofff4b992a2008-10-28 20:29:00 +00004465 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4466 // Rewrite the block body in place.
4467 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Mike Stump11289f42009-09-09 15:08:12 +00004468
Steve Narofff4b992a2008-10-28 20:29:00 +00004469 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroffd8907b72008-10-29 18:15:37 +00004470 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
4471 RewrittenBlockExprs[BE] = Str;
Mike Stump11289f42009-09-09 15:08:12 +00004472
Steve Narofff4b992a2008-10-28 20:29:00 +00004473 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4474 //blockTranscribed->dump();
Steve Naroffd8907b72008-10-29 18:15:37 +00004475 ReplaceStmt(S, blockTranscribed);
Steve Narofff4b992a2008-10-28 20:29:00 +00004476 return blockTranscribed;
4477 }
4478 // Handle specific things.
4479 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4480 return RewriteAtEncode(AtEncode);
Mike Stump11289f42009-09-09 15:08:12 +00004481
Steve Narofff4b992a2008-10-28 20:29:00 +00004482 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4483 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4484
Steve Naroff4588d0f2008-12-04 16:24:46 +00004485 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4486 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4487 if (BinOp) {
4488 // Because the rewriter doesn't allow us to rewrite rewritten code,
4489 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroff08628db2008-12-09 12:56:34 +00004490 DisableReplaceStmt = true;
4491 // Save the source range. Even if we disable the replacement, the
4492 // rewritten node will have been inserted into the tree. If the synthesized
4493 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump11289f42009-09-09 15:08:12 +00004494 // self.errorHandler = handler ? handler :
Steve Naroff08628db2008-12-09 12:56:34 +00004495 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4496 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroff4588d0f2008-12-04 16:24:46 +00004497 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroff08628db2008-12-09 12:56:34 +00004498 DisableReplaceStmt = false;
Steve Naroff22216db2008-12-04 23:50:32 +00004499 //
4500 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4501 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4502 // to see the original expression). Consider this example:
4503 //
4504 // Foo *obj1, *obj2;
4505 //
4506 // obj1.i = [obj2 rrrr];
4507 //
4508 // 'BinOp' for the previous expression looks like:
4509 //
4510 // (BinaryOperator 0x231ccf0 'int' '='
4511 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4512 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4513 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4514 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4515 //
4516 // 'newStmt' represents the rewritten message expression. For example:
4517 //
4518 // (CallExpr 0x231d300 'id':'struct objc_object *'
4519 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4520 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4521 // (CStyleCastExpr 0x231d220 'void *'
4522 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4523 //
4524 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4525 // can be used as the setter argument. ReplaceStmt() will still 'see'
4526 // the original RHS (since we haven't altered BinOp).
4527 //
Mike Stump11289f42009-09-09 15:08:12 +00004528 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff22216db2008-12-04 23:50:32 +00004529 // node. As a result, we now leak the original AST nodes.
4530 //
Steve Naroff08628db2008-12-09 12:56:34 +00004531 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroff4588d0f2008-12-04 16:24:46 +00004532 } else {
4533 return RewritePropertyGetter(PropRefExpr);
Steve Narofff326f402008-12-03 00:56:33 +00004534 }
4535 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004536 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4537 return RewriteAtSelector(AtSelector);
Mike Stump11289f42009-09-09 15:08:12 +00004538
Steve Narofff4b992a2008-10-28 20:29:00 +00004539 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4540 return RewriteObjCStringLiteral(AtString);
Mike Stump11289f42009-09-09 15:08:12 +00004541
Steve Narofff4b992a2008-10-28 20:29:00 +00004542 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00004543#if 0
Steve Narofff4b992a2008-10-28 20:29:00 +00004544 // Before we rewrite it, put the original message expression in a comment.
4545 SourceLocation startLoc = MessExpr->getLocStart();
4546 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00004547
Steve Narofff4b992a2008-10-28 20:29:00 +00004548 const char *startBuf = SM->getCharacterData(startLoc);
4549 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004550
Steve Narofff4b992a2008-10-28 20:29:00 +00004551 std::string messString;
4552 messString += "// ";
4553 messString.append(startBuf, endBuf-startBuf+1);
4554 messString += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00004555
4556 // FIXME: Missing definition of
Steve Narofff4b992a2008-10-28 20:29:00 +00004557 // InsertText(clang::SourceLocation, char const*, unsigned int).
4558 // InsertText(startLoc, messString.c_str(), messString.size());
4559 // Tried this, but it didn't work either...
4560 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff4588d0f2008-12-04 16:24:46 +00004561#endif
Steve Narofff4b992a2008-10-28 20:29:00 +00004562 return RewriteMessageExpr(MessExpr);
4563 }
Mike Stump11289f42009-09-09 15:08:12 +00004564
Steve Narofff4b992a2008-10-28 20:29:00 +00004565 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4566 return RewriteObjCTryStmt(StmtTry);
4567
4568 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4569 return RewriteObjCSynchronizedStmt(StmtTry);
4570
4571 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4572 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump11289f42009-09-09 15:08:12 +00004573
Steve Narofff4b992a2008-10-28 20:29:00 +00004574 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4575 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump11289f42009-09-09 15:08:12 +00004576
4577 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofff4b992a2008-10-28 20:29:00 +00004578 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump11289f42009-09-09 15:08:12 +00004579 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofff4b992a2008-10-28 20:29:00 +00004580 OrigStmtRange.getEnd());
4581 if (BreakStmt *StmtBreakStmt =
4582 dyn_cast<BreakStmt>(S))
4583 return RewriteBreakStmt(StmtBreakStmt);
4584 if (ContinueStmt *StmtContinueStmt =
4585 dyn_cast<ContinueStmt>(S))
4586 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump11289f42009-09-09 15:08:12 +00004587
4588 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofff4b992a2008-10-28 20:29:00 +00004589 // and cast exprs.
4590 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4591 // FIXME: What we're doing here is modifying the type-specifier that
4592 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump11289f42009-09-09 15:08:12 +00004593 // a separate type-specifier that we can rewrite.
Steve Naroffe70a52a2009-12-05 15:55:59 +00004594 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4595 // the context of an ObjCForCollectionStmt. For example:
4596 // NSArray *someArray;
4597 // for (id <FooProtocol> index in someArray) ;
4598 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4599 // and it depends on the original text locations/positions.
Benjamin Krameracc5fa12009-12-05 22:16:51 +00004600 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroffe70a52a2009-12-05 15:55:59 +00004601 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump11289f42009-09-09 15:08:12 +00004602
Steve Narofff4b992a2008-10-28 20:29:00 +00004603 // Blocks rewrite rules.
4604 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4605 DI != DE; ++DI) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004606 Decl *SD = *DI;
Steve Narofff4b992a2008-10-28 20:29:00 +00004607 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004608 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004609 RewriteBlockPointerDecl(ND);
Mike Stump11289f42009-09-09 15:08:12 +00004610 else if (ND->getType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004611 CheckFunctionPointerDecl(ND->getType(), ND);
4612 }
4613 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004614 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004615 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00004616 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004617 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4618 }
4619 }
4620 }
Mike Stump11289f42009-09-09 15:08:12 +00004621
Steve Narofff4b992a2008-10-28 20:29:00 +00004622 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4623 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump11289f42009-09-09 15:08:12 +00004624
4625 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004626 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4627 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump11289f42009-09-09 15:08:12 +00004628 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4629 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004630 && "Statement stack mismatch");
4631 Stmts.pop_back();
4632 }
4633 // Handle blocks rewriting.
4634 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4635 if (BDRE->isByRef())
Steve Naroffd9803712009-04-29 16:37:50 +00004636 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofff4b992a2008-10-28 20:29:00 +00004637 }
4638 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff350b6652008-10-30 10:07:53 +00004639 if (CE->getCallee()->getType()->isBlockPointerType()) {
4640 Stmt *BlockCall = SynthesizeBlockCall(CE);
4641 ReplaceStmt(S, BlockCall);
4642 return BlockCall;
4643 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004644 }
Steve Naroffc989a7b2008-11-03 23:29:32 +00004645 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004646 RewriteCastExpr(CE);
4647 }
4648#if 0
4649 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek5a201952009-02-07 01:47:29 +00004650 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004651 // Get the new text.
4652 std::string SStr;
4653 llvm::raw_string_ostream Buf(SStr);
Eli Friedman0905f142009-05-30 05:19:26 +00004654 Replacement->printPretty(Buf, *Context);
Steve Narofff4b992a2008-10-28 20:29:00 +00004655 const std::string &Str = Buf.str();
4656
4657 printf("CAST = %s\n", &Str[0]);
4658 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4659 delete S;
4660 return Replacement;
4661 }
4662#endif
4663 // Return this stmt unmodified.
4664 return S;
4665}
4666
Steve Naroffe70a52a2009-12-05 15:55:59 +00004667void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
4668 for (RecordDecl::field_iterator i = RD->field_begin(),
4669 e = RD->field_end(); i != e; ++i) {
4670 FieldDecl *FD = *i;
4671 if (isTopLevelBlockPointerType(FD->getType()))
4672 RewriteBlockPointerDecl(FD);
4673 if (FD->getType()->isObjCQualifiedIdType() ||
4674 FD->getType()->isObjCQualifiedInterfaceType())
4675 RewriteObjCQualifiedInterfaceTypes(FD);
4676 }
4677}
4678
Steve Narofff4b992a2008-10-28 20:29:00 +00004679/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4680/// main file of the input.
4681void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4682 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffb1368882008-12-17 00:20:22 +00004683 if (FD->isOverloadedOperator())
4684 return;
Mike Stump11289f42009-09-09 15:08:12 +00004685
Steve Narofff4b992a2008-10-28 20:29:00 +00004686 // Since function prototypes don't have ParmDecl's, we check the function
4687 // prototype. This enables us to rewrite function declarations and
4688 // definitions using the same code.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004689 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofff4b992a2008-10-28 20:29:00 +00004690
Sebastian Redla7b98a72009-04-26 20:35:05 +00004691 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00004692 if (CompoundStmt *Body = FD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004693 CurFunctionDef = FD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00004694 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00004695 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00004696 Body =
4697 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4698 FD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00004699 CurrentBody = 0;
4700 if (PropParentMap) {
4701 delete PropParentMap;
4702 PropParentMap = 0;
4703 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004704 // This synthesizes and inserts the block "impl" struct, invoke function,
4705 // and any copy/dispose helper functions.
4706 InsertBlockLiteralsWithinFunction(FD);
4707 CurFunctionDef = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004708 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004709 return;
4710 }
4711 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00004712 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004713 CurMethodDef = MD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00004714 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00004715 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00004716 Body =
4717 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4718 MD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00004719 CurrentBody = 0;
4720 if (PropParentMap) {
4721 delete PropParentMap;
4722 PropParentMap = 0;
4723 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004724 InsertBlockLiteralsWithinMethod(MD);
4725 CurMethodDef = 0;
4726 }
4727 }
4728 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
4729 ClassImplementation.push_back(CI);
4730 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4731 CategoryImplementation.push_back(CI);
4732 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4733 RewriteForwardClassDecl(CD);
4734 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4735 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroffa5c0db82008-12-11 21:05:33 +00004736 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004737 RewriteBlockPointerDecl(VD);
Steve Naroffd8907b72008-10-29 18:15:37 +00004738 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004739 CheckFunctionPointerDecl(VD->getType(), VD);
4740 if (VD->getInit()) {
Steve Naroffc989a7b2008-11-03 23:29:32 +00004741 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004742 RewriteCastExpr(CE);
4743 }
4744 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00004745 } else if (VD->getType()->isRecordType()) {
4746 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4747 if (RD->isDefinition())
4748 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00004749 }
Steve Naroffd8907b72008-10-29 18:15:37 +00004750 if (VD->getInit()) {
4751 GlobalVarDecl = VD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00004752 CollectPropertySetters(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00004753 CurrentBody = VD->getInit();
Steve Naroffd8907b72008-10-29 18:15:37 +00004754 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00004755 CurrentBody = 0;
4756 if (PropParentMap) {
4757 delete PropParentMap;
4758 PropParentMap = 0;
4759 }
Mike Stump11289f42009-09-09 15:08:12 +00004760 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner86d7d912008-11-24 03:54:41 +00004761 VD->getNameAsCString());
Steve Naroffd8907b72008-10-29 18:15:37 +00004762 GlobalVarDecl = 0;
4763
4764 // This is needed for blocks.
Steve Naroffc989a7b2008-11-03 23:29:32 +00004765 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroffd8907b72008-10-29 18:15:37 +00004766 RewriteCastExpr(CE);
4767 }
4768 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004769 return;
4770 }
4771 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004772 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004773 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00004774 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004775 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Steve Naroffe70a52a2009-12-05 15:55:59 +00004776 else if (TD->getUnderlyingType()->isRecordType()) {
4777 RecordDecl *RD = TD->getUnderlyingType()->getAs<RecordType>()->getDecl();
4778 if (RD->isDefinition())
4779 RewriteRecordBody(RD);
4780 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004781 return;
4782 }
4783 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroffe70a52a2009-12-05 15:55:59 +00004784 if (RD->isDefinition())
4785 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00004786 return;
4787 }
4788 // Nothing yet.
4789}
4790
Chris Lattnercf169832009-03-28 04:11:33 +00004791void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004792 // Get the top-level buffer that this corresponds to.
Mike Stump11289f42009-09-09 15:08:12 +00004793
Steve Narofff4b992a2008-10-28 20:29:00 +00004794 // Rewrite tabs if we care.
4795 //RewriteTabs();
Mike Stump11289f42009-09-09 15:08:12 +00004796
Steve Narofff4b992a2008-10-28 20:29:00 +00004797 if (Diags.hasErrorOccurred())
4798 return;
Mike Stump11289f42009-09-09 15:08:12 +00004799
Steve Narofff4b992a2008-10-28 20:29:00 +00004800 RewriteInclude();
Mike Stump11289f42009-09-09 15:08:12 +00004801
Steve Naroffd9803712009-04-29 16:37:50 +00004802 // Here's a great place to add any extra declarations that may be needed.
4803 // Write out meta data for each @protocol(<expr>).
Mike Stump11289f42009-09-09 15:08:12 +00004804 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00004805 E = ProtocolExprDecls.end(); I != E; ++I)
4806 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
4807
Mike Stump11289f42009-09-09 15:08:12 +00004808 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Narofff4b992a2008-10-28 20:29:00 +00004809 Preamble.c_str(), Preamble.size(), false);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00004810 if (ClassImplementation.size() || CategoryImplementation.size())
4811 RewriteImplementations();
Steve Naroffd9803712009-04-29 16:37:50 +00004812
Steve Narofff4b992a2008-10-28 20:29:00 +00004813 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4814 // we are done.
Mike Stump11289f42009-09-09 15:08:12 +00004815 if (const RewriteBuffer *RewriteBuf =
Steve Narofff4b992a2008-10-28 20:29:00 +00004816 Rewrite.getRewriteBufferFor(MainFileID)) {
4817 //printf("Changed:\n");
4818 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4819 } else {
4820 fprintf(stderr, "No changes\n");
4821 }
Steve Narofff8cfd162008-11-13 20:07:04 +00004822
Steve Naroffd9803712009-04-29 16:37:50 +00004823 if (ClassImplementation.size() || CategoryImplementation.size() ||
4824 ProtocolExprDecls.size()) {
Steve Naroff2a2a41f2008-11-14 14:10:01 +00004825 // Rewrite Objective-c meta data*
4826 std::string ResultStr;
4827 SynthesizeMetaDataIntoBuffer(ResultStr);
4828 // Emit metadata.
4829 *OutFile << ResultStr;
4830 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004831 OutFile->flush();
4832}
4833