blob: 9fc0669ca34b4cd544e5205cccc7ef1167e9e927 [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 Naroff2b3843d2009-12-06 01:33:56 +0000558 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
559 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 Naroffdad80ba2008-03-15 01:36:04 +00002243 // The minus 2 removes the begin/end double quotes.
Steve Naroff00a31762008-03-27 22:29:16 +00002244 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002245
2246 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2247 &Context->Idents.get(S.c_str()), strType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002248 VarDecl::Static);
Ted Kremenek5a201952009-02-07 01:47:29 +00002249 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2250 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002251 Context->getPointerType(DRE->getType()),
Steve Naroffce8e8862008-03-15 00:55:56 +00002252 SourceLocation());
Steve Naroff265a6b92007-11-08 14:30:50 +00002253 // cast to NSConstantString *
Mike Stump11289f42009-09-09 15:08:12 +00002254 CastExpr *cast = new (Context) CStyleCastExpr(Exp->getType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002255 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002256 Unop, Exp->getType(),
2257 SourceLocation(),
Anders Carlssona2615922009-07-31 00:48:10 +00002258 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002259 ReplaceStmt(Exp, cast);
Steve Naroff22216db2008-12-04 23:50:32 +00002260 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff265a6b92007-11-08 14:30:50 +00002261 return cast;
Steve Naroffa397efd2007-11-03 11:27:19 +00002262}
2263
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002264ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002265 // check if we are sending a message to 'super'
Douglas Gregorffca3a22009-01-09 17:18:27 +00002266 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002267
Douglas Gregor8ea1f532008-11-04 14:56:14 +00002268 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
Mike Stump11289f42009-09-09 15:08:12 +00002269 const ObjCObjectPointerType *OPT =
John McCall9dd450b2009-09-21 23:43:11 +00002270 Super->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00002271 assert(OPT);
2272 const ObjCInterfaceType *IT = OPT->getInterfaceType();
Chris Lattnera9b3cae2008-06-21 18:04:54 +00002273 return IT->getDecl();
2274 }
2275 return 0;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002276}
2277
2278// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002279QualType RewriteObjC::getSuperStructType() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002280 if (!SuperStructDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002281 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002282 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002283 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002284 QualType FieldTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002285
Steve Naroff7fa2f042007-11-15 10:28:18 +00002286 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002287 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002288 // struct objc_class *super;
Mike Stump11289f42009-09-09 15:08:12 +00002289 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor91f84212008-12-11 16:49:14 +00002290
Steve Naroff7fa2f042007-11-15 10:28:18 +00002291 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002292 for (unsigned i = 0; i < 2; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002293 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2294 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002295 FieldTypes[i], 0,
2296 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002297 /*Mutable=*/false));
Douglas Gregor91f84212008-12-11 16:49:14 +00002298 }
Mike Stump11289f42009-09-09 15:08:12 +00002299
Douglas Gregor91f84212008-12-11 16:49:14 +00002300 SuperStructDecl->completeDefinition(*Context);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002301 }
2302 return Context->getTagDeclType(SuperStructDecl);
2303}
2304
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002305QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffce8e8862008-03-15 00:55:56 +00002306 if (!ConstantStringDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002307 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002308 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002309 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffce8e8862008-03-15 00:55:56 +00002310 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002311
Steve Naroffce8e8862008-03-15 00:55:56 +00002312 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002313 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffce8e8862008-03-15 00:55:56 +00002314 // int flags;
Mike Stump11289f42009-09-09 15:08:12 +00002315 FieldTypes[1] = Context->IntTy;
Steve Naroffce8e8862008-03-15 00:55:56 +00002316 // char *str;
Mike Stump11289f42009-09-09 15:08:12 +00002317 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffce8e8862008-03-15 00:55:56 +00002318 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002319 FieldTypes[3] = Context->LongTy;
Douglas Gregor91f84212008-12-11 16:49:14 +00002320
Steve Naroffce8e8862008-03-15 00:55:56 +00002321 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002322 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002323 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2324 ConstantStringDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002325 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002326 FieldTypes[i], 0,
Douglas Gregor91f84212008-12-11 16:49:14 +00002327 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002328 /*Mutable=*/true));
Douglas Gregor91f84212008-12-11 16:49:14 +00002329 }
2330
2331 ConstantStringDecl->completeDefinition(*Context);
Steve Naroffce8e8862008-03-15 00:55:56 +00002332 }
2333 return Context->getTagDeclType(ConstantStringDecl);
2334}
2335
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002336Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002337 if (!SelGetUidFunctionDecl)
2338 SynthSelGetUidFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002339 if (!MsgSendFunctionDecl)
2340 SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002341 if (!MsgSendSuperFunctionDecl)
2342 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002343 if (!MsgSendStretFunctionDecl)
2344 SynthMsgSendStretFunctionDecl();
2345 if (!MsgSendSuperStretFunctionDecl)
2346 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002347 if (!MsgSendFpretFunctionDecl)
2348 SynthMsgSendFpretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002349 if (!GetClassFunctionDecl)
2350 SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002351 if (!GetMetaClassFunctionDecl)
2352 SynthGetMetaClassFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002353
Steve Naroff7fa2f042007-11-15 10:28:18 +00002354 // default to objc_msgSend().
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002355 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2356 // May need to use objc_msgSend_stret() as well.
2357 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroffd9803712009-04-29 16:37:50 +00002358 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2359 QualType resultType = mDecl->getResultType();
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002360 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002361 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002362 else if (resultType->isRealFloatingType())
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002363 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002364 }
Mike Stump11289f42009-09-09 15:08:12 +00002365
Steve Naroff574440f2007-10-24 22:48:43 +00002366 // Synthesize a call to objc_msgSend().
2367 llvm::SmallVector<Expr*, 8> MsgExprs;
2368 IdentifierInfo *clsName = Exp->getClassName();
Mike Stump11289f42009-09-09 15:08:12 +00002369
Steve Naroff574440f2007-10-24 22:48:43 +00002370 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2371 if (clsName) { // class message.
Steve Naroff6c79f972008-07-24 19:44:33 +00002372 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2373 // the 'super' idiom within a class method.
Daniel Dunbar07d07852009-10-18 21:17:35 +00002374 if (clsName->getName() == "super") {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002375 MsgSendFlavor = MsgSendSuperFunctionDecl;
2376 if (MsgSendStretFlavor)
2377 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2378 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002379
2380 ObjCInterfaceDecl *SuperDecl =
Steve Naroff677ab3a2008-10-27 17:20:55 +00002381 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002382
2383 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002384
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002385 // set the receiver to self, the first argument to all methods.
Steve Naroffd9803712009-04-29 16:37:50 +00002386 InitExprs.push_back(
Mike Stump11289f42009-09-09 15:08:12 +00002387 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002388 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002389 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroffd9803712009-04-29 16:37:50 +00002390 Context->getObjCIdType(),
2391 SourceLocation()),
2392 Context->getObjCIdType(),
2393 SourceLocation(), SourceLocation())); // set the 'receiver'.
2394
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002395 llvm::SmallVector<Expr*, 8> ClsExprs;
2396 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002397 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002398 SuperDecl->getIdentifier()->getNameStart(),
2399 SuperDecl->getIdentifier()->getLength(),
2400 false, argType, SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002401 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002402 &ClsExprs[0],
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002403 ClsExprs.size());
2404 // To turn off a warning, type-cast to 'id'
Douglas Gregore200adc2008-10-27 19:41:14 +00002405 InitExprs.push_back( // set 'super class', using objc_getClass().
Mike Stump11289f42009-09-09 15:08:12 +00002406 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002407 CastExpr::CK_Unknown,
Douglas Gregore200adc2008-10-27 19:41:14 +00002408 Cls, Context->getObjCIdType(),
Mike Stump11289f42009-09-09 15:08:12 +00002409 SourceLocation(), SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002410 // struct objc_super
2411 QualType superType = getSuperStructType();
Steve Naroff0b844f02008-03-11 18:14:26 +00002412 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002413
Steve Naroff0b844f02008-03-11 18:14:26 +00002414 if (LangOpts.Microsoft) {
2415 SynthSuperContructorFunctionDecl();
2416 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002417 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff0b844f02008-03-11 18:14:26 +00002418 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002419 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002420 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002421 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002422 // The code for super is a little tricky to prevent collision with
2423 // the structure definition in the header. The rewriter has it's own
2424 // internal definition (__rw_objc_super) that is uses. This is why
2425 // we need the cast below. For example:
2426 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2427 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002428 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002429 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002430 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002431 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
2432 CastExpr::CK_Unknown, SuperRep,
Anders Carlssona2615922009-07-31 00:48:10 +00002433 Context->getPointerType(superType),
Mike Stump11289f42009-09-09 15:08:12 +00002434 SourceLocation(), SourceLocation());
2435 } else {
Steve Naroff0b844f02008-03-11 18:14:26 +00002436 // (struct objc_super) { <exprs from above> }
Mike Stump11289f42009-09-09 15:08:12 +00002437 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2438 &InitExprs[0], InitExprs.size(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002439 SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00002440 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE,
Chris Lattner07d754a2008-10-26 23:43:26 +00002441 false);
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002442 // struct objc_super *
Ted Kremenek5a201952009-02-07 01:47:29 +00002443 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002444 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002445 SourceLocation());
Steve Naroff0b844f02008-03-11 18:14:26 +00002446 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002447 MsgExprs.push_back(SuperRep);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002448 } else {
2449 llvm::SmallVector<Expr*, 8> ClsExprs;
2450 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002451 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002452 clsName->getNameStart(),
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002453 clsName->getLength(),
2454 false, argType,
2455 SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002456 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002457 &ClsExprs[0],
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002458 ClsExprs.size());
2459 MsgExprs.push_back(Cls);
2460 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002461 } else { // instance message.
2462 Expr *recExpr = Exp->getReceiver();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002463
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002464 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002465 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002466 if (MsgSendStretFlavor)
2467 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002468 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002469
Steve Naroff7fa2f042007-11-15 10:28:18 +00002470 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002471
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002472 InitExprs.push_back(
Mike Stump11289f42009-09-09 15:08:12 +00002473 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002474 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002475 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff97adf602008-07-16 22:35:27 +00002476 Context->getObjCIdType(),
Douglas Gregore200adc2008-10-27 19:41:14 +00002477 SourceLocation()),
2478 Context->getObjCIdType(),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002479 SourceLocation(), SourceLocation())); // set the 'receiver'.
Mike Stump11289f42009-09-09 15:08:12 +00002480
Steve Naroff7fa2f042007-11-15 10:28:18 +00002481 llvm::SmallVector<Expr*, 8> ClsExprs;
2482 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002483 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002484 SuperDecl->getIdentifier()->getNameStart(),
2485 SuperDecl->getIdentifier()->getLength(),
2486 false, argType, SourceLocation()));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002487 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002488 &ClsExprs[0],
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002489 ClsExprs.size());
Fariborz Jahaniand5db92b2007-12-05 17:29:46 +00002490 // To turn off a warning, type-cast to 'id'
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002491 InitExprs.push_back(
Douglas Gregore200adc2008-10-27 19:41:14 +00002492 // set 'super class', using objc_getClass().
Mike Stump11289f42009-09-09 15:08:12 +00002493 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002494 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002495 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002496 // struct objc_super
2497 QualType superType = getSuperStructType();
Steve Naroff17978c42008-03-11 17:37:02 +00002498 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002499
Steve Naroff17978c42008-03-11 17:37:02 +00002500 if (LangOpts.Microsoft) {
2501 SynthSuperContructorFunctionDecl();
2502 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002503 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff17978c42008-03-11 17:37:02 +00002504 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002505 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002506 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002507 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002508 // The code for super is a little tricky to prevent collision with
2509 // the structure definition in the header. The rewriter has it's own
2510 // internal definition (__rw_objc_super) that is uses. This is why
2511 // we need the cast below. For example:
2512 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2513 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002514 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002515 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002516 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002517 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Anders Carlssona2615922009-07-31 00:48:10 +00002518 CastExpr::CK_Unknown,
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002519 SuperRep, Context->getPointerType(superType),
Mike Stump11289f42009-09-09 15:08:12 +00002520 SourceLocation(), SourceLocation());
Steve Naroff17978c42008-03-11 17:37:02 +00002521 } else {
2522 // (struct objc_super) { <exprs from above> }
Mike Stump11289f42009-09-09 15:08:12 +00002523 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2524 &InitExprs[0], InitExprs.size(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002525 SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00002526 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002527 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002528 MsgExprs.push_back(SuperRep);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002529 } else {
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002530 // Remove all type-casts because it may contain objc-style types; e.g.
2531 // Foo<Proto> *.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002532 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002533 recExpr = CE->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002534 recExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002535 CastExpr::CK_Unknown, recExpr,
Mike Stump11289f42009-09-09 15:08:12 +00002536 Context->getObjCIdType(),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002537 SourceLocation(), SourceLocation());
Steve Naroff7fa2f042007-11-15 10:28:18 +00002538 MsgExprs.push_back(recExpr);
2539 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002540 }
Steve Naroffa397efd2007-11-03 11:27:19 +00002541 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff574440f2007-10-24 22:48:43 +00002542 llvm::SmallVector<Expr*, 8> SelExprs;
2543 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002544 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002545 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002546 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00002547 false, argType, SourceLocation()));
Steve Naroff574440f2007-10-24 22:48:43 +00002548 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2549 &SelExprs[0], SelExprs.size());
2550 MsgExprs.push_back(SelExp);
Mike Stump11289f42009-09-09 15:08:12 +00002551
Steve Naroff574440f2007-10-24 22:48:43 +00002552 // Now push any user supplied arguments.
2553 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroffe7f18192007-11-14 23:54:14 +00002554 Expr *userExpr = Exp->getArg(i);
Steve Narofff60782b2007-11-15 02:58:25 +00002555 // Make all implicit casts explicit...ICE comes in handy:-)
2556 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2557 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregore200adc2008-10-27 19:41:14 +00002558 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002559 ? Context->getObjCIdType()
Douglas Gregore200adc2008-10-27 19:41:14 +00002560 : ICE->getType();
Anders Carlssona2615922009-07-31 00:48:10 +00002561 userExpr = new (Context) CStyleCastExpr(type, CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002562 userExpr, type, SourceLocation(),
Anders Carlssona2615922009-07-31 00:48:10 +00002563 SourceLocation());
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002564 }
2565 // Make id<P...> cast into an 'id' cast.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002566 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002567 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregorf19b2312008-10-28 15:36:24 +00002568 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002569 userExpr = CE->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002570 userExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002571 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002572 userExpr, Context->getObjCIdType(),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002573 SourceLocation(), SourceLocation());
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002574 }
Mike Stump11289f42009-09-09 15:08:12 +00002575 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002576 MsgExprs.push_back(userExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00002577 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2578 // out the argument in the original expression (since we aren't deleting
2579 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2580 //Exp->setArg(i, 0);
Steve Naroff574440f2007-10-24 22:48:43 +00002581 }
Steve Narofff36987c2007-11-04 22:37:50 +00002582 // Generate the funky cast.
2583 CastExpr *cast;
2584 llvm::SmallVector<QualType, 8> ArgTypes;
2585 QualType returnType;
Mike Stump11289f42009-09-09 15:08:12 +00002586
Steve Narofff36987c2007-11-04 22:37:50 +00002587 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff44864e42007-11-15 10:43:57 +00002588 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2589 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2590 else
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002591 ArgTypes.push_back(Context->getObjCIdType());
2592 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattnera4997152009-02-20 18:43:26 +00002593 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Narofff36987c2007-11-04 22:37:50 +00002594 // Push any user argument types.
Chris Lattnera4997152009-02-20 18:43:26 +00002595 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2596 E = OMD->param_end(); PI != E; ++PI) {
2597 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump11289f42009-09-09 15:08:12 +00002598 ? Context->getObjCIdType()
Chris Lattnera4997152009-02-20 18:43:26 +00002599 : (*PI)->getType();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002600 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00002601 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002602 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002603 t = Context->getPointerType(BPT->getPointeeType());
2604 }
Steve Naroff98eb8d12007-11-05 14:36:37 +00002605 ArgTypes.push_back(t);
2606 }
Chris Lattnera4997152009-02-20 18:43:26 +00002607 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2608 ? Context->getObjCIdType() : OMD->getResultType();
Steve Narofff36987c2007-11-04 22:37:50 +00002609 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002610 returnType = Context->getObjCIdType();
Steve Narofff36987c2007-11-04 22:37:50 +00002611 }
2612 // Get the type, we will need to reference it in a couple spots.
Steve Naroff7fa2f042007-11-15 10:28:18 +00002613 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002614
Steve Narofff36987c2007-11-04 22:37:50 +00002615 // Create a reference to the objc_msgSend() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002616 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002617 SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002618
Mike Stump11289f42009-09-09 15:08:12 +00002619 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Narofff36987c2007-11-04 22:37:50 +00002620 // If we don't do this cast, we get the following bizarre warning/note:
2621 // xx.m:13: warning: function called through a non-compatible type
2622 // xx.m:13: note: if this code is reached, the program will abort
Mike Stump11289f42009-09-09 15:08:12 +00002623 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy),
2624 CastExpr::CK_Unknown, DRE,
Douglas Gregore200adc2008-10-27 19:41:14 +00002625 Context->getPointerType(Context->VoidTy),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002626 SourceLocation(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002627
Steve Narofff36987c2007-11-04 22:37:50 +00002628 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002629 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002630 &ArgTypes[0], ArgTypes.size(),
Steve Naroff327f0f42008-03-18 02:02:04 +00002631 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002632 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Narofff36987c2007-11-04 22:37:50 +00002633 castType = Context->getPointerType(castType);
Mike Stump11289f42009-09-09 15:08:12 +00002634 cast = new (Context) CStyleCastExpr(castType, CastExpr::CK_Unknown, cast,
2635 castType, SourceLocation(),
Anders Carlssona2615922009-07-31 00:48:10 +00002636 SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002637
2638 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00002639 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00002640
John McCall9dd450b2009-09-21 23:43:11 +00002641 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002642 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002643 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002644 FT->getResultType(), SourceLocation());
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002645 Stmt *ReplacingStmt = CE;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002646 if (MsgSendStretFlavor) {
2647 // We have the method which returns a struct/union. Must also generate
2648 // call to objc_msgSend_stret and hang both varieties on a conditional
2649 // expression which dictate which one to envoke depending on size of
2650 // method's return type.
Mike Stump11289f42009-09-09 15:08:12 +00002651
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002652 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002653 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002654 SourceLocation());
2655 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Mike Stump11289f42009-09-09 15:08:12 +00002656 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy),
2657 CastExpr::CK_Unknown, STDRE,
Douglas Gregore200adc2008-10-27 19:41:14 +00002658 Context->getPointerType(Context->VoidTy),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002659 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002660 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002661 castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002662 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002663 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002664 castType = Context->getPointerType(castType);
Anders Carlssona2615922009-07-31 00:48:10 +00002665 cast = new (Context) CStyleCastExpr(castType, CastExpr::CK_Unknown,
2666 cast, castType, SourceLocation(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002667
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002668 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00002669 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00002670
John McCall9dd450b2009-09-21 23:43:11 +00002671 FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002672 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002673 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002674 FT->getResultType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002675
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002676 // Build sizeof(returnType)
Mike Stump11289f42009-09-09 15:08:12 +00002677 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCall4c98fd82009-11-04 07:28:41 +00002678 Context->getTrivialDeclaratorInfo(returnType),
Sebastian Redl6f282892008-11-11 17:56:53 +00002679 Context->getSizeType(),
2680 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002681 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2682 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2683 // For X86 it is more complicated and some kind of target specific routine
2684 // is needed to decide what to do.
Mike Stump11289f42009-09-09 15:08:12 +00002685 unsigned IntSize =
Chris Lattner37e05872008-03-05 18:54:05 +00002686 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Mike Stump11289f42009-09-09 15:08:12 +00002687 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002688 Context->IntTy,
2689 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002690 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
2691 BinaryOperator::LE,
2692 Context->IntTy,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002693 SourceLocation());
2694 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump11289f42009-09-09 15:08:12 +00002695 ConditionalOperator *CondExpr =
Douglas Gregor7e112b02009-08-26 14:37:04 +00002696 new (Context) ConditionalOperator(lessThanExpr,
2697 SourceLocation(), CE,
2698 SourceLocation(), STCE, returnType);
Ted Kremenek5a201952009-02-07 01:47:29 +00002699 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002700 }
Mike Stump11289f42009-09-09 15:08:12 +00002701 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002702 return ReplacingStmt;
2703}
2704
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002705Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002706 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Mike Stump11289f42009-09-09 15:08:12 +00002707
Steve Naroff574440f2007-10-24 22:48:43 +00002708 // Now do the actual rewrite.
Chris Lattner2e0d2602008-01-31 19:37:57 +00002709 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00002710
2711 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002712 return ReplacingStmt;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002713}
2714
Steve Naroffd9803712009-04-29 16:37:50 +00002715// typedef struct objc_object Protocol;
2716QualType RewriteObjC::getProtocolType() {
2717 if (!ProtocolTypeDecl) {
John McCall703a3f82009-10-24 08:00:42 +00002718 DeclaratorInfo *DInfo
2719 = Context->getTrivialDeclaratorInfo(Context->getObjCIdType());
Steve Naroffd9803712009-04-29 16:37:50 +00002720 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002721 SourceLocation(),
Steve Naroffd9803712009-04-29 16:37:50 +00002722 &Context->Idents.get("Protocol"),
John McCall703a3f82009-10-24 08:00:42 +00002723 DInfo);
Steve Naroffd9803712009-04-29 16:37:50 +00002724 }
2725 return Context->getTypeDeclType(ProtocolTypeDecl);
2726}
2727
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00002728/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroffd9803712009-04-29 16:37:50 +00002729/// a synthesized/forward data reference (to the protocol's metadata).
2730/// The forward references (and metadata) are generated in
2731/// RewriteObjC::HandleTranslationUnit().
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002732Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroffd9803712009-04-29 16:37:50 +00002733 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
2734 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump11289f42009-09-09 15:08:12 +00002735 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregored6c7442009-11-23 11:41:28 +00002736 ID, getProtocolType(), 0, VarDecl::Extern);
Steve Naroffd9803712009-04-29 16:37:50 +00002737 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
2738 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
2739 Context->getPointerType(DRE->getType()),
2740 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002741 CastExpr *castExpr = new (Context) CStyleCastExpr(DerefExpr->getType(),
2742 CastExpr::CK_Unknown,
2743 DerefExpr, DerefExpr->getType(),
Steve Naroffd9803712009-04-29 16:37:50 +00002744 SourceLocation(), SourceLocation());
2745 ReplaceStmt(Exp, castExpr);
2746 ProtocolExprDecls.insert(Exp->getProtocol());
Mike Stump11289f42009-09-09 15:08:12 +00002747 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00002748 return castExpr;
Mike Stump11289f42009-09-09 15:08:12 +00002749
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00002750}
2751
Mike Stump11289f42009-09-09 15:08:12 +00002752bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002753 const char *endBuf) {
2754 while (startBuf < endBuf) {
2755 if (*startBuf == '#') {
2756 // Skip whitespace.
2757 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2758 ;
2759 if (!strncmp(startBuf, "if", strlen("if")) ||
2760 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2761 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2762 !strncmp(startBuf, "define", strlen("define")) ||
2763 !strncmp(startBuf, "undef", strlen("undef")) ||
2764 !strncmp(startBuf, "else", strlen("else")) ||
2765 !strncmp(startBuf, "elif", strlen("elif")) ||
2766 !strncmp(startBuf, "endif", strlen("endif")) ||
2767 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2768 !strncmp(startBuf, "include", strlen("include")) ||
2769 !strncmp(startBuf, "import", strlen("import")) ||
2770 !strncmp(startBuf, "include_next", strlen("include_next")))
2771 return true;
2772 }
2773 startBuf++;
2774 }
2775 return false;
2776}
2777
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002778/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002779/// an objective-c class with ivars.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002780void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002781 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002782 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Mike Stump11289f42009-09-09 15:08:12 +00002783 assert(CDecl->getNameAsCString() &&
Douglas Gregor77324f32008-11-17 14:58:09 +00002784 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00002785 // Do not synthesize more than once.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002786 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00002787 return;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002788 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattner8d1c04f2008-03-16 21:08:55 +00002789 int NumIvars = CDecl->ivar_size();
Steve Naroffdde78982007-11-14 19:25:57 +00002790 SourceLocation LocStart = CDecl->getLocStart();
2791 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00002792
Steve Naroffdde78982007-11-14 19:25:57 +00002793 const char *startBuf = SM->getCharacterData(LocStart);
2794 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00002795
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002796 // If no ivars and no root or if its root, directly or indirectly,
2797 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattner8d1c04f2008-03-16 21:08:55 +00002798 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2799 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner184e65d2009-04-14 23:22:57 +00002800 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Chris Lattner9cc55f52008-01-31 19:51:04 +00002801 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002802 return;
2803 }
Mike Stump11289f42009-09-09 15:08:12 +00002804
2805 // FIXME: This has potential of causing problem. If
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002806 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002807 Result += "\nstruct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002808 Result += CDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00002809 if (LangOpts.Microsoft)
2810 Result += "_IMPL";
Steve Naroffdc5b6b22008-03-12 00:25:36 +00002811
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002812 if (NumIvars > 0) {
Steve Naroffdde78982007-11-14 19:25:57 +00002813 const char *cursor = strchr(startBuf, '{');
Mike Stump11289f42009-09-09 15:08:12 +00002814 assert((cursor && endBuf)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002815 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002816 // If the buffer contains preprocessor directives, we do more fine-grained
2817 // rewrites. This is intended to fix code that looks like (which occurs in
2818 // NSURL.h, for example):
2819 //
2820 // #ifdef XYZ
2821 // @interface Foo : NSObject
2822 // #else
2823 // @interface FooBar : NSObject
2824 // #endif
2825 // {
2826 // int i;
2827 // }
2828 // @end
2829 //
2830 // This clause is segregated to avoid breaking the common case.
2831 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump11289f42009-09-09 15:08:12 +00002832 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002833 CDecl->getClassLoc();
2834 const char *endHeader = SM->getCharacterData(L);
Chris Lattner184e65d2009-04-14 23:22:57 +00002835 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002836
Chris Lattnerf5b77512009-02-20 18:18:36 +00002837 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002838 // advance to the end of the referenced protocols.
2839 while (endHeader < cursor && *endHeader != '>') endHeader++;
2840 endHeader++;
2841 }
2842 // rewrite the original header
2843 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2844 } else {
2845 // rewrite the original header *without* disturbing the '{'
Steve Naroffb0e33902009-12-04 21:36:32 +00002846 ReplaceText(LocStart, cursor-startBuf, Result.c_str(), Result.size());
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002847 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002848 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroffdde78982007-11-14 19:25:57 +00002849 Result = "\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002850 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00002851 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002852 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00002853 Result += "_IVARS;\n";
Mike Stump11289f42009-09-09 15:08:12 +00002854
Steve Naroffdde78982007-11-14 19:25:57 +00002855 // insert the super class structure definition.
Chris Lattner1780a852008-01-31 19:42:41 +00002856 SourceLocation OnePastCurly =
2857 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2858 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Naroffdde78982007-11-14 19:25:57 +00002859 }
2860 cursor++; // past '{'
Mike Stump11289f42009-09-09 15:08:12 +00002861
Steve Naroffdde78982007-11-14 19:25:57 +00002862 // Now comment out any visibility specifiers.
2863 while (cursor < endBuf) {
2864 if (*cursor == '@') {
2865 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner174a8252007-11-14 22:57:51 +00002866 // Skip whitespace.
2867 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2868 /*scan*/;
2869
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002870 // FIXME: presence of @public, etc. inside comment results in
2871 // this transformation as well, which is still correct c-code.
Steve Naroffdde78982007-11-14 19:25:57 +00002872 if (!strncmp(cursor, "public", strlen("public")) ||
2873 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffaf91b9a2008-04-04 22:34:24 +00002874 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002875 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattner1780a852008-01-31 19:42:41 +00002876 InsertText(atLoc, "// ", 3);
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002877 }
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002878 // FIXME: If there are cases where '<' is used in ivar declaration part
2879 // of user code, then scan the ivar list and use needToScanForQualifiers
2880 // for type checking.
2881 else if (*cursor == '<') {
2882 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner1780a852008-01-31 19:42:41 +00002883 InsertText(atLoc, "/* ", 3);
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002884 cursor = strchr(cursor, '>');
2885 cursor++;
2886 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner1780a852008-01-31 19:42:41 +00002887 InsertText(atLoc, " */", 3);
Steve Naroff295570a2008-10-30 12:09:33 +00002888 } else if (*cursor == '^') { // rewrite block specifier.
2889 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2890 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002891 }
Steve Naroffdde78982007-11-14 19:25:57 +00002892 cursor++;
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002893 }
Steve Naroffdde78982007-11-14 19:25:57 +00002894 // Don't forget to add a ';'!!
Chris Lattner1780a852008-01-31 19:42:41 +00002895 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Naroffdde78982007-11-14 19:25:57 +00002896 } else { // we don't have any instance variables - insert super struct.
Chris Lattner184e65d2009-04-14 23:22:57 +00002897 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroffdde78982007-11-14 19:25:57 +00002898 Result += " {\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002899 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00002900 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002901 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00002902 Result += "_IVARS;\n};\n";
Chris Lattner9cc55f52008-01-31 19:51:04 +00002903 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002904 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002905 // Mark this struct as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002906 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff13e74872008-05-06 18:26:51 +00002907 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002908}
2909
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002910// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002911/// class methods.
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002912template<typename MethodIterator>
2913void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
2914 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +00002915 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002916 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +00002917 const char *ClassName,
2918 std::string &Result) {
Chris Lattner31bc07e2007-12-12 07:46:12 +00002919 if (MethodBegin == MethodEnd) return;
Mike Stump11289f42009-09-09 15:08:12 +00002920
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00002921 static bool objc_impl_method = false;
Chris Lattner31bc07e2007-12-12 07:46:12 +00002922 if (!objc_impl_method) {
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002923 /* struct _objc_method {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00002924 SEL _cmd;
2925 char *method_types;
2926 void *_imp;
2927 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002928 */
Chris Lattner211f8b82007-10-25 17:07:24 +00002929 Result += "\nstruct _objc_method {\n";
2930 Result += "\tSEL _cmd;\n";
2931 Result += "\tchar *method_types;\n";
2932 Result += "\tvoid *_imp;\n";
2933 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002934
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002935 objc_impl_method = true;
Fariborz Jahanian74a1cfa2007-10-19 00:36:46 +00002936 }
Mike Stump11289f42009-09-09 15:08:12 +00002937
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002938 // Build _objc_method_list for class's methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00002939
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002940 /* struct {
2941 struct _objc_method_list *next_method;
2942 int method_count;
2943 struct _objc_method method_list[];
2944 }
2945 */
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002946 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002947 Result += "\nstatic struct {\n";
2948 Result += "\tstruct _objc_method_list *next_method;\n";
2949 Result += "\tint method_count;\n";
2950 Result += "\tstruct _objc_method method_list[";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002951 Result += utostr(NumMethods);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002952 Result += "];\n} _OBJC_";
Chris Lattner31bc07e2007-12-12 07:46:12 +00002953 Result += prefix;
2954 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2955 Result += "_METHODS_";
2956 Result += ClassName;
Steve Naroffb327e492008-03-12 17:18:30 +00002957 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattner31bc07e2007-12-12 07:46:12 +00002958 Result += IsInstanceMethod ? "inst" : "cls";
2959 Result += "_meth\")))= ";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002960 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00002961
Chris Lattner31bc07e2007-12-12 07:46:12 +00002962 Result += "\t,{{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00002963 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattner31bc07e2007-12-12 07:46:12 +00002964 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002965 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattner31bc07e2007-12-12 07:46:12 +00002966 Result += "\", \"";
2967 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002968 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00002969 Result += MethodInternalNames[*MethodBegin];
2970 Result += "}\n";
2971 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2972 Result += "\t ,{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00002973 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00002974 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002975 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00002976 Result += "\", \"";
2977 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002978 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00002979 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanian56338352007-11-13 21:02:00 +00002980 Result += "}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00002981 }
Chris Lattner31bc07e2007-12-12 07:46:12 +00002982 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002983}
2984
Steve Naroffd9803712009-04-29 16:37:50 +00002985/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner390d39a2008-07-21 21:32:27 +00002986void RewriteObjC::
Steve Naroffd9803712009-04-29 16:37:50 +00002987RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
2988 const char *ClassName, std::string &Result) {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00002989 static bool objc_protocol_methods = false;
Steve Naroffd9803712009-04-29 16:37:50 +00002990
2991 // Output struct protocol_methods holder of method selector and type.
2992 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2993 /* struct protocol_methods {
2994 SEL _cmd;
2995 char *method_types;
2996 }
2997 */
2998 Result += "\nstruct _protocol_methods {\n";
2999 Result += "\tstruct objc_selector *_cmd;\n";
3000 Result += "\tchar *method_types;\n";
3001 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003002
Steve Naroffd9803712009-04-29 16:37:50 +00003003 objc_protocol_methods = true;
3004 }
3005 // Do not synthesize the protocol more than once.
3006 if (ObjCSynthesizedProtocols.count(PDecl))
3007 return;
Mike Stump11289f42009-09-09 15:08:12 +00003008
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003009 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3010 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3011 PDecl->instmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003012 /* struct _objc_protocol_method_list {
3013 int protocol_method_count;
3014 struct protocol_methods protocols[];
3015 }
Steve Naroff251084d2008-03-12 01:06:30 +00003016 */
Steve Naroffd9803712009-04-29 16:37:50 +00003017 Result += "\nstatic struct {\n";
3018 Result += "\tint protocol_method_count;\n";
3019 Result += "\tstruct _protocol_methods protocol_methods[";
3020 Result += utostr(NumMethods);
3021 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3022 Result += PDecl->getNameAsString();
3023 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3024 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003025
Steve Naroffd9803712009-04-29 16:37:50 +00003026 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003027 for (ObjCProtocolDecl::instmeth_iterator
3028 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003029 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003030 if (I == PDecl->instmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003031 Result += "\t ,{{(struct objc_selector *)\"";
3032 else
3033 Result += "\t ,{(struct objc_selector *)\"";
3034 Result += (*I)->getSelector().getAsString().c_str();
3035 std::string MethodTypeString;
3036 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3037 Result += "\", \"";
3038 Result += MethodTypeString;
3039 Result += "\"}\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003040 }
Steve Naroffd9803712009-04-29 16:37:50 +00003041 Result += "\t }\n};\n";
3042 }
Mike Stump11289f42009-09-09 15:08:12 +00003043
Steve Naroffd9803712009-04-29 16:37:50 +00003044 // Output class methods declared in this protocol.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003045 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3046 PDecl->classmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003047 if (NumMethods > 0) {
3048 /* struct _objc_protocol_method_list {
3049 int protocol_method_count;
3050 struct protocol_methods protocols[];
3051 }
3052 */
3053 Result += "\nstatic struct {\n";
3054 Result += "\tint protocol_method_count;\n";
3055 Result += "\tstruct _protocol_methods protocol_methods[";
3056 Result += utostr(NumMethods);
3057 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3058 Result += PDecl->getNameAsString();
3059 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3060 "{\n\t";
3061 Result += utostr(NumMethods);
3062 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003063
Steve Naroffd9803712009-04-29 16:37:50 +00003064 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003065 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003066 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003067 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003068 if (I == PDecl->classmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003069 Result += "\t ,{{(struct objc_selector *)\"";
3070 else
3071 Result += "\t ,{(struct objc_selector *)\"";
3072 Result += (*I)->getSelector().getAsString().c_str();
3073 std::string MethodTypeString;
3074 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3075 Result += "\", \"";
3076 Result += MethodTypeString;
3077 Result += "\"}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003078 }
Steve Naroffd9803712009-04-29 16:37:50 +00003079 Result += "\t }\n};\n";
3080 }
3081
3082 // Output:
3083 /* struct _objc_protocol {
3084 // Objective-C 1.0 extensions
3085 struct _objc_protocol_extension *isa;
3086 char *protocol_name;
3087 struct _objc_protocol **protocol_list;
3088 struct _objc_protocol_method_list *instance_methods;
3089 struct _objc_protocol_method_list *class_methods;
Mike Stump11289f42009-09-09 15:08:12 +00003090 };
Steve Naroffd9803712009-04-29 16:37:50 +00003091 */
3092 static bool objc_protocol = false;
3093 if (!objc_protocol) {
3094 Result += "\nstruct _objc_protocol {\n";
3095 Result += "\tstruct _objc_protocol_extension *isa;\n";
3096 Result += "\tchar *protocol_name;\n";
3097 Result += "\tstruct _objc_protocol **protocol_list;\n";
3098 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3099 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003100 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003101
Steve Naroffd9803712009-04-29 16:37:50 +00003102 objc_protocol = true;
Chris Lattner388f6e92008-07-21 21:33:21 +00003103 }
Mike Stump11289f42009-09-09 15:08:12 +00003104
Steve Naroffd9803712009-04-29 16:37:50 +00003105 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3106 Result += PDecl->getNameAsString();
3107 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3108 "{\n\t0, \"";
3109 Result += PDecl->getNameAsString();
3110 Result += "\", 0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003111 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003112 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3113 Result += PDecl->getNameAsString();
3114 Result += ", ";
3115 }
3116 else
3117 Result += "0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003118 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003119 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3120 Result += PDecl->getNameAsString();
3121 Result += "\n";
3122 }
3123 else
3124 Result += "0\n";
3125 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003126
Steve Naroffd9803712009-04-29 16:37:50 +00003127 // Mark this protocol as having been generated.
3128 if (!ObjCSynthesizedProtocols.insert(PDecl))
3129 assert(false && "protocol already synthesized");
3130
3131}
3132
3133void RewriteObjC::
3134RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3135 const char *prefix, const char *ClassName,
3136 std::string &Result) {
3137 if (Protocols.empty()) return;
Mike Stump11289f42009-09-09 15:08:12 +00003138
Steve Naroffd9803712009-04-29 16:37:50 +00003139 for (unsigned i = 0; i != Protocols.size(); i++)
3140 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3141
Chris Lattner388f6e92008-07-21 21:33:21 +00003142 // Output the top lovel protocol meta-data for the class.
3143 /* struct _objc_protocol_list {
3144 struct _objc_protocol_list *next;
3145 int protocol_count;
3146 struct _objc_protocol *class_protocols[];
3147 }
3148 */
3149 Result += "\nstatic struct {\n";
3150 Result += "\tstruct _objc_protocol_list *next;\n";
3151 Result += "\tint protocol_count;\n";
3152 Result += "\tstruct _objc_protocol *class_protocols[";
3153 Result += utostr(Protocols.size());
3154 Result += "];\n} _OBJC_";
3155 Result += prefix;
3156 Result += "_PROTOCOLS_";
3157 Result += ClassName;
3158 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3159 "{\n\t0, ";
3160 Result += utostr(Protocols.size());
3161 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003162
Chris Lattner388f6e92008-07-21 21:33:21 +00003163 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003164 Result += Protocols[0]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003165 Result += " \n";
Mike Stump11289f42009-09-09 15:08:12 +00003166
Chris Lattner388f6e92008-07-21 21:33:21 +00003167 for (unsigned i = 1; i != Protocols.size(); i++) {
3168 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003169 Result += Protocols[i]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003170 Result += "\n";
3171 }
3172 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003173}
3174
Steve Naroffd9803712009-04-29 16:37:50 +00003175
Mike Stump11289f42009-09-09 15:08:12 +00003176/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003177/// implementation.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003178void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003179 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003180 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003181 // Find category declaration for this implementation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003182 ObjCCategoryDecl *CDecl;
Mike Stump11289f42009-09-09 15:08:12 +00003183 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003184 CDecl = CDecl->getNextClassCategory())
3185 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3186 break;
Mike Stump11289f42009-09-09 15:08:12 +00003187
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003188 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003189 FullCategoryName += '_';
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003190 FullCategoryName += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003191
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003192 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003193 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003194 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003195
3196 // If any of our property implementations have associated getters or
3197 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003198 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3199 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003200 Prop != PropEnd; ++Prop) {
3201 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3202 continue;
3203 if (!(*Prop)->getPropertyIvarDecl())
3204 continue;
3205 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3206 if (!PD)
3207 continue;
3208 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3209 InstanceMethods.push_back(Getter);
3210 if (PD->isReadOnly())
3211 continue;
3212 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3213 InstanceMethods.push_back(Setter);
3214 }
3215 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003216 true, "CATEGORY_", FullCategoryName.c_str(),
3217 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003218
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003219 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003220 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003221 false, "CATEGORY_", FullCategoryName.c_str(),
3222 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003223
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003224 // Protocols referenced in class declaration?
Fariborz Jahanian989e0392007-11-13 22:09:49 +00003225 // Null CDecl is case of a category implementation with no category interface
3226 if (CDecl)
Steve Naroffd9803712009-04-29 16:37:50 +00003227 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3228 FullCategoryName.c_str(), Result);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003229 /* struct _objc_category {
3230 char *category_name;
3231 char *class_name;
3232 struct _objc_method_list *instance_methods;
3233 struct _objc_method_list *class_methods;
3234 struct _objc_protocol_list *protocols;
3235 // Objective-C 1.0 extensions
3236 uint32_t size; // sizeof (struct _objc_category)
Mike Stump11289f42009-09-09 15:08:12 +00003237 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003238 // @property decl.
Mike Stump11289f42009-09-09 15:08:12 +00003239 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003240 */
Mike Stump11289f42009-09-09 15:08:12 +00003241
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003242 static bool objc_category = false;
3243 if (!objc_category) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003244 Result += "\nstruct _objc_category {\n";
3245 Result += "\tchar *category_name;\n";
3246 Result += "\tchar *class_name;\n";
3247 Result += "\tstruct _objc_method_list *instance_methods;\n";
3248 Result += "\tstruct _objc_method_list *class_methods;\n";
3249 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003250 Result += "\tunsigned int size;\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003251 Result += "\tstruct _objc_property_list *instance_properties;\n";
3252 Result += "};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003253 objc_category = true;
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003254 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003255 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3256 Result += FullCategoryName;
Steve Naroffb327e492008-03-12 17:18:30 +00003257 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003258 Result += IDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003259 Result += "\"\n\t, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003260 Result += ClassDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003261 Result += "\"\n";
Mike Stump11289f42009-09-09 15:08:12 +00003262
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003263 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003264 Result += "\t, (struct _objc_method_list *)"
3265 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3266 Result += FullCategoryName;
3267 Result += "\n";
3268 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003269 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003270 Result += "\t, 0\n";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003271 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003272 Result += "\t, (struct _objc_method_list *)"
3273 "&_OBJC_CATEGORY_CLASS_METHODS_";
3274 Result += FullCategoryName;
3275 Result += "\n";
3276 }
3277 else
3278 Result += "\t, 0\n";
Mike Stump11289f42009-09-09 15:08:12 +00003279
Chris Lattnerf5b77512009-02-20 18:18:36 +00003280 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump11289f42009-09-09 15:08:12 +00003281 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003282 Result += FullCategoryName;
3283 Result += "\n";
3284 }
3285 else
3286 Result += "\t, 0\n";
3287 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003288}
3289
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003290/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3291/// ivar offset.
Mike Stump11289f42009-09-09 15:08:12 +00003292void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
3293 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003294 std::string &Result) {
Steve Naroffde7d0f62008-07-16 18:22:22 +00003295 if (ivar->isBitField()) {
3296 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3297 // place all bitfields at offset 0.
3298 Result += "0";
3299 } else {
3300 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003301 Result += IDecl->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003302 if (LangOpts.Microsoft)
3303 Result += "_IMPL";
3304 Result += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003305 Result += ivar->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003306 Result += ")";
3307 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003308}
3309
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003310//===----------------------------------------------------------------------===//
3311// Meta Data Emission
3312//===----------------------------------------------------------------------===//
3313
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003314void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003315 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003316 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00003317
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003318 // Explictly declared @interface's are already synthesized.
Steve Naroffaac654a2009-04-20 20:09:33 +00003319 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump11289f42009-09-09 15:08:12 +00003320 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003321 // produce correct synthesis as yet.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003322 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003323 }
Mike Stump11289f42009-09-09 15:08:12 +00003324
Chris Lattner30d23e82007-12-12 07:56:42 +00003325 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003326 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump11289f42009-09-09 15:08:12 +00003327 ? IDecl->ivar_size()
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003328 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003329 if (NumIvars > 0) {
3330 static bool objc_ivar = false;
3331 if (!objc_ivar) {
3332 /* struct _objc_ivar {
3333 char *ivar_name;
3334 char *ivar_type;
3335 int ivar_offset;
Mike Stump11289f42009-09-09 15:08:12 +00003336 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003337 */
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003338 Result += "\nstruct _objc_ivar {\n";
3339 Result += "\tchar *ivar_name;\n";
3340 Result += "\tchar *ivar_type;\n";
3341 Result += "\tint ivar_offset;\n";
3342 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003343
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003344 objc_ivar = true;
3345 }
3346
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003347 /* struct {
3348 int ivar_count;
3349 struct _objc_ivar ivar_list[nIvars];
Mike Stump11289f42009-09-09 15:08:12 +00003350 };
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003351 */
Mike Stump11289f42009-09-09 15:08:12 +00003352 Result += "\nstatic struct {\n";
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003353 Result += "\tint ivar_count;\n";
3354 Result += "\tstruct _objc_ivar ivar_list[";
3355 Result += utostr(NumIvars);
3356 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003357 Result += IDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003358 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003359 "{\n\t";
3360 Result += utostr(NumIvars);
3361 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003362
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003363 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor5f662052009-04-23 03:23:08 +00003364 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003365 if (!IDecl->ivar_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00003366 for (ObjCImplementationDecl::ivar_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003367 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor5f662052009-04-23 03:23:08 +00003368 IV != IVEnd; ++IV)
3369 IVars.push_back(*IV);
3370 IVI = IVars.begin();
3371 IVE = IVars.end();
Chris Lattner30d23e82007-12-12 07:56:42 +00003372 } else {
3373 IVI = CDecl->ivar_begin();
3374 IVE = CDecl->ivar_end();
3375 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003376 Result += "\t,{{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003377 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003378 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003379 std::string TmpString, StrEncoding;
3380 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3381 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003382 Result += StrEncoding;
3383 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003384 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003385 Result += "}\n";
Chris Lattner30d23e82007-12-12 07:56:42 +00003386 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003387 Result += "\t ,{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003388 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003389 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003390 std::string TmpString, StrEncoding;
3391 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3392 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003393 Result += StrEncoding;
3394 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003395 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003396 Result += "}\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003397 }
Mike Stump11289f42009-09-09 15:08:12 +00003398
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003399 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003400 }
Mike Stump11289f42009-09-09 15:08:12 +00003401
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003402 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003403 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003404 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003405
3406 // If any of our property implementations have associated getters or
3407 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003408 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3409 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003410 Prop != PropEnd; ++Prop) {
3411 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3412 continue;
3413 if (!(*Prop)->getPropertyIvarDecl())
3414 continue;
3415 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3416 if (!PD)
3417 continue;
3418 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3419 InstanceMethods.push_back(Getter);
3420 if (PD->isReadOnly())
3421 continue;
3422 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3423 InstanceMethods.push_back(Setter);
3424 }
3425 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003426 true, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003427
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003428 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003429 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003430 false, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003431
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003432 // Protocols referenced in class declaration?
Steve Naroffd9803712009-04-29 16:37:50 +00003433 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3434 "CLASS", CDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003435
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003436 // Declaration of class/meta-class metadata
3437 /* struct _objc_class {
3438 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003439 const char *super_class_name;
3440 char *name;
3441 long version;
3442 long info;
3443 long instance_size;
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003444 struct _objc_ivar_list *ivars;
3445 struct _objc_method_list *methods;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003446 struct objc_cache *cache;
3447 struct objc_protocol_list *protocols;
3448 const char *ivar_layout;
3449 struct _objc_class_ext *ext;
Mike Stump11289f42009-09-09 15:08:12 +00003450 };
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003451 */
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003452 static bool objc_class = false;
3453 if (!objc_class) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003454 Result += "\nstruct _objc_class {\n";
3455 Result += "\tstruct _objc_class *isa;\n";
3456 Result += "\tconst char *super_class_name;\n";
3457 Result += "\tchar *name;\n";
3458 Result += "\tlong version;\n";
3459 Result += "\tlong info;\n";
3460 Result += "\tlong instance_size;\n";
3461 Result += "\tstruct _objc_ivar_list *ivars;\n";
3462 Result += "\tstruct _objc_method_list *methods;\n";
3463 Result += "\tstruct objc_cache *cache;\n";
3464 Result += "\tstruct _objc_protocol_list *protocols;\n";
3465 Result += "\tconst char *ivar_layout;\n";
3466 Result += "\tstruct _objc_class_ext *ext;\n";
3467 Result += "};\n";
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003468 objc_class = true;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003469 }
Mike Stump11289f42009-09-09 15:08:12 +00003470
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003471 // Meta-class metadata generation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003472 ObjCInterfaceDecl *RootClass = 0;
3473 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003474 while (SuperClass) {
3475 RootClass = SuperClass;
3476 SuperClass = SuperClass->getSuperClass();
3477 }
3478 SuperClass = CDecl->getSuperClass();
Mike Stump11289f42009-09-09 15:08:12 +00003479
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003480 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003481 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003482 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003483 "{\n\t(struct _objc_class *)\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003484 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003485 Result += "\"";
3486
3487 if (SuperClass) {
3488 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003489 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003490 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003491 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003492 Result += "\"";
3493 }
3494 else {
3495 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003496 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003497 Result += "\"";
3498 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003499 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003500 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003501 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003502 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff0b844f02008-03-11 18:14:26 +00003503 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003504 Result += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003505 Result += "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003506 }
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003507 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003508 Result += ", 0\n";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003509 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003510 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003511 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003512 Result += ",0,0\n";
3513 }
Fariborz Jahanian486f7182007-10-24 20:54:23 +00003514 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003515 Result += "\t,0,0,0,0\n";
3516 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003517
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003518 // class metadata generation.
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003519 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003520 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003521 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003522 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003523 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003524 if (SuperClass) {
3525 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003526 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003527 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003528 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003529 Result += "\"";
3530 }
3531 else {
3532 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003533 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003534 Result += "\"";
3535 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003536 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003537 Result += ", 0,1";
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003538 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003539 Result += ",0";
3540 else {
3541 // class has size. Must synthesize its size.
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00003542 Result += ",sizeof(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003543 Result += CDecl->getNameAsString();
Steve Naroff14a07462008-03-10 23:33:22 +00003544 if (LangOpts.Microsoft)
3545 Result += "_IMPL";
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003546 Result += ")";
3547 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003548 if (NumIvars > 0) {
Steve Naroff17978c42008-03-11 17:37:02 +00003549 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003550 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003551 Result += "\n\t";
3552 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003553 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003554 Result += ",0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003555 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003556 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003557 Result += CDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003558 Result += ", 0\n\t";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003559 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003560 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003561 Result += ",0,0";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003562 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003563 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003564 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003565 Result += ", 0,0\n";
3566 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003567 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003568 Result += ",0,0,0\n";
3569 Result += "};\n";
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003570}
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003571
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003572/// RewriteImplementations - This routine rewrites all method implementations
3573/// and emits meta-data.
3574
Steve Narofff8cfd162008-11-13 20:07:04 +00003575void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003576 int ClsDefCount = ClassImplementation.size();
3577 int CatDefCount = CategoryImplementation.size();
Mike Stump11289f42009-09-09 15:08:12 +00003578
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003579 // Rewrite implemented methods
3580 for (int i = 0; i < ClsDefCount; i++)
3581 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003582
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00003583 for (int i = 0; i < CatDefCount; i++)
3584 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofff8cfd162008-11-13 20:07:04 +00003585}
Mike Stump11289f42009-09-09 15:08:12 +00003586
Steve Narofff8cfd162008-11-13 20:07:04 +00003587void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3588 int ClsDefCount = ClassImplementation.size();
3589 int CatDefCount = CategoryImplementation.size();
3590
Steve Naroff30ac2222008-05-07 21:23:49 +00003591 // This is needed for determining instance variable offsets.
Mike Stump11289f42009-09-09 15:08:12 +00003592 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003593 // For each implemented class, write out all its meta data.
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003594 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003595 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump11289f42009-09-09 15:08:12 +00003596
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003597 // For each implemented category, write out all its meta data.
3598 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003599 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroffd9803712009-04-29 16:37:50 +00003600
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003601 // Write objc_symtab metadata
3602 /*
3603 struct _objc_symtab
3604 {
3605 long sel_ref_cnt;
3606 SEL *refs;
3607 short cls_def_cnt;
3608 short cat_def_cnt;
3609 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump11289f42009-09-09 15:08:12 +00003610 };
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003611 */
Mike Stump11289f42009-09-09 15:08:12 +00003612
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003613 Result += "\nstruct _objc_symtab {\n";
3614 Result += "\tlong sel_ref_cnt;\n";
3615 Result += "\tSEL *refs;\n";
3616 Result += "\tshort cls_def_cnt;\n";
3617 Result += "\tshort cat_def_cnt;\n";
3618 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3619 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003620
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003621 Result += "static struct _objc_symtab "
Steve Naroffb327e492008-03-12 17:18:30 +00003622 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003623 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003624 + ", " + utostr(CatDefCount) + "\n";
3625 for (int i = 0; i < ClsDefCount; i++) {
3626 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003627 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003628 Result += "\n";
3629 }
Mike Stump11289f42009-09-09 15:08:12 +00003630
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003631 for (int i = 0; i < CatDefCount; i++) {
3632 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003633 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003634 Result += "_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003635 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003636 Result += "\n";
3637 }
Mike Stump11289f42009-09-09 15:08:12 +00003638
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003639 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003640
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003641 // Write objc_module metadata
Mike Stump11289f42009-09-09 15:08:12 +00003642
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003643 /*
3644 struct _objc_module {
3645 long version;
3646 long size;
3647 const char *name;
3648 struct _objc_symtab *symtab;
3649 }
3650 */
Mike Stump11289f42009-09-09 15:08:12 +00003651
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003652 Result += "\nstruct _objc_module {\n";
3653 Result += "\tlong version;\n";
3654 Result += "\tlong size;\n";
3655 Result += "\tconst char *name;\n";
3656 Result += "\tstruct _objc_symtab *symtab;\n";
3657 Result += "};\n\n";
3658 Result += "static struct _objc_module "
Steve Naroffb327e492008-03-12 17:18:30 +00003659 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003660 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003661 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003662 Result += "};\n\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003663
3664 if (LangOpts.Microsoft) {
Steve Naroffd9803712009-04-29 16:37:50 +00003665 if (ProtocolExprDecls.size()) {
3666 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
3667 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump11289f42009-09-09 15:08:12 +00003668 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00003669 E = ProtocolExprDecls.end(); I != E; ++I) {
3670 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
3671 Result += (*I)->getNameAsString();
3672 Result += " = &_OBJC_PROTOCOL_";
3673 Result += (*I)->getNameAsString();
3674 Result += ";\n";
3675 }
3676 Result += "#pragma data_seg(pop)\n\n";
3677 }
Steve Naroff945a3b12008-03-10 20:43:59 +00003678 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffcab93d52008-05-07 00:06:16 +00003679 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003680 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3681 Result += "&_OBJC_MODULES;\n";
3682 Result += "#pragma data_seg(pop)\n\n";
3683 }
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003684}
Chris Lattnera7c19fe2007-10-16 22:36:42 +00003685
Steve Naroff677ab3a2008-10-27 17:20:55 +00003686std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3687 const char *funcName,
3688 std::string Tag) {
3689 const FunctionType *AFT = CE->getFunctionType();
3690 QualType RT = AFT->getResultType();
3691 std::string StructRef = "struct " + Tag;
3692 std::string S = "static " + RT.getAsString() + " __" +
3693 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00003694
Steve Naroff677ab3a2008-10-27 17:20:55 +00003695 BlockDecl *BD = CE->getBlockDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003696
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003697 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump11289f42009-09-09 15:08:12 +00003698 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Narofff26a1d42009-02-02 17:19:26 +00003699 // block (to reference imported block decl refs).
3700 S += "(" + StructRef + " *__cself)";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003701 } else if (BD->param_empty()) {
3702 S += "(" + StructRef + " *__cself)";
3703 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003704 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003705 assert(FT && "SynthesizeBlockFunc: No function proto");
3706 S += '(';
3707 // first add the implicit argument.
3708 S += StructRef + " *__cself, ";
3709 std::string ParamStr;
3710 for (BlockDecl::param_iterator AI = BD->param_begin(),
3711 E = BD->param_end(); AI != E; ++AI) {
3712 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003713 ParamStr = (*AI)->getNameAsString();
Douglas Gregor7de59662009-05-29 20:38:28 +00003714 (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003715 S += ParamStr;
3716 }
3717 if (FT->isVariadic()) {
3718 if (!BD->param_empty()) S += ", ";
3719 S += "...";
3720 }
3721 S += ')';
3722 }
3723 S += " {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003724
Steve Naroff677ab3a2008-10-27 17:20:55 +00003725 // Create local declarations to avoid rewriting all closure decl ref exprs.
3726 // First, emit a declaration for all "by ref" decls.
Mike Stump11289f42009-09-09 15:08:12 +00003727 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003728 E = BlockByRefDecls.end(); I != E; ++I) {
3729 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003730 std::string Name = (*I)->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003731 Context->getPointerType((*I)->getType()).getAsStringInternal(Name,
Douglas Gregor7de59662009-05-29 20:38:28 +00003732 Context->PrintingPolicy);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003733 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump11289f42009-09-09 15:08:12 +00003734 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003735 // Next, emit a declaration for all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003736 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003737 E = BlockByCopyDecls.end(); I != E; ++I) {
3738 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003739 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003740 // Handle nested closure invocation. For example:
3741 //
3742 // void (^myImportedClosure)(void);
3743 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003744 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003745 // void (^anotherClosure)(void);
3746 // anotherClosure = ^(void) {
3747 // myImportedClosure(); // import and invoke the closure
3748 // };
3749 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003750 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003751 S += "struct __block_impl *";
3752 else
Douglas Gregor7de59662009-05-29 20:38:28 +00003753 (*I)->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003754 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003755 }
3756 std::string RewrittenStr = RewrittenBlockExprs[CE];
3757 const char *cstr = RewrittenStr.c_str();
3758 while (*cstr++ != '{') ;
3759 S += cstr;
3760 S += "\n";
3761 return S;
3762}
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00003763
Steve Naroff677ab3a2008-10-27 17:20:55 +00003764std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3765 const char *funcName,
3766 std::string Tag) {
3767 std::string StructRef = "struct " + Tag;
3768 std::string S = "static void __";
Mike Stump11289f42009-09-09 15:08:12 +00003769
Steve Naroff677ab3a2008-10-27 17:20:55 +00003770 S += funcName;
3771 S += "_block_copy_" + utostr(i);
3772 S += "(" + StructRef;
3773 S += "*dst, " + StructRef;
3774 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003775 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003776 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003777 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003778 S += (*I)->getNameAsString();
Steve Naroff5ac4eac2008-12-11 20:51:38 +00003779 S += ", (void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003780 S += (*I)->getNameAsString();
Steve Naroff61d879e2008-12-16 15:50:30 +00003781 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);}";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003782 }
3783 S += "\nstatic void __";
3784 S += funcName;
3785 S += "_block_dispose_" + utostr(i);
3786 S += "(" + StructRef;
3787 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003788 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003789 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003790 S += "_Block_object_dispose((void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003791 S += (*I)->getNameAsString();
Steve Naroff61d879e2008-12-16 15:50:30 +00003792 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003793 }
Mike Stump11289f42009-09-09 15:08:12 +00003794 S += "}\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003795 return S;
3796}
3797
3798std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3799 bool hasCopyDisposeHelpers) {
Steve Naroff295570a2008-10-30 12:09:33 +00003800 std::string S = "\nstruct " + Tag;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003801 std::string Constructor = " " + Tag;
Mike Stump11289f42009-09-09 15:08:12 +00003802
Steve Naroff677ab3a2008-10-27 17:20:55 +00003803 S += " {\n struct __block_impl impl;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003804
Steve Naroff677ab3a2008-10-27 17:20:55 +00003805 if (hasCopyDisposeHelpers)
3806 S += " void *copy;\n void *dispose;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003807
Steve Naroff677ab3a2008-10-27 17:20:55 +00003808 Constructor += "(void *fp";
Mike Stump11289f42009-09-09 15:08:12 +00003809
Steve Naroff677ab3a2008-10-27 17:20:55 +00003810 if (hasCopyDisposeHelpers)
3811 Constructor += ", void *copyHelp, void *disposeHelp";
Mike Stump11289f42009-09-09 15:08:12 +00003812
Steve Naroff677ab3a2008-10-27 17:20:55 +00003813 if (BlockDeclRefs.size()) {
3814 // Output all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003815 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003816 E = BlockByCopyDecls.end(); I != E; ++I) {
3817 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003818 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003819 std::string ArgName = "_" + FieldName;
3820 // Handle nested closure invocation. For example:
3821 //
3822 // void (^myImportedBlock)(void);
3823 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003824 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003825 // void (^anotherBlock)(void);
3826 // anotherBlock = ^(void) {
3827 // myImportedBlock(); // import and invoke the closure
3828 // };
3829 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003830 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003831 S += "struct __block_impl *";
3832 Constructor += ", void *" + ArgName;
3833 } else {
Douglas Gregor7de59662009-05-29 20:38:28 +00003834 (*I)->getType().getAsStringInternal(FieldName, Context->PrintingPolicy);
3835 (*I)->getType().getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003836 Constructor += ", " + ArgName;
3837 }
3838 S += FieldName + ";\n";
3839 }
3840 // Output all "by ref" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003841 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003842 E = BlockByRefDecls.end(); I != E; ++I) {
3843 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003844 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003845 std::string ArgName = "_" + FieldName;
3846 // Handle nested closure invocation. For example:
3847 //
3848 // void (^myImportedBlock)(void);
3849 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003850 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003851 // void (^anotherBlock)(void);
3852 // anotherBlock = ^(void) {
3853 // myImportedBlock(); // import and invoke the closure
3854 // };
3855 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003856 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003857 S += "struct __block_impl *";
3858 Constructor += ", void *" + ArgName;
3859 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003860 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName,
Douglas Gregor7de59662009-05-29 20:38:28 +00003861 Context->PrintingPolicy);
Mike Stump11289f42009-09-09 15:08:12 +00003862 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName,
Douglas Gregor7de59662009-05-29 20:38:28 +00003863 Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003864 Constructor += ", " + ArgName;
3865 }
3866 S += FieldName + "; // by ref\n";
3867 }
3868 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00003869 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00003870 if (GlobalVarDecl)
3871 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3872 else
3873 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3874 Constructor += " impl.Size = sizeof(";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003875 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003876
Steve Naroff677ab3a2008-10-27 17:20:55 +00003877 if (hasCopyDisposeHelpers)
3878 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003879
Steve Naroff677ab3a2008-10-27 17:20:55 +00003880 // Initialize all "by copy" arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003881 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003882 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003883 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003884 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00003885 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003886 Constructor += Name + " = (struct __block_impl *)_";
3887 else
3888 Constructor += Name + " = _";
3889 Constructor += Name + ";\n";
3890 }
3891 // Initialize all "by ref" arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003892 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003893 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003894 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003895 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00003896 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003897 Constructor += Name + " = (struct __block_impl *)_";
3898 else
3899 Constructor += Name + " = _";
3900 Constructor += Name + ";\n";
3901 }
3902 } else {
3903 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00003904 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00003905 if (GlobalVarDecl)
3906 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3907 else
3908 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3909 Constructor += " impl.Size = sizeof(";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003910 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3911 if (hasCopyDisposeHelpers)
3912 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3913 }
3914 Constructor += " ";
3915 Constructor += "}\n";
3916 S += Constructor;
3917 S += "};\n";
3918 return S;
3919}
3920
3921void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3922 const char *FunName) {
3923 // Insert closures that were part of the function.
3924 for (unsigned i = 0; i < Blocks.size(); i++) {
3925
3926 CollectBlockDeclRefInfo(Blocks[i]);
3927
3928 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
Mike Stump11289f42009-09-09 15:08:12 +00003929
3930 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
Steve Naroff677ab3a2008-10-27 17:20:55 +00003931 ImportedBlockDecls.size() > 0);
3932
3933 InsertText(FunLocStart, CI.c_str(), CI.size());
3934
3935 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
Mike Stump11289f42009-09-09 15:08:12 +00003936
Steve Naroff677ab3a2008-10-27 17:20:55 +00003937 InsertText(FunLocStart, CF.c_str(), CF.size());
3938
3939 if (ImportedBlockDecls.size()) {
3940 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3941 InsertText(FunLocStart, HF.c_str(), HF.size());
3942 }
Mike Stump11289f42009-09-09 15:08:12 +00003943
Steve Naroff677ab3a2008-10-27 17:20:55 +00003944 BlockDeclRefs.clear();
3945 BlockByRefDecls.clear();
3946 BlockByCopyDecls.clear();
3947 BlockCallExprs.clear();
3948 ImportedBlockDecls.clear();
3949 }
3950 Blocks.clear();
3951 RewrittenBlockExprs.clear();
3952}
3953
3954void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3955 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner86d7d912008-11-24 03:54:41 +00003956 const char *FuncName = FD->getNameAsCString();
Mike Stump11289f42009-09-09 15:08:12 +00003957
Steve Naroff677ab3a2008-10-27 17:20:55 +00003958 SynthesizeBlockLiterals(FunLocStart, FuncName);
3959}
3960
3961void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff295570a2008-10-30 12:09:33 +00003962 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3963 //SourceLocation FunLocStart = MD->getLocStart();
3964 // FIXME: This hack works around a bug in Rewrite.InsertText().
3965 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattnere4b95692008-11-24 03:33:13 +00003966 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003967 // Convert colons to underscores.
3968 std::string::size_type loc = 0;
3969 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3970 FuncName.replace(loc, 1, "_");
Mike Stump11289f42009-09-09 15:08:12 +00003971
Steve Naroff677ab3a2008-10-27 17:20:55 +00003972 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3973}
3974
3975void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3976 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3977 CI != E; ++CI)
3978 if (*CI) {
3979 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3980 GetBlockDeclRefExprs(CBE->getBody());
3981 else
3982 GetBlockDeclRefExprs(*CI);
3983 }
3984 // Handle specific things.
3985 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3986 // FIXME: Handle enums.
3987 if (!isa<FunctionDecl>(CDRE->getDecl()))
3988 BlockDeclRefs.push_back(CDRE);
3989 return;
3990}
3991
3992void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3993 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3994 CI != E; ++CI)
3995 if (*CI) {
3996 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3997 GetBlockCallExprs(CBE->getBody());
3998 else
3999 GetBlockCallExprs(*CI);
4000 }
Mike Stump11289f42009-09-09 15:08:12 +00004001
Steve Naroff677ab3a2008-10-27 17:20:55 +00004002 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4003 if (CE->getCallee()->getType()->isBlockPointerType()) {
4004 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
4005 }
4006 }
4007 return;
4008}
4009
Steve Naroff350b6652008-10-30 10:07:53 +00004010Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004011 // Navigate to relevant type information.
4012 const char *closureName = 0;
4013 const BlockPointerType *CPT = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004014
Steve Naroff677ab3a2008-10-27 17:20:55 +00004015 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004016 closureName = DRE->getDecl()->getNameAsCString();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004017 CPT = DRE->getType()->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004018 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004019 closureName = CDRE->getDecl()->getNameAsCString();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004020 CPT = CDRE->getType()->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004021 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004022 closureName = MExpr->getMemberDecl()->getNameAsCString();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004023 CPT = MExpr->getType()->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004024 } else {
4025 assert(1 && "RewriteBlockClass: Bad type");
4026 }
4027 assert(CPT && "RewriteBlockClass: Bad type");
John McCall9dd450b2009-09-21 23:43:11 +00004028 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004029 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004030 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004031 // FTP will be null for closures that don't take arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004032
Steve Naroff350b6652008-10-30 10:07:53 +00004033 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
4034 SourceLocation(),
4035 &Context->Idents.get("__block_impl"));
4036 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff677ab3a2008-10-27 17:20:55 +00004037
Steve Naroff350b6652008-10-30 10:07:53 +00004038 // Generate a funky cast.
4039 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00004040
Steve Naroff350b6652008-10-30 10:07:53 +00004041 // Push the block argument type.
4042 ArgTypes.push_back(PtrBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004043 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004044 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff350b6652008-10-30 10:07:53 +00004045 E = FTP->arg_type_end(); I && (I != E); ++I) {
4046 QualType t = *I;
4047 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00004048 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004049 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff350b6652008-10-30 10:07:53 +00004050 t = Context->getPointerType(BPT->getPointeeType());
4051 }
4052 ArgTypes.push_back(t);
4053 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004054 }
Steve Naroff350b6652008-10-30 10:07:53 +00004055 // Now do the pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00004056 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Steve Naroff350b6652008-10-30 10:07:53 +00004057 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004058
Steve Naroff350b6652008-10-30 10:07:53 +00004059 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump11289f42009-09-09 15:08:12 +00004060
4061 CastExpr *BlkCast = new (Context) CStyleCastExpr(PtrBlock,
Anders Carlssona2615922009-07-31 00:48:10 +00004062 CastExpr::CK_Unknown,
4063 Exp->getCallee(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004064 PtrBlock, SourceLocation(),
4065 SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004066 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00004067 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4068 BlkCast);
Steve Naroff350b6652008-10-30 10:07:53 +00004069 //PE->dump();
Mike Stump11289f42009-09-09 15:08:12 +00004070
Douglas Gregor91f84212008-12-11 16:49:14 +00004071 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00004072 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004073 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek5a201952009-02-07 01:47:29 +00004074 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4075 FD->getType());
Mike Stump11289f42009-09-09 15:08:12 +00004076
Anders Carlssona2615922009-07-31 00:48:10 +00004077 CastExpr *FunkCast = new (Context) CStyleCastExpr(PtrToFuncCastType,
4078 CastExpr::CK_Unknown, ME,
Ted Kremenek5a201952009-02-07 01:47:29 +00004079 PtrToFuncCastType,
4080 SourceLocation(),
4081 SourceLocation());
4082 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump11289f42009-09-09 15:08:12 +00004083
Steve Naroff350b6652008-10-30 10:07:53 +00004084 llvm::SmallVector<Expr*, 8> BlkExprs;
4085 // Add the implicit argument.
4086 BlkExprs.push_back(BlkCast);
4087 // Add the user arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004088 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004089 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00004090 BlkExprs.push_back(*I);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004091 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004092 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4093 BlkExprs.size(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004094 Exp->getType(), SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004095 return CE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004096}
4097
4098void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Steve Naroff350b6652008-10-30 10:07:53 +00004099 Stmt *BlockCall = SynthesizeBlockCall(Exp);
4100 ReplaceStmt(Exp, BlockCall);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004101}
4102
Steve Naroffd9803712009-04-29 16:37:50 +00004103// We need to return the rewritten expression to handle cases where the
4104// BlockDeclRefExpr is embedded in another expression being rewritten.
4105// For example:
4106//
4107// int main() {
4108// __block Foo *f;
4109// __block int i;
Mike Stump11289f42009-09-09 15:08:12 +00004110//
Steve Naroffd9803712009-04-29 16:37:50 +00004111// void (^myblock)() = ^() {
4112// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4113// i = 77;
4114// };
4115//}
4116Stmt *RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004117 // FIXME: Add more elaborate code generation required by the ABI.
Ted Kremenek5a201952009-02-07 01:47:29 +00004118 Expr *DerefExpr = new (Context) UnaryOperator(BDRE, UnaryOperator::Deref,
Steve Narofff26a1d42009-02-02 17:19:26 +00004119 Context->getPointerType(BDRE->getType()),
4120 SourceLocation());
4121 // Need parens to enforce precedence.
Ted Kremenek5a201952009-02-07 01:47:29 +00004122 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), DerefExpr);
Steve Narofff26a1d42009-02-02 17:19:26 +00004123 ReplaceStmt(BDRE, PE);
Steve Naroffd9803712009-04-29 16:37:50 +00004124 return PE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004125}
4126
Steve Naroffc989a7b2008-11-03 23:29:32 +00004127void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4128 SourceLocation LocStart = CE->getLParenLoc();
4129 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofff4b992a2008-10-28 20:29:00 +00004130
4131 // Need to avoid trying to rewrite synthesized casts.
4132 if (LocStart.isInvalid())
4133 return;
Steve Naroff3e7ced12008-11-03 11:20:24 +00004134 // Need to avoid trying to rewrite casts contained in macros.
4135 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4136 return;
Mike Stump11289f42009-09-09 15:08:12 +00004137
Steve Naroff677ab3a2008-10-27 17:20:55 +00004138 const char *startBuf = SM->getCharacterData(LocStart);
4139 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00004140
Steve Naroff677ab3a2008-10-27 17:20:55 +00004141 // advance the location to startArgList.
4142 const char *argPtr = startBuf;
Mike Stump11289f42009-09-09 15:08:12 +00004143
Steve Naroff677ab3a2008-10-27 17:20:55 +00004144 while (*argPtr++ && (argPtr < endBuf)) {
4145 switch (*argPtr) {
Mike Stump11289f42009-09-09 15:08:12 +00004146 case '^':
Steve Naroff677ab3a2008-10-27 17:20:55 +00004147 // Replace the '^' with '*'.
4148 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
4149 ReplaceText(LocStart, 1, "*", 1);
4150 break;
4151 }
4152 }
4153 return;
4154}
4155
4156void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4157 SourceLocation DeclLoc = FD->getLocation();
4158 unsigned parenCount = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004159
Steve Naroff677ab3a2008-10-27 17:20:55 +00004160 // We have 1 or more arguments that have closure pointers.
4161 const char *startBuf = SM->getCharacterData(DeclLoc);
4162 const char *startArgList = strchr(startBuf, '(');
Mike Stump11289f42009-09-09 15:08:12 +00004163
Steve Naroff677ab3a2008-10-27 17:20:55 +00004164 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004165
Steve Naroff677ab3a2008-10-27 17:20:55 +00004166 parenCount++;
4167 // advance the location to startArgList.
4168 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4169 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump11289f42009-09-09 15:08:12 +00004170
Steve Naroff677ab3a2008-10-27 17:20:55 +00004171 const char *argPtr = startArgList;
Mike Stump11289f42009-09-09 15:08:12 +00004172
Steve Naroff677ab3a2008-10-27 17:20:55 +00004173 while (*argPtr++ && parenCount) {
4174 switch (*argPtr) {
Mike Stump11289f42009-09-09 15:08:12 +00004175 case '^':
Steve Naroff677ab3a2008-10-27 17:20:55 +00004176 // Replace the '^' with '*'.
4177 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
4178 ReplaceText(DeclLoc, 1, "*", 1);
4179 break;
Mike Stump11289f42009-09-09 15:08:12 +00004180 case '(':
4181 parenCount++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004182 break;
Mike Stump11289f42009-09-09 15:08:12 +00004183 case ')':
Steve Naroff677ab3a2008-10-27 17:20:55 +00004184 parenCount--;
4185 break;
4186 }
4187 }
4188 return;
4189}
4190
4191bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004192 const FunctionProtoType *FTP;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004193 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004194 if (PT) {
John McCall9dd450b2009-09-21 23:43:11 +00004195 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004196 } else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004197 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004198 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall9dd450b2009-09-21 23:43:11 +00004199 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004200 }
4201 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004202 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004203 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +00004204 if (isTopLevelBlockPointerType(*I))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004205 return true;
4206 }
4207 return false;
4208}
4209
Ted Kremenek5a201952009-02-07 01:47:29 +00004210void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4211 const char *&RParen) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004212 const char *argPtr = strchr(Name, '(');
4213 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004214
Steve Naroff677ab3a2008-10-27 17:20:55 +00004215 LParen = argPtr; // output the start.
4216 argPtr++; // skip past the left paren.
4217 unsigned parenCount = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004218
Steve Naroff677ab3a2008-10-27 17:20:55 +00004219 while (*argPtr && parenCount) {
4220 switch (*argPtr) {
4221 case '(': parenCount++; break;
4222 case ')': parenCount--; break;
4223 default: break;
4224 }
4225 if (parenCount) argPtr++;
4226 }
4227 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4228 RParen = argPtr; // output the end
4229}
4230
4231void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4232 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4233 RewriteBlockPointerFunctionArgs(FD);
4234 return;
Mike Stump11289f42009-09-09 15:08:12 +00004235 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004236 // Handle Variables and Typedefs.
4237 SourceLocation DeclLoc = ND->getLocation();
4238 QualType DeclT;
4239 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4240 DeclT = VD->getType();
4241 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4242 DeclT = TDD->getUnderlyingType();
4243 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4244 DeclT = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004245 else
Steve Naroff677ab3a2008-10-27 17:20:55 +00004246 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump11289f42009-09-09 15:08:12 +00004247
Steve Naroff677ab3a2008-10-27 17:20:55 +00004248 const char *startBuf = SM->getCharacterData(DeclLoc);
4249 const char *endBuf = startBuf;
4250 // scan backward (from the decl location) for the end of the previous decl.
4251 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4252 startBuf--;
Mike Stump11289f42009-09-09 15:08:12 +00004253
Steve Naroff677ab3a2008-10-27 17:20:55 +00004254 // *startBuf != '^' if we are dealing with a pointer to function that
4255 // may take block argument types (which will be handled below).
4256 if (*startBuf == '^') {
4257 // Replace the '^' with '*', computing a negative offset.
4258 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4259 ReplaceText(DeclLoc, 1, "*", 1);
4260 }
4261 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4262 // Replace the '^' with '*' for arguments.
4263 DeclLoc = ND->getLocation();
4264 startBuf = SM->getCharacterData(DeclLoc);
4265 const char *argListBegin, *argListEnd;
4266 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4267 while (argListBegin < argListEnd) {
4268 if (*argListBegin == '^') {
4269 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
4270 ReplaceText(CaretLoc, 1, "*", 1);
4271 }
4272 argListBegin++;
4273 }
4274 }
4275 return;
4276}
4277
Mike Stump11289f42009-09-09 15:08:12 +00004278void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004279 // Add initializers for any closure decl refs.
4280 GetBlockDeclRefExprs(Exp->getBody());
4281 if (BlockDeclRefs.size()) {
4282 // Unique all "by copy" declarations.
4283 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4284 if (!BlockDeclRefs[i]->isByRef())
4285 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
4286 // Unique all "by ref" declarations.
4287 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4288 if (BlockDeclRefs[i]->isByRef()) {
4289 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
4290 }
4291 // Find any imported blocks...they will need special attention.
4292 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Steve Naroff5ac4eac2008-12-11 20:51:38 +00004293 if (BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroff832d8902008-11-13 17:40:07 +00004294 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004295 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4296 }
4297 }
4298}
4299
Steve Narofff4b992a2008-10-28 20:29:00 +00004300FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4301 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004302 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump11289f42009-09-09 15:08:12 +00004303 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004304 ID, FType, 0, FunctionDecl::Extern, false,
Douglas Gregor739ef0c2009-02-25 16:33:18 +00004305 false);
Steve Narofff4b992a2008-10-28 20:29:00 +00004306}
4307
Steve Naroffd8907b72008-10-29 18:15:37 +00004308Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004309 Blocks.push_back(Exp);
4310
4311 CollectBlockDeclRefInfo(Exp);
4312 std::string FuncName;
Mike Stump11289f42009-09-09 15:08:12 +00004313
Steve Narofff4b992a2008-10-28 20:29:00 +00004314 if (CurFunctionDef)
Chris Lattnere4b95692008-11-24 03:33:13 +00004315 FuncName = CurFunctionDef->getNameAsString();
Steve Narofff4b992a2008-10-28 20:29:00 +00004316 else if (CurMethodDef) {
Chris Lattnere4b95692008-11-24 03:33:13 +00004317 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofff4b992a2008-10-28 20:29:00 +00004318 // Convert colons to underscores.
4319 std::string::size_type loc = 0;
4320 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4321 FuncName.replace(loc, 1, "_");
Steve Naroffd8907b72008-10-29 18:15:37 +00004322 } else if (GlobalVarDecl)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004323 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump11289f42009-09-09 15:08:12 +00004324
Steve Narofff4b992a2008-10-28 20:29:00 +00004325 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump11289f42009-09-09 15:08:12 +00004326
Steve Narofff4b992a2008-10-28 20:29:00 +00004327 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4328 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump11289f42009-09-09 15:08:12 +00004329
Steve Narofff4b992a2008-10-28 20:29:00 +00004330 // Get a pointer to the function type so we can cast appropriately.
4331 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4332
4333 FunctionDecl *FD;
4334 Expr *NewRep;
Mike Stump11289f42009-09-09 15:08:12 +00004335
Steve Narofff4b992a2008-10-28 20:29:00 +00004336 // Simulate a contructor call...
4337 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004338 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004339
Steve Narofff4b992a2008-10-28 20:29:00 +00004340 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00004341
Steve Naroffe2514232008-10-29 21:23:59 +00004342 // Initialize the block function.
Steve Narofff4b992a2008-10-28 20:29:00 +00004343 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004344 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4345 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004346 CastExpr *castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4347 CastExpr::CK_Unknown, Arg,
Ted Kremenek5a201952009-02-07 01:47:29 +00004348 Context->VoidPtrTy, SourceLocation(),
4349 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004350 InitExprs.push_back(castExpr);
4351
Steve Narofff4b992a2008-10-28 20:29:00 +00004352 if (ImportedBlockDecls.size()) {
4353 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
Steve Naroffe2514232008-10-29 21:23:59 +00004354 FD = SynthBlockInitFunctionDecl(Buf.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004355 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004356 castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4357 CastExpr::CK_Unknown, Arg,
Ted Kremenek5a201952009-02-07 01:47:29 +00004358 Context->VoidPtrTy, SourceLocation(),
4359 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004360 InitExprs.push_back(castExpr);
4361
Steve Narofff4b992a2008-10-28 20:29:00 +00004362 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
Steve Naroffe2514232008-10-29 21:23:59 +00004363 FD = SynthBlockInitFunctionDecl(Buf.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004364 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004365 castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4366 CastExpr::CK_Unknown, Arg,
Ted Kremenek5a201952009-02-07 01:47:29 +00004367 Context->VoidPtrTy, SourceLocation(),
4368 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004369 InitExprs.push_back(castExpr);
Steve Narofff4b992a2008-10-28 20:29:00 +00004370 }
4371 // Add initializers for any closure decl refs.
4372 if (BlockDeclRefs.size()) {
Steve Naroffe2514232008-10-29 21:23:59 +00004373 Expr *Exp;
Steve Narofff4b992a2008-10-28 20:29:00 +00004374 // Output all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004375 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004376 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004377 if (isObjCType((*I)->getType())) {
Steve Naroffe2514232008-10-29 21:23:59 +00004378 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner86d7d912008-11-24 03:54:41 +00004379 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004380 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroffa5c0db82008-12-11 21:05:33 +00004381 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004382 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004383 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004384 Exp = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4385 CastExpr::CK_Unknown, Arg,
4386 Context->VoidPtrTy,
Anders Carlssona2615922009-07-31 00:48:10 +00004387 SourceLocation(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004388 SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004389 } else {
Chris Lattner86d7d912008-11-24 03:54:41 +00004390 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004391 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004392 }
Mike Stump11289f42009-09-09 15:08:12 +00004393 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004394 }
4395 // Output all "by ref" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004396 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004397 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004398 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004399 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4400 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004401 Context->getPointerType(Exp->getType()),
Steve Naroffe2514232008-10-29 21:23:59 +00004402 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004403 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004404 }
4405 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004406 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4407 FType, SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00004408 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004409 Context->getPointerType(NewRep->getType()),
Steve Narofff4b992a2008-10-28 20:29:00 +00004410 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004411 NewRep = new (Context) CStyleCastExpr(FType, CastExpr::CK_Unknown, NewRep,
Anders Carlssona2615922009-07-31 00:48:10 +00004412 FType, SourceLocation(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004413 SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004414 BlockDeclRefs.clear();
4415 BlockByRefDecls.clear();
4416 BlockByCopyDecls.clear();
4417 ImportedBlockDecls.clear();
4418 return NewRep;
4419}
4420
4421//===----------------------------------------------------------------------===//
4422// Function Body / Expression rewriting
4423//===----------------------------------------------------------------------===//
4424
Steve Naroff4588d0f2008-12-04 16:24:46 +00004425// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4426// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4427// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4428// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4429// Since the rewriter isn't capable of rewriting rewritten code, it's important
4430// we get this right.
4431void RewriteObjC::CollectPropertySetters(Stmt *S) {
4432 // Perform a bottom up traversal of all children.
4433 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4434 CI != E; ++CI)
4435 if (*CI)
4436 CollectPropertySetters(*CI);
4437
4438 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4439 if (BinOp->isAssignmentOp()) {
4440 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4441 PropSetters[PRE] = BinOp;
4442 }
4443 }
4444}
4445
Steve Narofff4b992a2008-10-28 20:29:00 +00004446Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump11289f42009-09-09 15:08:12 +00004447 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004448 isa<DoStmt>(S) || isa<ForStmt>(S))
4449 Stmts.push_back(S);
4450 else if (isa<ObjCForCollectionStmt>(S)) {
4451 Stmts.push_back(S);
4452 ObjCBcLabelNo.push_back(++BcLabelCount);
4453 }
Mike Stump11289f42009-09-09 15:08:12 +00004454
Steve Narofff4b992a2008-10-28 20:29:00 +00004455 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004456
Steve Narofff4b992a2008-10-28 20:29:00 +00004457 // Perform a bottom up rewrite of all children.
4458 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4459 CI != E; ++CI)
4460 if (*CI) {
4461 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Mike Stump11289f42009-09-09 15:08:12 +00004462 if (newStmt)
Steve Narofff4b992a2008-10-28 20:29:00 +00004463 *CI = newStmt;
4464 }
Mike Stump11289f42009-09-09 15:08:12 +00004465
Steve Narofff4b992a2008-10-28 20:29:00 +00004466 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4467 // Rewrite the block body in place.
4468 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Mike Stump11289f42009-09-09 15:08:12 +00004469
Steve Narofff4b992a2008-10-28 20:29:00 +00004470 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroffd8907b72008-10-29 18:15:37 +00004471 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
4472 RewrittenBlockExprs[BE] = Str;
Mike Stump11289f42009-09-09 15:08:12 +00004473
Steve Narofff4b992a2008-10-28 20:29:00 +00004474 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4475 //blockTranscribed->dump();
Steve Naroffd8907b72008-10-29 18:15:37 +00004476 ReplaceStmt(S, blockTranscribed);
Steve Narofff4b992a2008-10-28 20:29:00 +00004477 return blockTranscribed;
4478 }
4479 // Handle specific things.
4480 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4481 return RewriteAtEncode(AtEncode);
Mike Stump11289f42009-09-09 15:08:12 +00004482
Steve Narofff4b992a2008-10-28 20:29:00 +00004483 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4484 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4485
Steve Naroff4588d0f2008-12-04 16:24:46 +00004486 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4487 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4488 if (BinOp) {
4489 // Because the rewriter doesn't allow us to rewrite rewritten code,
4490 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroff08628db2008-12-09 12:56:34 +00004491 DisableReplaceStmt = true;
4492 // Save the source range. Even if we disable the replacement, the
4493 // rewritten node will have been inserted into the tree. If the synthesized
4494 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump11289f42009-09-09 15:08:12 +00004495 // self.errorHandler = handler ? handler :
Steve Naroff08628db2008-12-09 12:56:34 +00004496 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4497 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroff4588d0f2008-12-04 16:24:46 +00004498 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroff08628db2008-12-09 12:56:34 +00004499 DisableReplaceStmt = false;
Steve Naroff22216db2008-12-04 23:50:32 +00004500 //
4501 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4502 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4503 // to see the original expression). Consider this example:
4504 //
4505 // Foo *obj1, *obj2;
4506 //
4507 // obj1.i = [obj2 rrrr];
4508 //
4509 // 'BinOp' for the previous expression looks like:
4510 //
4511 // (BinaryOperator 0x231ccf0 'int' '='
4512 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4513 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4514 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4515 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4516 //
4517 // 'newStmt' represents the rewritten message expression. For example:
4518 //
4519 // (CallExpr 0x231d300 'id':'struct objc_object *'
4520 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4521 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4522 // (CStyleCastExpr 0x231d220 'void *'
4523 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4524 //
4525 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4526 // can be used as the setter argument. ReplaceStmt() will still 'see'
4527 // the original RHS (since we haven't altered BinOp).
4528 //
Mike Stump11289f42009-09-09 15:08:12 +00004529 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff22216db2008-12-04 23:50:32 +00004530 // node. As a result, we now leak the original AST nodes.
4531 //
Steve Naroff08628db2008-12-09 12:56:34 +00004532 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroff4588d0f2008-12-04 16:24:46 +00004533 } else {
4534 return RewritePropertyGetter(PropRefExpr);
Steve Narofff326f402008-12-03 00:56:33 +00004535 }
4536 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004537 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4538 return RewriteAtSelector(AtSelector);
Mike Stump11289f42009-09-09 15:08:12 +00004539
Steve Narofff4b992a2008-10-28 20:29:00 +00004540 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4541 return RewriteObjCStringLiteral(AtString);
Mike Stump11289f42009-09-09 15:08:12 +00004542
Steve Narofff4b992a2008-10-28 20:29:00 +00004543 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00004544#if 0
Steve Narofff4b992a2008-10-28 20:29:00 +00004545 // Before we rewrite it, put the original message expression in a comment.
4546 SourceLocation startLoc = MessExpr->getLocStart();
4547 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00004548
Steve Narofff4b992a2008-10-28 20:29:00 +00004549 const char *startBuf = SM->getCharacterData(startLoc);
4550 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004551
Steve Narofff4b992a2008-10-28 20:29:00 +00004552 std::string messString;
4553 messString += "// ";
4554 messString.append(startBuf, endBuf-startBuf+1);
4555 messString += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00004556
4557 // FIXME: Missing definition of
Steve Narofff4b992a2008-10-28 20:29:00 +00004558 // InsertText(clang::SourceLocation, char const*, unsigned int).
4559 // InsertText(startLoc, messString.c_str(), messString.size());
4560 // Tried this, but it didn't work either...
4561 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff4588d0f2008-12-04 16:24:46 +00004562#endif
Steve Narofff4b992a2008-10-28 20:29:00 +00004563 return RewriteMessageExpr(MessExpr);
4564 }
Mike Stump11289f42009-09-09 15:08:12 +00004565
Steve Narofff4b992a2008-10-28 20:29:00 +00004566 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4567 return RewriteObjCTryStmt(StmtTry);
4568
4569 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4570 return RewriteObjCSynchronizedStmt(StmtTry);
4571
4572 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4573 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump11289f42009-09-09 15:08:12 +00004574
Steve Narofff4b992a2008-10-28 20:29:00 +00004575 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4576 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump11289f42009-09-09 15:08:12 +00004577
4578 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofff4b992a2008-10-28 20:29:00 +00004579 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump11289f42009-09-09 15:08:12 +00004580 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofff4b992a2008-10-28 20:29:00 +00004581 OrigStmtRange.getEnd());
4582 if (BreakStmt *StmtBreakStmt =
4583 dyn_cast<BreakStmt>(S))
4584 return RewriteBreakStmt(StmtBreakStmt);
4585 if (ContinueStmt *StmtContinueStmt =
4586 dyn_cast<ContinueStmt>(S))
4587 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump11289f42009-09-09 15:08:12 +00004588
4589 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofff4b992a2008-10-28 20:29:00 +00004590 // and cast exprs.
4591 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4592 // FIXME: What we're doing here is modifying the type-specifier that
4593 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump11289f42009-09-09 15:08:12 +00004594 // a separate type-specifier that we can rewrite.
Steve Naroffe70a52a2009-12-05 15:55:59 +00004595 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4596 // the context of an ObjCForCollectionStmt. For example:
4597 // NSArray *someArray;
4598 // for (id <FooProtocol> index in someArray) ;
4599 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4600 // and it depends on the original text locations/positions.
Benjamin Krameracc5fa12009-12-05 22:16:51 +00004601 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroffe70a52a2009-12-05 15:55:59 +00004602 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump11289f42009-09-09 15:08:12 +00004603
Steve Narofff4b992a2008-10-28 20:29:00 +00004604 // Blocks rewrite rules.
4605 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4606 DI != DE; ++DI) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004607 Decl *SD = *DI;
Steve Narofff4b992a2008-10-28 20:29:00 +00004608 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004609 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004610 RewriteBlockPointerDecl(ND);
Mike Stump11289f42009-09-09 15:08:12 +00004611 else if (ND->getType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004612 CheckFunctionPointerDecl(ND->getType(), ND);
4613 }
4614 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004615 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004616 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00004617 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004618 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4619 }
4620 }
4621 }
Mike Stump11289f42009-09-09 15:08:12 +00004622
Steve Narofff4b992a2008-10-28 20:29:00 +00004623 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4624 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump11289f42009-09-09 15:08:12 +00004625
4626 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004627 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4628 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump11289f42009-09-09 15:08:12 +00004629 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4630 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004631 && "Statement stack mismatch");
4632 Stmts.pop_back();
4633 }
4634 // Handle blocks rewriting.
4635 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4636 if (BDRE->isByRef())
Steve Naroffd9803712009-04-29 16:37:50 +00004637 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofff4b992a2008-10-28 20:29:00 +00004638 }
4639 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff350b6652008-10-30 10:07:53 +00004640 if (CE->getCallee()->getType()->isBlockPointerType()) {
4641 Stmt *BlockCall = SynthesizeBlockCall(CE);
4642 ReplaceStmt(S, BlockCall);
4643 return BlockCall;
4644 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004645 }
Steve Naroffc989a7b2008-11-03 23:29:32 +00004646 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004647 RewriteCastExpr(CE);
4648 }
4649#if 0
4650 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek5a201952009-02-07 01:47:29 +00004651 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004652 // Get the new text.
4653 std::string SStr;
4654 llvm::raw_string_ostream Buf(SStr);
Eli Friedman0905f142009-05-30 05:19:26 +00004655 Replacement->printPretty(Buf, *Context);
Steve Narofff4b992a2008-10-28 20:29:00 +00004656 const std::string &Str = Buf.str();
4657
4658 printf("CAST = %s\n", &Str[0]);
4659 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4660 delete S;
4661 return Replacement;
4662 }
4663#endif
4664 // Return this stmt unmodified.
4665 return S;
4666}
4667
Steve Naroffe70a52a2009-12-05 15:55:59 +00004668void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
4669 for (RecordDecl::field_iterator i = RD->field_begin(),
4670 e = RD->field_end(); i != e; ++i) {
4671 FieldDecl *FD = *i;
4672 if (isTopLevelBlockPointerType(FD->getType()))
4673 RewriteBlockPointerDecl(FD);
4674 if (FD->getType()->isObjCQualifiedIdType() ||
4675 FD->getType()->isObjCQualifiedInterfaceType())
4676 RewriteObjCQualifiedInterfaceTypes(FD);
4677 }
4678}
4679
Steve Narofff4b992a2008-10-28 20:29:00 +00004680/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4681/// main file of the input.
4682void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4683 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffb1368882008-12-17 00:20:22 +00004684 if (FD->isOverloadedOperator())
4685 return;
Mike Stump11289f42009-09-09 15:08:12 +00004686
Steve Narofff4b992a2008-10-28 20:29:00 +00004687 // Since function prototypes don't have ParmDecl's, we check the function
4688 // prototype. This enables us to rewrite function declarations and
4689 // definitions using the same code.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004690 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofff4b992a2008-10-28 20:29:00 +00004691
Sebastian Redla7b98a72009-04-26 20:35:05 +00004692 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00004693 if (CompoundStmt *Body = FD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004694 CurFunctionDef = FD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00004695 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00004696 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00004697 Body =
4698 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4699 FD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00004700 CurrentBody = 0;
4701 if (PropParentMap) {
4702 delete PropParentMap;
4703 PropParentMap = 0;
4704 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004705 // This synthesizes and inserts the block "impl" struct, invoke function,
4706 // and any copy/dispose helper functions.
4707 InsertBlockLiteralsWithinFunction(FD);
4708 CurFunctionDef = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004709 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004710 return;
4711 }
4712 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00004713 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004714 CurMethodDef = MD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00004715 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00004716 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00004717 Body =
4718 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4719 MD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00004720 CurrentBody = 0;
4721 if (PropParentMap) {
4722 delete PropParentMap;
4723 PropParentMap = 0;
4724 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004725 InsertBlockLiteralsWithinMethod(MD);
4726 CurMethodDef = 0;
4727 }
4728 }
4729 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
4730 ClassImplementation.push_back(CI);
4731 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4732 CategoryImplementation.push_back(CI);
4733 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4734 RewriteForwardClassDecl(CD);
4735 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4736 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroffa5c0db82008-12-11 21:05:33 +00004737 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004738 RewriteBlockPointerDecl(VD);
Steve Naroffd8907b72008-10-29 18:15:37 +00004739 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004740 CheckFunctionPointerDecl(VD->getType(), VD);
4741 if (VD->getInit()) {
Steve Naroffc989a7b2008-11-03 23:29:32 +00004742 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004743 RewriteCastExpr(CE);
4744 }
4745 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00004746 } else if (VD->getType()->isRecordType()) {
4747 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4748 if (RD->isDefinition())
4749 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00004750 }
Steve Naroffd8907b72008-10-29 18:15:37 +00004751 if (VD->getInit()) {
4752 GlobalVarDecl = VD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00004753 CollectPropertySetters(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00004754 CurrentBody = VD->getInit();
Steve Naroffd8907b72008-10-29 18:15:37 +00004755 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00004756 CurrentBody = 0;
4757 if (PropParentMap) {
4758 delete PropParentMap;
4759 PropParentMap = 0;
4760 }
Mike Stump11289f42009-09-09 15:08:12 +00004761 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner86d7d912008-11-24 03:54:41 +00004762 VD->getNameAsCString());
Steve Naroffd8907b72008-10-29 18:15:37 +00004763 GlobalVarDecl = 0;
4764
4765 // This is needed for blocks.
Steve Naroffc989a7b2008-11-03 23:29:32 +00004766 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroffd8907b72008-10-29 18:15:37 +00004767 RewriteCastExpr(CE);
4768 }
4769 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004770 return;
4771 }
4772 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004773 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004774 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00004775 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004776 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Steve Naroffe70a52a2009-12-05 15:55:59 +00004777 else if (TD->getUnderlyingType()->isRecordType()) {
4778 RecordDecl *RD = TD->getUnderlyingType()->getAs<RecordType>()->getDecl();
4779 if (RD->isDefinition())
4780 RewriteRecordBody(RD);
4781 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004782 return;
4783 }
4784 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroffe70a52a2009-12-05 15:55:59 +00004785 if (RD->isDefinition())
4786 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00004787 return;
4788 }
4789 // Nothing yet.
4790}
4791
Chris Lattnercf169832009-03-28 04:11:33 +00004792void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004793 // Get the top-level buffer that this corresponds to.
Mike Stump11289f42009-09-09 15:08:12 +00004794
Steve Narofff4b992a2008-10-28 20:29:00 +00004795 // Rewrite tabs if we care.
4796 //RewriteTabs();
Mike Stump11289f42009-09-09 15:08:12 +00004797
Steve Narofff4b992a2008-10-28 20:29:00 +00004798 if (Diags.hasErrorOccurred())
4799 return;
Mike Stump11289f42009-09-09 15:08:12 +00004800
Steve Narofff4b992a2008-10-28 20:29:00 +00004801 RewriteInclude();
Mike Stump11289f42009-09-09 15:08:12 +00004802
Steve Naroffd9803712009-04-29 16:37:50 +00004803 // Here's a great place to add any extra declarations that may be needed.
4804 // Write out meta data for each @protocol(<expr>).
Mike Stump11289f42009-09-09 15:08:12 +00004805 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00004806 E = ProtocolExprDecls.end(); I != E; ++I)
4807 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
4808
Mike Stump11289f42009-09-09 15:08:12 +00004809 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Narofff4b992a2008-10-28 20:29:00 +00004810 Preamble.c_str(), Preamble.size(), false);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00004811 if (ClassImplementation.size() || CategoryImplementation.size())
4812 RewriteImplementations();
Steve Naroffd9803712009-04-29 16:37:50 +00004813
Steve Narofff4b992a2008-10-28 20:29:00 +00004814 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4815 // we are done.
Mike Stump11289f42009-09-09 15:08:12 +00004816 if (const RewriteBuffer *RewriteBuf =
Steve Narofff4b992a2008-10-28 20:29:00 +00004817 Rewrite.getRewriteBufferFor(MainFileID)) {
4818 //printf("Changed:\n");
4819 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4820 } else {
4821 fprintf(stderr, "No changes\n");
4822 }
Steve Narofff8cfd162008-11-13 20:07:04 +00004823
Steve Naroffd9803712009-04-29 16:37:50 +00004824 if (ClassImplementation.size() || CategoryImplementation.size() ||
4825 ProtocolExprDecls.size()) {
Steve Naroff2a2a41f2008-11-14 14:10:01 +00004826 // Rewrite Objective-c meta data*
4827 std::string ResultStr;
4828 SynthesizeMetaDataIntoBuffer(ResultStr);
4829 // Emit metadata.
4830 *OutFile << ResultStr;
4831 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004832 OutFile->flush();
4833}
4834