blob: cd497a7838d55caf794994e5fa8f509fe9892d1a [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);
Steve Naroff30484702009-12-06 21:14:13 +0000334 std::string SynthesizeBlockImpl(BlockExpr *CE,
335 std::string Tag, std::string Desc);
336 std::string SynthesizeBlockDescriptor(std::string DescTag,
337 std::string ImplTag,
338 int i, const char *funcName,
339 unsigned hasCopy);
Steve Naroff350b6652008-10-30 10:07:53 +0000340 Stmt *SynthesizeBlockCall(CallExpr *Exp);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000341 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
342 const char *FunName);
Steve Naroffe70a52a2009-12-05 15:55:59 +0000343 void RewriteRecordBody(RecordDecl *RD);
Mike Stump11289f42009-09-09 15:08:12 +0000344
Steve Naroff677ab3a2008-10-27 17:20:55 +0000345 void CollectBlockDeclRefInfo(BlockExpr *Exp);
346 void GetBlockCallExprs(Stmt *S);
347 void GetBlockDeclRefExprs(Stmt *S);
Mike Stump11289f42009-09-09 15:08:12 +0000348
Steve Naroff677ab3a2008-10-27 17:20:55 +0000349 // We avoid calling Type::isBlockPointerType(), since it operates on the
350 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek5a201952009-02-07 01:47:29 +0000351 bool isTopLevelBlockPointerType(QualType T) {
352 return isa<BlockPointerType>(T);
353 }
Mike Stump11289f42009-09-09 15:08:12 +0000354
Steve Naroff677ab3a2008-10-27 17:20:55 +0000355 // FIXME: This predicate seems like it would be useful to add to ASTContext.
356 bool isObjCType(QualType T) {
357 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
358 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000359
Steve Naroff677ab3a2008-10-27 17:20:55 +0000360 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000361
Steve Naroff677ab3a2008-10-27 17:20:55 +0000362 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
363 OCT == Context->getCanonicalType(Context->getObjCClassType()))
364 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000365
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000366 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +0000367 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Narofffb4330f2009-06-17 22:40:22 +0000368 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff677ab3a2008-10-27 17:20:55 +0000369 return true;
370 }
371 return false;
372 }
373 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek5a201952009-02-07 01:47:29 +0000374 void GetExtentOfArgList(const char *Name, const char *&LParen,
375 const char *&RParen);
Steve Naroffc989a7b2008-11-03 23:29:32 +0000376 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump11289f42009-09-09 15:08:12 +0000377
Steve Narofff4b992a2008-10-28 20:29:00 +0000378 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroffd8907b72008-10-29 18:15:37 +0000379 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Mike Stump11289f42009-09-09 15:08:12 +0000380
Steve Naroffd9803712009-04-29 16:37:50 +0000381 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump11289f42009-09-09 15:08:12 +0000382 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroffd9803712009-04-29 16:37:50 +0000383 if (From[i] == '"')
384 To += "\\\"";
385 else
386 To += From[i];
387 }
388 }
Chris Lattnere99c8322007-10-11 00:43:27 +0000389 };
390}
391
Mike Stump11289f42009-09-09 15:08:12 +0000392void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
393 NamedDecl *D) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000394 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000395 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +0000396 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +0000397 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +0000398 // All the args are checked/rewritten. Don't call twice!
399 RewriteBlockPointerDecl(D);
400 break;
401 }
402 }
403}
404
405void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000406 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +0000407 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000408 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000409}
410
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000411static bool IsHeaderFile(const std::string &Filename) {
412 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump11289f42009-09-09 15:08:12 +0000413
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000414 if (DotPos == std::string::npos) {
415 // no file extension
Mike Stump11289f42009-09-09 15:08:12 +0000416 return false;
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000417 }
Mike Stump11289f42009-09-09 15:08:12 +0000418
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000419 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
420 // C header: .h
421 // C++ header: .hh or .H;
422 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump11289f42009-09-09 15:08:12 +0000423}
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000424
Eli Friedman94cf21e2009-05-18 22:20:00 +0000425RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000426 Diagnostic &D, const LangOptions &LOpts,
427 bool silenceMacroWarn)
428 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
429 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Narofff9e7c902008-03-28 22:26:09 +0000430 IsHeader = IsHeaderFile(inFile);
Mike Stump11289f42009-09-09 15:08:12 +0000431 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Narofff9e7c902008-03-28 22:26:09 +0000432 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump11289f42009-09-09 15:08:12 +0000433 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek5a201952009-02-07 01:47:29 +0000434 "rewriter doesn't support user-specified control flow semantics "
435 "for @try/@finally (code may not execute properly)");
Steve Narofff9e7c902008-03-28 22:26:09 +0000436}
437
Eli Friedmana63ab2d2009-05-18 22:29:17 +0000438ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
439 llvm::raw_ostream* OS,
Mike Stump11289f42009-09-09 15:08:12 +0000440 Diagnostic &Diags,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000441 const LangOptions &LOpts,
442 bool SilenceRewriteMacroWarning) {
443 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere9c810c2007-11-30 22:25:36 +0000444}
Chris Lattnere99c8322007-10-11 00:43:27 +0000445
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000446void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner187f6262008-01-31 19:38:44 +0000447 Context = &context;
448 SM = &Context->getSourceManager();
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +0000449 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner187f6262008-01-31 19:38:44 +0000450 MsgSendFunctionDecl = 0;
451 MsgSendSuperFunctionDecl = 0;
452 MsgSendStretFunctionDecl = 0;
453 MsgSendSuperStretFunctionDecl = 0;
454 MsgSendFpretFunctionDecl = 0;
455 GetClassFunctionDecl = 0;
456 GetMetaClassFunctionDecl = 0;
457 SelGetUidFunctionDecl = 0;
458 CFStringFunctionDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000459 ConstantStringClassReference = 0;
460 NSStringRecord = 0;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000461 CurMethodDef = 0;
462 CurFunctionDef = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000463 GlobalVarDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000464 SuperStructDecl = 0;
Steve Naroffd9803712009-04-29 16:37:50 +0000465 ProtocolTypeDecl = 0;
Steve Naroff60a9ef62008-03-27 22:59:54 +0000466 ConstantStringDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000467 BcLabelCount = 0;
Steve Naroff17978c42008-03-11 17:37:02 +0000468 SuperContructorFunctionDecl = 0;
Steve Naroffce8e8862008-03-15 00:55:56 +0000469 NumObjCStringLiterals = 0;
Steve Narofff1ab6002008-12-08 20:01:41 +0000470 PropParentMap = 0;
471 CurrentBody = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000472 DisableReplaceStmt = false;
Mike Stump11289f42009-09-09 15:08:12 +0000473
Chris Lattner187f6262008-01-31 19:38:44 +0000474 // Get the ID and start/end of the main file.
475 MainFileID = SM->getMainFileID();
476 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
477 MainFileStart = MainBuf->getBufferStart();
478 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000479
Chris Lattner184e65d2009-04-14 23:22:57 +0000480 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump11289f42009-09-09 15:08:12 +0000481
Chris Lattner187f6262008-01-31 19:38:44 +0000482 // declaring objc_selector outside the parameter list removes a silly
483 // scope related warning...
Steve Naroff00a31762008-03-27 22:29:16 +0000484 if (IsHeader)
Steve Narofffcc6fd52009-02-03 20:39:18 +0000485 Preamble = "#pragma once\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000486 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff6ab6dc72008-12-23 20:11:22 +0000487 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroff00a31762008-03-27 22:29:16 +0000488 Preamble += "struct objc_object *superClass; ";
Steve Naroff17978c42008-03-11 17:37:02 +0000489 if (LangOpts.Microsoft) {
490 // Add a constructor for creating temporary objects.
Ted Kremenek5a201952009-02-07 01:47:29 +0000491 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
492 ": ";
Steve Naroff00a31762008-03-27 22:29:16 +0000493 Preamble += "object(o), superClass(s) {} ";
Steve Naroff17978c42008-03-11 17:37:02 +0000494 }
Steve Naroff00a31762008-03-27 22:29:16 +0000495 Preamble += "};\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000496 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
497 Preamble += "typedef struct objc_object Protocol;\n";
498 Preamble += "#define _REWRITER_typedef_Protocol\n";
499 Preamble += "#endif\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000500 if (LangOpts.Microsoft) {
501 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
502 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
503 } else
504 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
505 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
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";
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 struct objc_object *objc_msgSend_stret";
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_msgSendSuper_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000512 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000513 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroff00a31762008-03-27 22:29:16 +0000514 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000515 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000516 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000517 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000518 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000519 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
520 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
521 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
522 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
523 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroffd30f8c52008-05-09 21:17:56 +0000524 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff8dd15252008-07-16 18:58:11 +0000525 // @synchronized hooks.
Steve Narofff122ff02008-12-08 17:30:33 +0000526 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
527 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
528 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000529 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
530 Preamble += "struct __objcFastEnumerationState {\n\t";
531 Preamble += "unsigned long state;\n\t";
Steve Naroff4dbab8a2008-04-04 22:58:22 +0000532 Preamble += "void **itemsPtr;\n\t";
Steve Naroff00a31762008-03-27 22:29:16 +0000533 Preamble += "unsigned long *mutationsPtr;\n\t";
534 Preamble += "unsigned long extra[5];\n};\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000535 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000536 Preamble += "#define __FASTENUMERATIONSTATE\n";
537 Preamble += "#endif\n";
538 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
539 Preamble += "struct __NSConstantStringImpl {\n";
540 Preamble += " int *isa;\n";
541 Preamble += " int flags;\n";
542 Preamble += " char *str;\n";
543 Preamble += " long length;\n";
544 Preamble += "};\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000545 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
546 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
547 Preamble += "#else\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000548 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000549 Preamble += "#endif\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000550 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
551 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000552 // Blocks preamble.
553 Preamble += "#ifndef BLOCK_IMPL\n";
554 Preamble += "#define BLOCK_IMPL\n";
555 Preamble += "struct __block_impl {\n";
556 Preamble += " void *isa;\n";
557 Preamble += " int Flags;\n";
Steve Naroff30484702009-12-06 21:14:13 +0000558 Preamble += " int Reserved;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000559 Preamble += " void *FuncPtr;\n";
560 Preamble += "};\n";
Steve Naroff61d879e2008-12-16 15:50:30 +0000561 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroff287a2bf2009-12-06 01:52:22 +0000562 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000563 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_assign(void *, const void *, const int);\n";
564 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
565 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
566 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
567 Preamble += "#else\n";
568 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
569 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
570 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
571 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
572 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000573 Preamble += "#endif\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000574 if (LangOpts.Microsoft) {
Steve Narofff122ff02008-12-08 17:30:33 +0000575 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
576 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000577 Preamble += "#define __attribute__(X)\n";
578 }
Chris Lattner187f6262008-01-31 19:38:44 +0000579}
580
581
Chris Lattner3c799d72007-10-24 17:06:59 +0000582//===----------------------------------------------------------------------===//
583// Top Level Driver Code
584//===----------------------------------------------------------------------===//
585
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000586void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Chris Lattner0bd1c972007-10-16 21:07:07 +0000587 // Two cases: either the decl could be in the main file, or it could be in a
588 // #included file. If the former, rewrite it now. If the later, check to see
589 // if we rewrote the #include/#import.
590 SourceLocation Loc = D->getLocation();
Chris Lattner8a425862009-01-16 07:36:28 +0000591 Loc = SM->getInstantiationLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000592
Chris Lattner0bd1c972007-10-16 21:07:07 +0000593 // If this is for a builtin, ignore it.
594 if (Loc.isInvalid()) return;
595
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000596 // Look for built-in declarations that we need to refer during the rewrite.
597 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000598 RewriteFunctionDecl(FD);
Steve Naroff08899ff2008-04-15 22:42:06 +0000599 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000600 // declared in <Foundation/NSString.h>
Chris Lattner86d7d912008-11-24 03:54:41 +0000601 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000602 ConstantStringClassReference = FVD;
603 return;
604 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000605 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff161a92b2007-10-26 20:53:56 +0000606 RewriteInterfaceDecl(MD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000607 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000608 RewriteCategoryDecl(CD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000609 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff921385f2007-10-30 16:42:30 +0000610 RewriteProtocolDecl(PD);
Mike Stump11289f42009-09-09 15:08:12 +0000611 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000612 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000613 RewriteForwardProtocolDecl(FP);
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000614 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
615 // Recurse into linkage specifications
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000616 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
617 DIEnd = LSD->decls_end();
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000618 DI != DIEnd; ++DI)
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000619 HandleTopLevelSingleDecl(*DI);
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000620 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000621 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekd61ed3b2008-04-14 21:24:13 +0000622 if (SM->isFromMainFile(Loc))
Chris Lattner0bd1c972007-10-16 21:07:07 +0000623 return HandleDeclInMainFile(D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000624}
625
Chris Lattner3c799d72007-10-24 17:06:59 +0000626//===----------------------------------------------------------------------===//
627// Syntactic (non-AST) Rewriting Code
628//===----------------------------------------------------------------------===//
629
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000630void RewriteObjC::RewriteInclude() {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000631 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000632 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
633 const char *MainBufStart = MainBuf.first;
634 const char *MainBufEnd = MainBuf.second;
635 size_t ImportLen = strlen("import");
636 size_t IncludeLen = strlen("include");
Mike Stump11289f42009-09-09 15:08:12 +0000637
Fariborz Jahanian137d6932008-01-19 01:03:17 +0000638 // Loop over the whole file, looking for includes.
Fariborz Jahanian80258362008-01-19 00:30:35 +0000639 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
640 if (*BufPtr == '#') {
641 if (++BufPtr == MainBufEnd)
642 return;
643 while (*BufPtr == ' ' || *BufPtr == '\t')
644 if (++BufPtr == MainBufEnd)
645 return;
646 if (!strncmp(BufPtr, "import", ImportLen)) {
647 // replace import with include
Mike Stump11289f42009-09-09 15:08:12 +0000648 SourceLocation ImportLoc =
Fariborz Jahanian80258362008-01-19 00:30:35 +0000649 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000650 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000651 BufPtr += ImportLen;
652 }
653 }
654 }
Chris Lattner0bd1c972007-10-16 21:07:07 +0000655}
656
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000657void RewriteObjC::RewriteTabs() {
Chris Lattner3c799d72007-10-24 17:06:59 +0000658 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
659 const char *MainBufStart = MainBuf.first;
660 const char *MainBufEnd = MainBuf.second;
Mike Stump11289f42009-09-09 15:08:12 +0000661
Chris Lattner3c799d72007-10-24 17:06:59 +0000662 // Loop over the whole file, looking for tabs.
663 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
664 if (*BufPtr != '\t')
665 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000666
Chris Lattner3c799d72007-10-24 17:06:59 +0000667 // Okay, we found a tab. This tab will turn into at least one character,
668 // but it depends on which 'virtual column' it is in. Compute that now.
669 unsigned VCol = 0;
670 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
671 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
672 ++VCol;
Mike Stump11289f42009-09-09 15:08:12 +0000673
Chris Lattner3c799d72007-10-24 17:06:59 +0000674 // Okay, now that we know the virtual column, we know how many spaces to
675 // insert. We assume 8-character tab-stops.
676 unsigned Spaces = 8-(VCol & 7);
Mike Stump11289f42009-09-09 15:08:12 +0000677
Chris Lattner3c799d72007-10-24 17:06:59 +0000678 // Get the location of the tab.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000679 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
680 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Mike Stump11289f42009-09-09 15:08:12 +0000681
Chris Lattner3c799d72007-10-24 17:06:59 +0000682 // Rewrite the single tab character into a sequence of spaces.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000683 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattner3c799d72007-10-24 17:06:59 +0000684 }
Chris Lattner16a0de42007-10-11 18:38:32 +0000685}
686
Steve Naroff9af94912008-12-02 15:48:25 +0000687static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
688 ObjCIvarDecl *OID) {
689 std::string S;
690 S = "((struct ";
691 S += ClassDecl->getIdentifier()->getName();
692 S += "_IMPL *)self)->";
Daniel Dunbar70e7ead2009-10-18 20:26:27 +0000693 S += OID->getName();
Steve Naroff9af94912008-12-02 15:48:25 +0000694 return S;
695}
696
Steve Naroffc038b3a2008-12-02 17:36:43 +0000697void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
698 ObjCImplementationDecl *IMD,
699 ObjCCategoryImplDecl *CID) {
Steve Naroffe1908e32008-12-01 20:33:01 +0000700 SourceLocation startLoc = PID->getLocStart();
701 InsertText(startLoc, "// ", 3);
Steve Naroff9af94912008-12-02 15:48:25 +0000702 const char *startBuf = SM->getCharacterData(startLoc);
703 assert((*startBuf == '@') && "bogus @synthesize location");
704 const char *semiBuf = strchr(startBuf, ';');
705 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek5a201952009-02-07 01:47:29 +0000706 SourceLocation onePastSemiLoc =
707 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroff9af94912008-12-02 15:48:25 +0000708
709 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
710 return; // FIXME: is this correct?
Mike Stump11289f42009-09-09 15:08:12 +0000711
Steve Naroff9af94912008-12-02 15:48:25 +0000712 // Generate the 'getter' function.
Steve Naroff9af94912008-12-02 15:48:25 +0000713 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroff9af94912008-12-02 15:48:25 +0000714 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroff9af94912008-12-02 15:48:25 +0000715 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000716
Steve Naroff003d00e2008-12-02 16:05:55 +0000717 if (!OID)
718 return;
Mike Stump11289f42009-09-09 15:08:12 +0000719
Steve Naroff003d00e2008-12-02 16:05:55 +0000720 std::string Getr;
721 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
722 Getr += "{ ";
723 // Synthesize an explicit cast to gain access to the ivar.
Mike Stump11289f42009-09-09 15:08:12 +0000724 // FIXME: deal with code generation implications for various property
725 // attributes (copy, retain, nonatomic).
Steve Naroff06297042008-12-02 17:54:50 +0000726 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroff003d00e2008-12-02 16:05:55 +0000727 Getr += "return " + getIvarAccessString(ClassDecl, OID);
728 Getr += "; }";
Steve Naroff9af94912008-12-02 15:48:25 +0000729 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroff9af94912008-12-02 15:48:25 +0000730 if (PD->isReadOnly())
731 return;
Mike Stump11289f42009-09-09 15:08:12 +0000732
Steve Naroff9af94912008-12-02 15:48:25 +0000733 // Generate the 'setter' function.
734 std::string Setr;
735 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroff9af94912008-12-02 15:48:25 +0000736 Setr += "{ ";
Steve Naroff003d00e2008-12-02 16:05:55 +0000737 // Synthesize an explicit cast to initialize the ivar.
Mike Stump11289f42009-09-09 15:08:12 +0000738 // FIXME: deal with code generation implications for various property
739 // attributes (copy, retain, nonatomic).
Steve Narofff326f402008-12-03 00:56:33 +0000740 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroff003d00e2008-12-02 16:05:55 +0000741 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000742 Setr += PD->getNameAsCString();
Steve Naroff003d00e2008-12-02 16:05:55 +0000743 Setr += "; }";
Steve Naroff9af94912008-12-02 15:48:25 +0000744 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffe1908e32008-12-01 20:33:01 +0000745}
Chris Lattner16a0de42007-10-11 18:38:32 +0000746
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000747void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattner3c799d72007-10-24 17:06:59 +0000748 // Get the start location and compute the semi location.
749 SourceLocation startLoc = ClassDecl->getLocation();
750 const char *startBuf = SM->getCharacterData(startLoc);
751 const char *semiPtr = strchr(startBuf, ';');
Mike Stump11289f42009-09-09 15:08:12 +0000752
Chris Lattner3c799d72007-10-24 17:06:59 +0000753 // Translate to typedef's that forward reference structs with the same name
754 // as the class. As a convenience, we include the original declaration
755 // as a comment.
756 std::string typedefString;
757 typedefString += "// ";
Steve Naroff574440f2007-10-24 22:48:43 +0000758 typedefString.append(startBuf, semiPtr-startBuf+1);
759 typedefString += "\n";
Chris Lattner9ee23b72009-02-20 18:04:31 +0000760 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
761 I != E; ++I) {
Ted Kremenek9b124e12009-11-18 00:28:11 +0000762 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff1b232132007-11-09 12:50:28 +0000763 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000764 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000765 typedefString += "\n";
766 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000767 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000768 typedefString += "\n";
Steve Naroff98eb8d12007-11-05 14:36:37 +0000769 typedefString += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000770 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000771 typedefString += ";\n#endif\n";
Steve Naroff574440f2007-10-24 22:48:43 +0000772 }
Mike Stump11289f42009-09-09 15:08:12 +0000773
Steve Naroff574440f2007-10-24 22:48:43 +0000774 // Replace the @class with typedefs corresponding to the classes.
Mike Stump11289f42009-09-09 15:08:12 +0000775 ReplaceText(startLoc, semiPtr-startBuf+1,
Chris Lattner9cc55f52008-01-31 19:51:04 +0000776 typedefString.c_str(), typedefString.size());
Chris Lattner3c799d72007-10-24 17:06:59 +0000777}
778
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000779void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff3ce37a62007-12-14 23:37:57 +0000780 SourceLocation LocStart = Method->getLocStart();
781 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000782
Chris Lattner88ea93e2009-02-04 01:06:56 +0000783 if (SM->getInstantiationLineNumber(LocEnd) >
784 SM->getInstantiationLineNumber(LocStart)) {
Steve Naroffe020fa12008-10-21 13:37:27 +0000785 InsertText(LocStart, "#if 0\n", 6);
786 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff3ce37a62007-12-14 23:37:57 +0000787 } else {
Chris Lattner1780a852008-01-31 19:42:41 +0000788 InsertText(LocStart, "// ", 3);
Steve Naroff5448cf62007-10-30 13:30:57 +0000789 }
790}
791
Mike Stump11289f42009-09-09 15:08:12 +0000792void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000793 SourceLocation Loc = prop->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000794
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000795 ReplaceText(Loc, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000796
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000797 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahaniane8a30162007-11-07 00:09:37 +0000798}
799
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000800void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000801 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000802
Steve Naroff5448cf62007-10-30 13:30:57 +0000803 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000804 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000805
806 for (ObjCCategoryDecl::instmeth_iterator
807 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000808 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000809 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +0000810 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000811 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000812 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000813 RewriteMethodDeclaration(*I);
814
Steve Naroff5448cf62007-10-30 13:30:57 +0000815 // Lastly, comment out the @end.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000816 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff5448cf62007-10-30 13:30:57 +0000817}
818
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000819void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000820 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Mike Stump11289f42009-09-09 15:08:12 +0000821
Steve Narofff921385f2007-10-30 16:42:30 +0000822 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000823
Steve Narofff921385f2007-10-30 16:42:30 +0000824 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000825 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000826
827 for (ObjCProtocolDecl::instmeth_iterator
828 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000829 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000830 RewriteMethodDeclaration(*I);
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000831 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000832 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000833 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000834 RewriteMethodDeclaration(*I);
835
Steve Narofff921385f2007-10-30 16:42:30 +0000836 // Lastly, comment out the @end.
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000837 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattner9cc55f52008-01-31 19:51:04 +0000838 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroffa509f042007-11-14 15:03:57 +0000839
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000840 // Must comment out @optional/@required
841 const char *startBuf = SM->getCharacterData(LocStart);
842 const char *endBuf = SM->getCharacterData(LocEnd);
843 for (const char *p = startBuf; p < endBuf; p++) {
844 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
845 std::string CommentedOptional = "/* @optional */";
Steve Naroffa509f042007-11-14 15:03:57 +0000846 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000847 ReplaceText(OptionalLoc, strlen("@optional"),
848 CommentedOptional.c_str(), CommentedOptional.size());
Mike Stump11289f42009-09-09 15:08:12 +0000849
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000850 }
851 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
852 std::string CommentedRequired = "/* @required */";
Steve Naroffa509f042007-11-14 15:03:57 +0000853 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000854 ReplaceText(OptionalLoc, strlen("@required"),
855 CommentedRequired.c_str(), CommentedRequired.size());
Mike Stump11289f42009-09-09 15:08:12 +0000856
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000857 }
858 }
Steve Narofff921385f2007-10-30 16:42:30 +0000859}
860
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000861void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000862 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffc17b0562007-11-14 03:37:28 +0000863 if (LocStart.isInvalid())
864 assert(false && "Invalid SourceLocation");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000865 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000866 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000867}
868
Mike Stump11289f42009-09-09 15:08:12 +0000869void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000870 std::string &ResultStr) {
Steve Naroff295570a2008-10-30 12:09:33 +0000871 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroffb067bbd2008-07-16 14:40:40 +0000872 const FunctionType *FPRetType = 0;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000873 ResultStr += "\nstatic ";
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000874 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +0000875 ResultStr += "id";
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000876 else if (OMD->getResultType()->isFunctionPointerType() ||
877 OMD->getResultType()->isBlockPointerType()) {
Steve Naroffb067bbd2008-07-16 14:40:40 +0000878 // needs special handling, since pointer-to-functions have special
879 // syntax (where a decaration models use).
880 QualType retType = OMD->getResultType();
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000881 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000882 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000883 PointeeTy = PT->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000884 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000885 PointeeTy = BPT->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +0000886 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000887 ResultStr += FPRetType->getResultType().getAsString();
888 ResultStr += "(*";
Steve Naroffb067bbd2008-07-16 14:40:40 +0000889 }
890 } else
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +0000891 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian7262fca2008-01-10 01:39:52 +0000892 ResultStr += " ";
Mike Stump11289f42009-09-09 15:08:12 +0000893
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000894 // Unique method name
Fariborz Jahanian56338352007-11-13 21:02:00 +0000895 std::string NameStr;
Mike Stump11289f42009-09-09 15:08:12 +0000896
Douglas Gregorffca3a22009-01-09 17:18:27 +0000897 if (OMD->isInstanceMethod())
Fariborz Jahanian56338352007-11-13 21:02:00 +0000898 NameStr += "_I_";
899 else
900 NameStr += "_C_";
Mike Stump11289f42009-09-09 15:08:12 +0000901
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000902 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +0000903 NameStr += "_";
Mike Stump11289f42009-09-09 15:08:12 +0000904
905 if (ObjCCategoryImplDecl *CID =
Steve Naroff11b387f2009-01-08 19:41:02 +0000906 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000907 NameStr += CID->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +0000908 NameStr += "_";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000909 }
Mike Stump11289f42009-09-09 15:08:12 +0000910 // Append selector names, replacing ':' with '_'
Chris Lattnere4b95692008-11-24 03:33:13 +0000911 {
912 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000913 int len = selString.size();
914 for (int i = 0; i < len; i++)
915 if (selString[i] == ':')
916 selString[i] = '_';
Fariborz Jahanian56338352007-11-13 21:02:00 +0000917 NameStr += selString;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000918 }
Fariborz Jahanian56338352007-11-13 21:02:00 +0000919 // Remember this name for metadata emission
920 MethodInternalNames[OMD] = NameStr;
921 ResultStr += NameStr;
Mike Stump11289f42009-09-09 15:08:12 +0000922
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000923 // Rewrite arguments
924 ResultStr += "(";
Mike Stump11289f42009-09-09 15:08:12 +0000925
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000926 // invisible arguments
Douglas Gregorffca3a22009-01-09 17:18:27 +0000927 if (OMD->isInstanceMethod()) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000928 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000929 selfTy = Context->getPointerType(selfTy);
Steve Naroffdc5b6b22008-03-12 00:25:36 +0000930 if (!LangOpts.Microsoft) {
931 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
932 ResultStr += "struct ";
933 }
934 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000935 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +0000936 ResultStr += " *";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000937 }
938 else
Steve Naroffd9803712009-04-29 16:37:50 +0000939 ResultStr += Context->getObjCClassType().getAsString();
Mike Stump11289f42009-09-09 15:08:12 +0000940
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000941 ResultStr += " self, ";
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000942 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000943 ResultStr += " _cmd";
Mike Stump11289f42009-09-09 15:08:12 +0000944
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000945 // Method arguments.
Chris Lattnera4997152009-02-20 18:43:26 +0000946 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
947 E = OMD->param_end(); PI != E; ++PI) {
948 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000949 ResultStr += ", ";
Steve Naroffdcdcdcd2008-04-18 21:13:19 +0000950 if (PDecl->getType()->isObjCQualifiedIdType()) {
951 ResultStr += "id ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000952 ResultStr += PDecl->getNameAsString();
Steve Naroffdcdcdcd2008-04-18 21:13:19 +0000953 } else {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000954 std::string Name = PDecl->getNameAsString();
Steve Naroffa5c0db82008-12-11 21:05:33 +0000955 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroff44df6a22008-10-30 14:45:29 +0000956 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000957 const BlockPointerType *BPT = PDecl->getType()->getAs<BlockPointerType>();
Douglas Gregor7de59662009-05-29 20:38:28 +0000958 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name,
959 Context->PrintingPolicy);
Steve Naroff44df6a22008-10-30 14:45:29 +0000960 } else
Douglas Gregor7de59662009-05-29 20:38:28 +0000961 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroffdcdcdcd2008-04-18 21:13:19 +0000962 ResultStr += Name;
963 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000964 }
Fariborz Jahanianeab81cd2008-01-21 20:14:23 +0000965 if (OMD->isVariadic())
966 ResultStr += ", ...";
Fariborz Jahanian7262fca2008-01-10 01:39:52 +0000967 ResultStr += ") ";
Mike Stump11289f42009-09-09 15:08:12 +0000968
Steve Naroffb067bbd2008-07-16 14:40:40 +0000969 if (FPRetType) {
970 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump11289f42009-09-09 15:08:12 +0000971
Steve Naroffb067bbd2008-07-16 14:40:40 +0000972 // Now, emit the argument types (if any).
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000973 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroffb067bbd2008-07-16 14:40:40 +0000974 ResultStr += "(";
975 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
976 if (i) ResultStr += ", ";
977 std::string ParamStr = FT->getArgType(i).getAsString();
978 ResultStr += ParamStr;
979 }
980 if (FT->isVariadic()) {
981 if (FT->getNumArgs()) ResultStr += ", ";
982 ResultStr += "...";
983 }
984 ResultStr += ")";
985 } else {
986 ResultStr += "()";
987 }
988 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000989}
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000990void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000991 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
992 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump11289f42009-09-09 15:08:12 +0000993
Fariborz Jahanianc54d8462007-11-13 20:04:28 +0000994 if (IMD)
Chris Lattner1780a852008-01-31 19:42:41 +0000995 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanianc54d8462007-11-13 20:04:28 +0000996 else
Chris Lattner1780a852008-01-31 19:42:41 +0000997 InsertText(CID->getLocStart(), "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000998
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000999 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001000 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1001 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001002 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001003 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001004 ObjCMethodDecl *OMD = *I;
1005 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001006 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001007 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redla7b98a72009-04-26 20:35:05 +00001008
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001009 const char *startBuf = SM->getCharacterData(LocStart);
1010 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattner9cc55f52008-01-31 19:51:04 +00001011 ReplaceText(LocStart, endBuf-startBuf,
1012 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001013 }
Mike Stump11289f42009-09-09 15:08:12 +00001014
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001015 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001016 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1017 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001018 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001019 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001020 ObjCMethodDecl *OMD = *I;
1021 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001022 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001023 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +00001024
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001025 const char *startBuf = SM->getCharacterData(LocStart);
1026 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattner9cc55f52008-01-31 19:51:04 +00001027 ReplaceText(LocStart, endBuf-startBuf,
Mike Stump11289f42009-09-09 15:08:12 +00001028 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001029 }
Steve Naroffe1908e32008-12-01 20:33:01 +00001030 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001031 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001032 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001033 I != E; ++I) {
Steve Naroffc038b3a2008-12-02 17:36:43 +00001034 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffe1908e32008-12-01 20:33:01 +00001035 }
1036
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001037 if (IMD)
Chris Lattner1780a852008-01-31 19:42:41 +00001038 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001039 else
Mike Stump11289f42009-09-09 15:08:12 +00001040 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001041}
1042
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001043void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffc5484042007-10-30 02:23:23 +00001044 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001045 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff2f55b982007-11-01 03:35:41 +00001046 // we haven't seen a forward decl - generate a typedef.
Steve Naroff03f27672007-11-14 23:02:56 +00001047 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001048 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001049 ResultStr += "\n";
1050 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001051 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001052 ResultStr += "\n";
Steve Naroffa1e115e2008-03-10 23:16:54 +00001053 ResultStr += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001054 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001055 ResultStr += ";\n#endif\n";
Steve Naroff2f55b982007-11-01 03:35:41 +00001056 // Mark this typedef as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001057 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff2f55b982007-11-01 03:35:41 +00001058 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001059 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump11289f42009-09-09 15:08:12 +00001060
1061 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001062 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff0c0f5ba2009-01-11 01:06:09 +00001063 RewriteProperty(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001064 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001065 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001066 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001067 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001068 for (ObjCInterfaceDecl::classmeth_iterator
1069 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001070 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001071 RewriteMethodDeclaration(*I);
1072
Steve Naroff4cd61ac2007-10-30 03:43:13 +00001073 // Lastly, comment out the @end.
Chris Lattner9cc55f52008-01-31 19:51:04 +00001074 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff161a92b2007-10-26 20:53:56 +00001075}
1076
Steve Naroff08628db2008-12-09 12:56:34 +00001077Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1078 SourceRange SrcRange) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00001079 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1080 // This allows us to reuse all the fun and games in SynthMessageExpr().
1081 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1082 ObjCMessageExpr *MsgExpr;
1083 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1084 llvm::SmallVector<Expr *, 1> ExprVec;
1085 ExprVec.push_back(newStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001086
Steve Naroff1042ff32008-12-08 16:43:47 +00001087 Stmt *Receiver = PropRefExpr->getBase();
1088 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1089 if (PRE && PropGetters[PRE]) {
1090 // This allows us to handle chain/nested property getters.
1091 Receiver = PropGetters[PRE];
1092 }
Mike Stump11289f42009-09-09 15:08:12 +00001093 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1094 PDecl->getSetterName(), PDecl->getType(),
1095 PDecl->getSetterMethodDecl(),
1096 SourceLocation(), SourceLocation(),
Steve Naroff4588d0f2008-12-04 16:24:46 +00001097 &ExprVec[0], 1);
1098 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001099
Steve Naroff4588d0f2008-12-04 16:24:46 +00001100 // Now do the actual rewrite.
Steve Naroff08628db2008-12-09 12:56:34 +00001101 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffdf705772008-12-10 14:53:27 +00001102 //delete BinOp;
Ted Kremenek5a201952009-02-07 01:47:29 +00001103 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1104 // to things that stay around.
1105 Context->Deallocate(MsgExpr);
Steve Naroff4588d0f2008-12-04 16:24:46 +00001106 return ReplacingStmt;
Steve Narofff326f402008-12-03 00:56:33 +00001107}
1108
Steve Naroff4588d0f2008-12-04 16:24:46 +00001109Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Narofff326f402008-12-03 00:56:33 +00001110 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1111 // This allows us to reuse all the fun and games in SynthMessageExpr().
1112 ObjCMessageExpr *MsgExpr;
1113 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
Mike Stump11289f42009-09-09 15:08:12 +00001114
Steve Naroff1042ff32008-12-08 16:43:47 +00001115 Stmt *Receiver = PropRefExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00001116
Steve Naroff1042ff32008-12-08 16:43:47 +00001117 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1118 if (PRE && PropGetters[PRE]) {
1119 // This allows us to handle chain/nested property getters.
1120 Receiver = PropGetters[PRE];
1121 }
Mike Stump11289f42009-09-09 15:08:12 +00001122 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1123 PDecl->getGetterName(), PDecl->getType(),
1124 PDecl->getGetterMethodDecl(),
1125 SourceLocation(), SourceLocation(),
Steve Narofff326f402008-12-03 00:56:33 +00001126 0, 0);
1127
Steve Naroff22216db2008-12-04 23:50:32 +00001128 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001129
1130 if (!PropParentMap)
1131 PropParentMap = new ParentMap(CurrentBody);
1132
1133 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1134 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1135 // We stash away the ReplacingStmt since actually doing the
1136 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1137 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek5a201952009-02-07 01:47:29 +00001138 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1139 // to things that stay around.
1140 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001141 return PropRefExpr; // return the original...
1142 } else {
1143 ReplaceStmt(PropRefExpr, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001144 // delete PropRefExpr; elsewhere...
Ted Kremenek5a201952009-02-07 01:47:29 +00001145 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1146 // to things that stay around.
1147 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001148 return ReplacingStmt;
1149 }
Steve Narofff326f402008-12-03 00:56:33 +00001150}
1151
Mike Stump11289f42009-09-09 15:08:12 +00001152Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001153 SourceLocation OrigStart) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001154 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff677ab3a2008-10-27 17:20:55 +00001155 if (CurMethodDef) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001156 if (const PointerType *pType = IV->getBase()->getType()->getAs<PointerType>()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001157 ObjCInterfaceType *iFaceDecl =
1158 dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroffb1c02372008-05-08 17:52:16 +00001159 // lookup which class implements the instance variable.
1160 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001161 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001162 clsDeclared);
Steve Naroffb1c02372008-05-08 17:52:16 +00001163 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001164
Steve Naroffb1c02372008-05-08 17:52:16 +00001165 // Synthesize an explicit cast to gain access to the ivar.
1166 std::string RecName = clsDeclared->getIdentifier()->getName();
1167 RecName += "_IMPL";
1168 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001169 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001170 SourceLocation(), II);
Steve Naroffb1c02372008-05-08 17:52:16 +00001171 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1172 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Mike Stump11289f42009-09-09 15:08:12 +00001173 CastExpr *castExpr = new (Context) CStyleCastExpr(castT,
Anders Carlssona2615922009-07-31 00:48:10 +00001174 CastExpr::CK_Unknown,
1175 IV->getBase(),
1176 castT,SourceLocation(),
1177 SourceLocation());
Steve Naroffb1c02372008-05-08 17:52:16 +00001178 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001179 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1180 IV->getBase()->getLocEnd(),
1181 castExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001182 if (IV->isFreeIvar() &&
Steve Naroff677ab3a2008-10-27 17:20:55 +00001183 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001184 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1185 IV->getLocation(),
1186 D->getType());
Steve Naroffb1c02372008-05-08 17:52:16 +00001187 ReplaceStmt(IV, ME);
Steve Naroff22216db2008-12-04 23:50:32 +00001188 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb1c02372008-05-08 17:52:16 +00001189 return ME;
Steve Naroff05caa482007-11-15 11:33:00 +00001190 }
Mike Stump11289f42009-09-09 15:08:12 +00001191
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001192 ReplaceStmt(IV->getBase(), PE);
1193 // Cannot delete IV->getBase(), since PE points to it.
1194 // Replace the old base with the cast. This is important when doing
1195 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001196 IV->setBase(PE);
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001197 return IV;
Steve Naroff05caa482007-11-15 11:33:00 +00001198 }
Steve Naroff24840f62008-04-18 21:55:08 +00001199 } else { // we are outside a method.
Steve Naroff29ce4e52008-05-06 23:20:07 +00001200 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump11289f42009-09-09 15:08:12 +00001201
Steve Naroff29ce4e52008-05-06 23:20:07 +00001202 // Explicit ivar refs need to have a cast inserted.
1203 // FIXME: consider sharing some of this code with the code above.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001204 if (const PointerType *pType = IV->getBase()->getType()->getAs<PointerType>()) {
Steve Naroffb1c02372008-05-08 17:52:16 +00001205 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001206 // lookup which class implements the instance variable.
1207 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001208 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001209 clsDeclared);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001210 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001211
Steve Naroff29ce4e52008-05-06 23:20:07 +00001212 // Synthesize an explicit cast to gain access to the ivar.
1213 std::string RecName = clsDeclared->getIdentifier()->getName();
1214 RecName += "_IMPL";
1215 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001216 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001217 SourceLocation(), II);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001218 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1219 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Mike Stump11289f42009-09-09 15:08:12 +00001220 CastExpr *castExpr = new (Context) CStyleCastExpr(castT,
Anders Carlssona2615922009-07-31 00:48:10 +00001221 CastExpr::CK_Unknown,
1222 IV->getBase(),
Ted Kremenek5a201952009-02-07 01:47:29 +00001223 castT, SourceLocation(),
1224 SourceLocation());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001225 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001226 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner34873d22008-05-28 16:38:23 +00001227 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001228 ReplaceStmt(IV->getBase(), PE);
1229 // Cannot delete IV->getBase(), since PE points to it.
1230 // Replace the old base with the cast. This is important when doing
1231 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001232 IV->setBase(PE);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001233 return IV;
1234 }
Steve Naroff05caa482007-11-15 11:33:00 +00001235 }
Steve Naroff24840f62008-04-18 21:55:08 +00001236 return IV;
Steve Narofff60782b2007-11-15 02:58:25 +00001237}
1238
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001239/// SynthCountByEnumWithState - To print:
1240/// ((unsigned int (*)
1241/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001242/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001243/// sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001244/// "countByEnumeratingWithState:objects:count:"),
1245/// &enumState,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001246/// (id *)items, (unsigned int)16)
1247///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001248void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001249 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1250 "id *, unsigned int))(void *)objc_msgSend)";
1251 buf += "\n\t\t";
1252 buf += "((id)l_collection,\n\t\t";
1253 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1254 buf += "\n\t\t";
1255 buf += "&enumState, "
1256 "(id *)items, (unsigned int)16)";
1257}
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001258
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001259/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1260/// statement to exit to its outer synthesized loop.
1261///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001262Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001263 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1264 return S;
1265 // replace break with goto __break_label
1266 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001267
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001268 SourceLocation startLoc = S->getLocStart();
1269 buf = "goto __break_label_";
1270 buf += utostr(ObjCBcLabelNo.back());
Chris Lattner9cc55f52008-01-31 19:51:04 +00001271 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001272
1273 return 0;
1274}
1275
1276/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1277/// statement to continue with its inner synthesized loop.
1278///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001279Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001280 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1281 return S;
1282 // replace continue with goto __continue_label
1283 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001284
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001285 SourceLocation startLoc = S->getLocStart();
1286 buf = "goto __continue_label_";
1287 buf += utostr(ObjCBcLabelNo.back());
Chris Lattner9cc55f52008-01-31 19:51:04 +00001288 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001289
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001290 return 0;
1291}
1292
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001293/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001294/// It rewrites:
1295/// for ( type elem in collection) { stmts; }
Mike Stump11289f42009-09-09 15:08:12 +00001296
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001297/// Into:
1298/// {
Mike Stump11289f42009-09-09 15:08:12 +00001299/// type elem;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001300/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001301/// id items[16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001302/// id l_collection = (id)collection;
Mike Stump11289f42009-09-09 15:08:12 +00001303/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001304/// objects:items count:16];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001305/// if (limit) {
1306/// unsigned long startMutations = *enumState.mutationsPtr;
1307/// do {
1308/// unsigned long counter = 0;
1309/// do {
Mike Stump11289f42009-09-09 15:08:12 +00001310/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001311/// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001312/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001313/// stmts;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001314/// __continue_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001315/// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001316/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001317/// objects:items count:16]);
1318/// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001319/// __break_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001320/// }
1321/// else
1322/// elem = nil;
1323/// }
1324///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001325Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattnera779d692008-01-31 05:10:40 +00001326 SourceLocation OrigEnd) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001327 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001328 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001329 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump11289f42009-09-09 15:08:12 +00001330 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001331 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001332
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001333 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001334 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001335 const char *elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001336 std::string elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001337 std::string buf;
1338 buf = "\n{\n\t";
1339 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1340 // type elem;
Chris Lattner529efc72009-03-28 06:33:19 +00001341 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek292b3842008-10-06 22:16:13 +00001342 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001343 if (ElementType->isObjCQualifiedIdType() ||
1344 ElementType->isObjCQualifiedInterfaceType())
1345 // Simply use 'id' for all qualified types.
1346 elementTypeAsString = "id";
1347 else
1348 elementTypeAsString = ElementType.getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001349 buf += elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001350 buf += " ";
Chris Lattner86d7d912008-11-24 03:54:41 +00001351 elementName = D->getNameAsCString();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001352 buf += elementName;
1353 buf += ";\n\t";
1354 }
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001355 else {
1356 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner86d7d912008-11-24 03:54:41 +00001357 elementName = DR->getDecl()->getNameAsCString();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001358 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1359 if (VD->getType()->isObjCQualifiedIdType() ||
1360 VD->getType()->isObjCQualifiedInterfaceType())
1361 // Simply use 'id' for all qualified types.
1362 elementTypeAsString = "id";
1363 else
1364 elementTypeAsString = VD->getType().getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001365 }
Mike Stump11289f42009-09-09 15:08:12 +00001366
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001367 // struct __objcFastEnumerationState enumState = { 0 };
1368 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1369 // id items[16];
1370 buf += "id items[16];\n\t";
1371 // id l_collection = (id)
1372 buf += "id l_collection = (id)";
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001373 // Find start location of 'collection' the hard way!
1374 const char *startCollectionBuf = startBuf;
1375 startCollectionBuf += 3; // skip 'for'
1376 startCollectionBuf = strchr(startCollectionBuf, '(');
1377 startCollectionBuf++; // skip '('
1378 // find 'in' and skip it.
1379 while (*startCollectionBuf != ' ' ||
1380 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1381 (*(startCollectionBuf+3) != ' ' &&
1382 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1383 startCollectionBuf++;
1384 startCollectionBuf += 3;
Mike Stump11289f42009-09-09 15:08:12 +00001385
1386 // Replace: "for (type element in" with string constructed thus far.
Chris Lattner9cc55f52008-01-31 19:51:04 +00001387 ReplaceText(startLoc, startCollectionBuf - startBuf,
1388 buf.c_str(), buf.size());
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001389 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001390 SourceLocation rightParenLoc = S->getRParenLoc();
1391 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1392 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001393 buf = ";\n\t";
Mike Stump11289f42009-09-09 15:08:12 +00001394
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001395 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1396 // objects:items count:16];
1397 // which is synthesized into:
Mike Stump11289f42009-09-09 15:08:12 +00001398 // unsigned int limit =
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001399 // ((unsigned int (*)
1400 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001401 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001402 // sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001403 // "countByEnumeratingWithState:objects:count:"),
1404 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001405 // (id *)items, (unsigned int)16);
1406 buf += "unsigned long limit =\n\t\t";
1407 SynthCountByEnumWithState(buf);
1408 buf += ";\n\t";
1409 /// if (limit) {
1410 /// unsigned long startMutations = *enumState.mutationsPtr;
1411 /// do {
1412 /// unsigned long counter = 0;
1413 /// do {
Mike Stump11289f42009-09-09 15:08:12 +00001414 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001415 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001416 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001417 buf += "if (limit) {\n\t";
1418 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1419 buf += "do {\n\t\t";
1420 buf += "unsigned long counter = 0;\n\t\t";
1421 buf += "do {\n\t\t\t";
1422 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1423 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1424 buf += elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001425 buf += " = (";
1426 buf += elementTypeAsString;
1427 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001428 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattner9cc55f52008-01-31 19:51:04 +00001429 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001430
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001431 /// __continue_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001432 /// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001433 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001434 /// objects:items count:16]);
1435 /// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001436 /// __break_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001437 /// }
1438 /// else
1439 /// elem = nil;
1440 /// }
Mike Stump11289f42009-09-09 15:08:12 +00001441 ///
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001442 buf = ";\n\t";
1443 buf += "__continue_label_";
1444 buf += utostr(ObjCBcLabelNo.back());
1445 buf += ": ;";
1446 buf += "\n\t\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001447 buf += "} while (counter < limit);\n\t";
1448 buf += "} while (limit = ";
1449 SynthCountByEnumWithState(buf);
1450 buf += ");\n\t";
1451 buf += elementName;
Steve Naroffd1a36792008-12-17 14:24:39 +00001452 buf += " = ((id)0);\n\t";
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001453 buf += "__break_label_";
1454 buf += utostr(ObjCBcLabelNo.back());
1455 buf += ": ;\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001456 buf += "}\n\t";
1457 buf += "else\n\t\t";
1458 buf += elementName;
Steve Naroffd1a36792008-12-17 14:24:39 +00001459 buf += " = ((id)0);\n";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001460 buf += "}\n";
Mike Stump11289f42009-09-09 15:08:12 +00001461
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001462 // Insert all these *after* the statement body.
Sebastian Redla7b98a72009-04-26 20:35:05 +00001463 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Narofff0ff8792008-07-21 18:26:02 +00001464 if (isa<CompoundStmt>(S->getBody())) {
1465 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1466 InsertText(endBodyLoc, buf.c_str(), buf.size());
1467 } else {
1468 /* Need to treat single statements specially. For example:
1469 *
1470 * for (A *a in b) if (stuff()) break;
1471 * for (A *a in b) xxxyy;
1472 *
1473 * The following code simply scans ahead to the semi to find the actual end.
1474 */
1475 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1476 const char *semiBuf = strchr(stmtBuf, ';');
1477 assert(semiBuf && "Can't find ';'");
1478 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1479 InsertText(endBodyLoc, buf.c_str(), buf.size());
1480 }
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001481 Stmts.pop_back();
1482 ObjCBcLabelNo.pop_back();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001483 return 0;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001484}
1485
Mike Stump11289f42009-09-09 15:08:12 +00001486/// RewriteObjCSynchronizedStmt -
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001487/// This routine rewrites @synchronized(expr) stmt;
1488/// into:
1489/// objc_sync_enter(expr);
1490/// @try stmt @finally { objc_sync_exit(expr); }
1491///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001492Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001493 // Get the start location and compute the semi location.
1494 SourceLocation startLoc = S->getLocStart();
1495 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001496
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001497 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump11289f42009-09-09 15:08:12 +00001498
1499 std::string buf;
Steve Naroffb2fc0522008-08-21 13:03:03 +00001500 buf = "objc_sync_enter((id)";
1501 const char *lparenBuf = startBuf;
1502 while (*lparenBuf != '(') lparenBuf++;
1503 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001504 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1505 // the sync expression is typically a message expression that's already
Steve Naroffad7013b2008-08-19 13:04:19 +00001506 // been rewritten! (which implies the SourceLocation's are invalid).
1507 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001508 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffad7013b2008-08-19 13:04:19 +00001509 while (*endBuf != ')') endBuf--;
1510 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001511 buf = ");\n";
1512 // declare a new scope with two variables, _stack and _rethrow.
1513 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1514 buf += "int buf[18/*32-bit i386*/];\n";
1515 buf += "char *pointers[4];} _stack;\n";
1516 buf += "id volatile _rethrow = 0;\n";
1517 buf += "objc_exception_try_enter(&_stack);\n";
1518 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001519 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001520 startLoc = S->getSynchBody()->getLocEnd();
1521 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001522
Steve Naroffad7013b2008-08-19 13:04:19 +00001523 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001524 SourceLocation lastCurlyLoc = startLoc;
1525 buf = "}\nelse {\n";
1526 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroffd9803712009-04-29 16:37:50 +00001527 buf += "}\n";
1528 buf += "{ /* implicit finally clause */\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001529 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffec60b432009-12-05 21:43:12 +00001530
1531 std::string syncBuf;
1532 syncBuf += " objc_sync_exit(";
Mike Stump11289f42009-09-09 15:08:12 +00001533 Expr *syncExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00001534 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00001535 S->getSynchExpr(),
Ted Kremenek5a201952009-02-07 01:47:29 +00001536 Context->getObjCIdType(),
1537 SourceLocation(),
1538 SourceLocation());
Ted Kremenek2d470fc2008-09-13 05:16:45 +00001539 std::string syncExprBufS;
1540 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00001541 syncExpr->printPretty(syncExprBuf, *Context, 0,
1542 PrintingPolicy(LangOpts));
Steve Naroffec60b432009-12-05 21:43:12 +00001543 syncBuf += syncExprBuf.str();
1544 syncBuf += ");";
1545
1546 buf += syncBuf;
1547 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001548 buf += "}\n";
1549 buf += "}";
Mike Stump11289f42009-09-09 15:08:12 +00001550
Chris Lattner9cc55f52008-01-31 19:51:04 +00001551 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffec60b432009-12-05 21:43:12 +00001552
1553 bool hasReturns = false;
1554 HasReturnStmts(S->getSynchBody(), hasReturns);
1555 if (hasReturns)
1556 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1557
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001558 return 0;
1559}
1560
Steve Naroffec60b432009-12-05 21:43:12 +00001561void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1562{
Steve Naroff6d6da252008-12-05 17:03:39 +00001563 // Perform a bottom up traversal of all children.
1564 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1565 CI != E; ++CI)
1566 if (*CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001567 WarnAboutReturnGotoStmts(*CI);
Steve Naroff6d6da252008-12-05 17:03:39 +00001568
Steve Naroffec60b432009-12-05 21:43:12 +00001569 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump11289f42009-09-09 15:08:12 +00001570 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff6d6da252008-12-05 17:03:39 +00001571 TryFinallyContainsReturnDiag);
1572 }
1573 return;
1574}
1575
Steve Naroffec60b432009-12-05 21:43:12 +00001576void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1577{
1578 // Perform a bottom up traversal of all children.
1579 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1580 CI != E; ++CI)
1581 if (*CI)
1582 HasReturnStmts(*CI, hasReturns);
1583
1584 if (isa<ReturnStmt>(S))
1585 hasReturns = true;
1586 return;
1587}
1588
1589void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1590 // Perform a bottom up traversal of all children.
1591 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1592 CI != E; ++CI)
1593 if (*CI) {
1594 RewriteTryReturnStmts(*CI);
1595 }
1596 if (isa<ReturnStmt>(S)) {
1597 SourceLocation startLoc = S->getLocStart();
1598 const char *startBuf = SM->getCharacterData(startLoc);
1599
1600 const char *semiBuf = strchr(startBuf, ';');
1601 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1602 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1603
1604 std::string buf;
1605 buf = "{ objc_exception_try_exit(&_stack); return";
1606
1607 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1608 InsertText(onePastSemiLoc, "}", 1);
1609 }
1610 return;
1611}
1612
1613void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1614 // Perform a bottom up traversal of all children.
1615 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1616 CI != E; ++CI)
1617 if (*CI) {
1618 RewriteSyncReturnStmts(*CI, syncExitBuf);
1619 }
1620 if (isa<ReturnStmt>(S)) {
1621 SourceLocation startLoc = S->getLocStart();
1622 const char *startBuf = SM->getCharacterData(startLoc);
1623
1624 const char *semiBuf = strchr(startBuf, ';');
1625 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1626 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1627
1628 std::string buf;
1629 buf = "{ objc_exception_try_exit(&_stack);";
1630 buf += syncExitBuf;
1631 buf += " return";
1632
1633 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1634 InsertText(onePastSemiLoc, "}", 1);
1635 }
1636 return;
1637}
1638
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001639Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001640 // Get the start location and compute the semi location.
1641 SourceLocation startLoc = S->getLocStart();
1642 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001643
Steve Naroffbf478ec2007-11-07 04:08:17 +00001644 assert((*startBuf == '@') && "bogus @try location");
1645
1646 std::string buf;
1647 // declare a new scope with two variables, _stack and _rethrow.
1648 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1649 buf += "int buf[18/*32-bit i386*/];\n";
1650 buf += "char *pointers[4];} _stack;\n";
1651 buf += "id volatile _rethrow = 0;\n";
1652 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff16018582007-11-07 18:43:40 +00001653 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffbf478ec2007-11-07 04:08:17 +00001654
Chris Lattner9cc55f52008-01-31 19:51:04 +00001655 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001656
Steve Naroffbf478ec2007-11-07 04:08:17 +00001657 startLoc = S->getTryBody()->getLocEnd();
1658 startBuf = SM->getCharacterData(startLoc);
1659
1660 assert((*startBuf == '}') && "bogus @try block");
Mike Stump11289f42009-09-09 15:08:12 +00001661
Steve Naroffbf478ec2007-11-07 04:08:17 +00001662 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffce2dca12008-07-16 15:31:30 +00001663 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1664 if (catchList) {
1665 startLoc = startLoc.getFileLocWithOffset(1);
1666 buf = " /* @catch begin */ else {\n";
1667 buf += " id _caught = objc_exception_extract(&_stack);\n";
1668 buf += " objc_exception_try_enter (&_stack);\n";
1669 buf += " if (_setjmp(_stack.buf))\n";
1670 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1671 buf += " else { /* @catch continue */";
Mike Stump11289f42009-09-09 15:08:12 +00001672
Steve Naroffce2dca12008-07-16 15:31:30 +00001673 InsertText(startLoc, buf.c_str(), buf.size());
Steve Narofffac18fe2008-09-09 19:59:12 +00001674 } else { /* no catch list */
1675 buf = "}\nelse {\n";
1676 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1677 buf += "}";
1678 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffce2dca12008-07-16 15:31:30 +00001679 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001680 bool sawIdTypedCatch = false;
1681 Stmt *lastCatchBody = 0;
Steve Naroffbf478ec2007-11-07 04:08:17 +00001682 while (catchList) {
Steve Naroff371b8fb2009-03-03 19:52:17 +00001683 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001684
Mike Stump11289f42009-09-09 15:08:12 +00001685 if (catchList == S->getCatchStmts())
Steve Naroffbf478ec2007-11-07 04:08:17 +00001686 buf = "if ("; // we are generating code for the first catch clause
1687 else
1688 buf = "else if (";
1689 startLoc = catchList->getLocStart();
1690 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001691
Steve Naroffbf478ec2007-11-07 04:08:17 +00001692 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump11289f42009-09-09 15:08:12 +00001693
Steve Naroffbf478ec2007-11-07 04:08:17 +00001694 const char *lParenLoc = strchr(startBuf, '(');
1695
Steve Naroffe6b7ffd2008-02-01 22:08:12 +00001696 if (catchList->hasEllipsis()) {
Steve Naroffedb5bc62008-02-01 20:02:07 +00001697 // Now rewrite the body...
1698 lastCatchBody = catchList->getCatchBody();
Steve Naroffedb5bc62008-02-01 20:02:07 +00001699 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1700 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001701 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1702 "bogus @catch paren location");
Steve Naroffedb5bc62008-02-01 20:02:07 +00001703 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001704
Steve Naroffedb5bc62008-02-01 20:02:07 +00001705 buf += "1) { id _tmp = _caught;";
Daniel Dunbardec484a2009-08-19 19:10:30 +00001706 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff371b8fb2009-03-03 19:52:17 +00001707 } else if (catchDecl) {
1708 QualType t = catchDecl->getType();
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001709 if (t == Context->getObjCIdType()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001710 buf += "1) { ";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001711 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001712 sawIdTypedCatch = true;
Mike Stump11289f42009-09-09 15:08:12 +00001713 } else if (const PointerType *pType = t->getAs<PointerType>()) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001714 ObjCInterfaceType *cls; // Should be a pointer to a class.
Mike Stump11289f42009-09-09 15:08:12 +00001715
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001716 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001717 if (cls) {
Steve Naroff16018582007-11-07 18:43:40 +00001718 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001719 buf += cls->getDecl()->getNameAsString();
Steve Naroff16018582007-11-07 18:43:40 +00001720 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001721 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001722 }
1723 }
1724 // Now rewrite the body...
1725 lastCatchBody = catchList->getCatchBody();
1726 SourceLocation rParenLoc = catchList->getRParenLoc();
1727 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1728 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1729 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1730 assert((*rParenBuf == ')') && "bogus @catch paren location");
1731 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001732
Steve Naroffbf478ec2007-11-07 04:08:17 +00001733 buf = " = _caught;";
Mike Stump11289f42009-09-09 15:08:12 +00001734 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroffbf478ec2007-11-07 04:08:17 +00001735 // declares the @catch parameter).
Chris Lattner9cc55f52008-01-31 19:51:04 +00001736 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff371b8fb2009-03-03 19:52:17 +00001737 } else {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001738 assert(false && "@catch rewrite bug");
Steve Naroffa733c7f2007-11-07 15:32:26 +00001739 }
Steve Naroffedb5bc62008-02-01 20:02:07 +00001740 // make sure all the catch bodies get rewritten!
Steve Naroffbf478ec2007-11-07 04:08:17 +00001741 catchList = catchList->getNextCatchStmt();
1742 }
1743 // Complete the catch list...
1744 if (lastCatchBody) {
1745 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001746 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1747 "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001748
Steve Naroff4adbe312008-09-11 15:29:03 +00001749 // Insert the last (implicit) else clause *before* the right curly brace.
1750 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1751 buf = "} /* last catch end */\n";
1752 buf += "else {\n";
1753 buf += " _rethrow = _caught;\n";
1754 buf += " objc_exception_try_exit(&_stack);\n";
1755 buf += "} } /* @catch end */\n";
1756 if (!S->getFinallyStmt())
1757 buf += "}\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001758 InsertText(bodyLoc, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001759
Steve Naroffbf478ec2007-11-07 04:08:17 +00001760 // Set lastCurlyLoc
1761 lastCurlyLoc = lastCatchBody->getLocEnd();
1762 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001763 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001764 startLoc = finalStmt->getLocStart();
1765 startBuf = SM->getCharacterData(startLoc);
1766 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump11289f42009-09-09 15:08:12 +00001767
Steve Naroffbf478ec2007-11-07 04:08:17 +00001768 buf = "/* @finally */";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001769 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001770
Steve Naroffbf478ec2007-11-07 04:08:17 +00001771 Stmt *body = finalStmt->getFinallyBody();
1772 SourceLocation startLoc = body->getLocStart();
1773 SourceLocation endLoc = body->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001774 assert(*SM->getCharacterData(startLoc) == '{' &&
1775 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001776 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001777 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001778
Steve Naroffbf478ec2007-11-07 04:08:17 +00001779 startLoc = startLoc.getFileLocWithOffset(1);
1780 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001781 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001782 endLoc = endLoc.getFileLocWithOffset(-1);
1783 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001784 InsertText(endLoc, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001785
Steve Naroffbf478ec2007-11-07 04:08:17 +00001786 // Set lastCurlyLoc
1787 lastCurlyLoc = body->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00001788
Steve Naroff6d6da252008-12-05 17:03:39 +00001789 // Now check for any return/continue/go statements within the @try.
Steve Naroffec60b432009-12-05 21:43:12 +00001790 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff4adbe312008-09-11 15:29:03 +00001791 } else { /* no finally clause - make sure we synthesize an implicit one */
1792 buf = "{ /* implicit finally clause */\n";
1793 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1794 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1795 buf += "}";
1796 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffec60b432009-12-05 21:43:12 +00001797
1798 // Now check for any return/continue/go statements within the @try.
1799 // The implicit finally clause won't called if the @try contains any
1800 // jump statements.
1801 bool hasReturns = false;
1802 HasReturnStmts(S->getTryBody(), hasReturns);
1803 if (hasReturns)
1804 RewriteTryReturnStmts(S->getTryBody());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001805 }
1806 // Now emit the final closing curly brace...
1807 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1808 buf = " } /* @try scope end */\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001809 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001810 return 0;
1811}
1812
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001813Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001814 return 0;
1815}
1816
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001817Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001818 return 0;
1819}
1820
Mike Stump11289f42009-09-09 15:08:12 +00001821// This can't be done with ReplaceStmt(S, ThrowExpr), since
1822// the throw expression is typically a message expression that's already
Steve Naroffa733c7f2007-11-07 15:32:26 +00001823// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001824Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroffa733c7f2007-11-07 15:32:26 +00001825 // Get the start location and compute the semi location.
1826 SourceLocation startLoc = S->getLocStart();
1827 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001828
Steve Naroffa733c7f2007-11-07 15:32:26 +00001829 assert((*startBuf == '@') && "bogus @throw location");
1830
1831 std::string buf;
1832 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffc7d2df22008-01-19 00:42:38 +00001833 if (S->getThrowExpr())
1834 buf = "objc_exception_throw(";
1835 else // add an implicit argument
1836 buf = "objc_exception_throw(_caught";
Mike Stump11289f42009-09-09 15:08:12 +00001837
Steve Naroff29788342008-07-25 15:41:30 +00001838 // handle "@ throw" correctly.
1839 const char *wBuf = strchr(startBuf, 'w');
1840 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1841 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001842
Steve Naroffa733c7f2007-11-07 15:32:26 +00001843 const char *semiBuf = strchr(startBuf, ';');
1844 assert((*semiBuf == ';') && "@throw: can't find ';'");
1845 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1846 buf = ");";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001847 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroffa733c7f2007-11-07 15:32:26 +00001848 return 0;
1849}
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001850
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001851Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerc6d91c02007-10-17 22:35:30 +00001852 // Create a new string expression.
1853 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlssond8499822007-10-29 05:01:08 +00001854 std::string StrEncoding;
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00001855 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00001856 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
1857 StrEncoding.length(), false,StrType,
1858 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00001859 ReplaceStmt(Exp, Replacement);
Mike Stump11289f42009-09-09 15:08:12 +00001860
Chris Lattner4431a1b2007-11-30 22:53:43 +00001861 // Replace this subexpr in the parent.
Steve Naroff22216db2008-12-04 23:50:32 +00001862 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattner69534692007-10-24 16:57:36 +00001863 return Replacement;
Chris Lattnera7c19fe2007-10-16 22:36:42 +00001864}
1865
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001866Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff2654e182008-12-22 22:16:07 +00001867 if (!SelGetUidFunctionDecl)
1868 SynthSelGetUidFunctionDecl();
Steve Naroffe4f9b232007-11-05 14:50:49 +00001869 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1870 // Create a call to sel_registerName("selName").
1871 llvm::SmallVector<Expr*, 8> SelExprs;
1872 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00001873 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00001874 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00001875 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00001876 false, argType, SourceLocation()));
Steve Naroffe4f9b232007-11-05 14:50:49 +00001877 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1878 &SelExprs[0], SelExprs.size());
Chris Lattner2e0d2602008-01-31 19:37:57 +00001879 ReplaceStmt(Exp, SelExp);
Steve Naroff22216db2008-12-04 23:50:32 +00001880 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffe4f9b232007-11-05 14:50:49 +00001881 return SelExp;
1882}
1883
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001884CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff574440f2007-10-24 22:48:43 +00001885 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001886 // Get the type, we will need to reference it in a couple spots.
Steve Naroff574440f2007-10-24 22:48:43 +00001887 QualType msgSendType = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001888
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001889 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek5a201952009-02-07 01:47:29 +00001890 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001891
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001892 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattner3c799d72007-10-24 17:06:59 +00001893 QualType pToFunc = Context->getPointerType(msgSendType);
Mike Stump11289f42009-09-09 15:08:12 +00001894 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc,
Anders Carlssona2615922009-07-31 00:48:10 +00001895 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00001896 DRE,
Douglas Gregora11693b2008-11-12 17:17:38 +00001897 /*isLvalue=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001898
John McCall9dd450b2009-09-21 23:43:11 +00001899 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00001900
Ted Kremenekd7b4f402009-02-09 20:51:47 +00001901 return new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
1902 SourceLocation());
Steve Naroff574440f2007-10-24 22:48:43 +00001903}
1904
Steve Naroff50d42052007-11-01 13:24:47 +00001905static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1906 const char *&startRef, const char *&endRef) {
1907 while (startBuf < endBuf) {
1908 if (*startBuf == '<')
1909 startRef = startBuf; // mark the start.
1910 if (*startBuf == '>') {
Steve Naroff1b232132007-11-09 12:50:28 +00001911 if (startRef && *startRef == '<') {
1912 endRef = startBuf; // mark the end.
1913 return true;
1914 }
1915 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00001916 }
1917 startBuf++;
1918 }
1919 return false;
1920}
1921
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001922static void scanToNextArgument(const char *&argRef) {
1923 int angle = 0;
1924 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1925 if (*argRef == '<')
1926 angle++;
1927 else if (*argRef == '>')
1928 angle--;
1929 argRef++;
1930 }
1931 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1932}
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00001933
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001934bool RewriteObjC::needToScanForQualifiers(QualType T) {
Steve Naroffc277ad12009-07-18 15:33:26 +00001935 return T->isObjCQualifiedIdType() || T->isObjCQualifiedInterfaceType();
Steve Naroff50d42052007-11-01 13:24:47 +00001936}
1937
Steve Naroff873bd842008-07-29 18:15:38 +00001938void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1939 QualType Type = E->getType();
1940 if (needToScanForQualifiers(Type)) {
Steve Naroffdbfc6932008-11-19 21:15:47 +00001941 SourceLocation Loc, EndLoc;
Mike Stump11289f42009-09-09 15:08:12 +00001942
Steve Naroffdbfc6932008-11-19 21:15:47 +00001943 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1944 Loc = ECE->getLParenLoc();
1945 EndLoc = ECE->getRParenLoc();
1946 } else {
1947 Loc = E->getLocStart();
1948 EndLoc = E->getLocEnd();
1949 }
1950 // This will defend against trying to rewrite synthesized expressions.
1951 if (Loc.isInvalid() || EndLoc.isInvalid())
1952 return;
1953
Steve Naroff873bd842008-07-29 18:15:38 +00001954 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffdbfc6932008-11-19 21:15:47 +00001955 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff873bd842008-07-29 18:15:38 +00001956 const char *startRef = 0, *endRef = 0;
1957 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1958 // Get the locations of the startRef, endRef.
1959 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1960 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1961 // Comment out the protocol references.
1962 InsertText(LessLoc, "/*", 2);
1963 InsertText(GreaterLoc, "*/", 2);
1964 }
1965 }
1966}
1967
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001968void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001969 SourceLocation Loc;
1970 QualType Type;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001971 const FunctionProtoType *proto = 0;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001972 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1973 Loc = VD->getLocation();
1974 Type = VD->getType();
1975 }
1976 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1977 Loc = FD->getLocation();
1978 // Check for ObjC 'id' and class types that have been adorned with protocol
1979 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall9dd450b2009-09-21 23:43:11 +00001980 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001981 assert(funcType && "missing function type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001982 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001983 if (!proto)
1984 return;
1985 Type = proto->getResultType();
1986 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00001987 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
1988 Loc = FD->getLocation();
1989 Type = FD->getType();
1990 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001991 else
1992 return;
Mike Stump11289f42009-09-09 15:08:12 +00001993
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001994 if (needToScanForQualifiers(Type)) {
Steve Naroff50d42052007-11-01 13:24:47 +00001995 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00001996
Steve Naroff50d42052007-11-01 13:24:47 +00001997 const char *endBuf = SM->getCharacterData(Loc);
1998 const char *startBuf = endBuf;
Steve Naroff930e0992008-05-31 05:02:17 +00001999 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroff50d42052007-11-01 13:24:47 +00002000 startBuf--; // scan backward (from the decl location) for return type.
2001 const char *startRef = 0, *endRef = 0;
2002 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2003 // Get the locations of the startRef, endRef.
2004 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2005 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2006 // Comment out the protocol references.
Chris Lattner1780a852008-01-31 19:42:41 +00002007 InsertText(LessLoc, "/*", 2);
2008 InsertText(GreaterLoc, "*/", 2);
Steve Naroff37e011c2007-10-31 04:38:33 +00002009 }
2010 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002011 if (!proto)
2012 return; // most likely, was a variable
Steve Naroff50d42052007-11-01 13:24:47 +00002013 // Now check arguments.
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002014 const char *startBuf = SM->getCharacterData(Loc);
2015 const char *startFuncBuf = startBuf;
Steve Naroff50d42052007-11-01 13:24:47 +00002016 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2017 if (needToScanForQualifiers(proto->getArgType(i))) {
2018 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002019
Steve Naroff50d42052007-11-01 13:24:47 +00002020 const char *endBuf = startBuf;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002021 // scan forward (from the decl location) for argument types.
2022 scanToNextArgument(endBuf);
Steve Naroff50d42052007-11-01 13:24:47 +00002023 const char *startRef = 0, *endRef = 0;
2024 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2025 // Get the locations of the startRef, endRef.
Mike Stump11289f42009-09-09 15:08:12 +00002026 SourceLocation LessLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002027 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump11289f42009-09-09 15:08:12 +00002028 SourceLocation GreaterLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002029 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002030 // Comment out the protocol references.
Chris Lattner1780a852008-01-31 19:42:41 +00002031 InsertText(LessLoc, "/*", 2);
2032 InsertText(GreaterLoc, "*/", 2);
Steve Naroff50d42052007-11-01 13:24:47 +00002033 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002034 startBuf = ++endBuf;
2035 }
2036 else {
Steve Naroffc884aa82008-08-06 15:58:23 +00002037 // If the function name is derived from a macro expansion, then the
2038 // argument buffer will not follow the name. Need to speak with Chris.
2039 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002040 startBuf++; // scan forward (from the decl location) for argument types.
2041 startBuf++;
2042 }
Steve Naroff50d42052007-11-01 13:24:47 +00002043 }
Steve Naroff37e011c2007-10-31 04:38:33 +00002044}
2045
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002046// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002047void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002048 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2049 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002050 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002051 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002052 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002053 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002054 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002055 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002056 SelGetUidIdent, getFuncType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002057 FunctionDecl::Extern, false);
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002058}
2059
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002060void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002061 // declared in <objc/objc.h>
Douglas Gregor1e21c192009-01-09 01:47:02 +00002062 if (FD->getIdentifier() &&
2063 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002064 SelGetUidFunctionDecl = FD;
Steve Naroff37e011c2007-10-31 04:38:33 +00002065 return;
2066 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002067 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002068}
2069
Steve Naroff17978c42008-03-11 17:37:02 +00002070// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002071void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroff17978c42008-03-11 17:37:02 +00002072 if (SuperContructorFunctionDecl)
2073 return;
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002074 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroff17978c42008-03-11 17:37:02 +00002075 llvm::SmallVector<QualType, 16> ArgTys;
2076 QualType argT = Context->getObjCIdType();
2077 assert(!argT.isNull() && "Can't find 'id' type");
2078 ArgTys.push_back(argT);
2079 ArgTys.push_back(argT);
2080 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2081 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002082 false, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002083 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002084 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002085 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002086 FunctionDecl::Extern, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002087}
2088
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002089// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002090void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002091 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2092 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002093 QualType argT = Context->getObjCIdType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002094 assert(!argT.isNull() && "Can't find 'id' type");
2095 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002096 argT = Context->getObjCSelType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002097 assert(!argT.isNull() && "Can't find 'SEL' type");
2098 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002099 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002100 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002101 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002102 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002103 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002104 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002105 FunctionDecl::Extern, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002106}
2107
Steve Naroff7fa2f042007-11-15 10:28:18 +00002108// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002109void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002110 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2111 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002112 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002113 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002114 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002115 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2116 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2117 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002118 argT = Context->getObjCSelType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002119 assert(!argT.isNull() && "Can't find 'SEL' type");
2120 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002121 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff7fa2f042007-11-15 10:28:18 +00002122 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002123 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002124 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002125 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002126 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002127 FunctionDecl::Extern, false);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002128}
2129
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002130// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002131void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002132 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2133 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002134 QualType argT = Context->getObjCIdType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002135 assert(!argT.isNull() && "Can't find 'id' type");
2136 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002137 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002138 assert(!argT.isNull() && "Can't find 'SEL' type");
2139 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002140 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002141 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002142 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002143 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002144 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002145 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002146 FunctionDecl::Extern, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002147}
2148
Mike Stump11289f42009-09-09 15:08:12 +00002149// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002150// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002151void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump11289f42009-09-09 15:08:12 +00002152 IdentifierInfo *msgSendIdent =
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002153 &Context->Idents.get("objc_msgSendSuper_stret");
2154 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002155 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002156 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002157 &Context->Idents.get("objc_super"));
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002158 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2159 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2160 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002161 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002162 assert(!argT.isNull() && "Can't find 'SEL' type");
2163 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002164 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002165 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002166 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002167 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002168 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002169 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002170 FunctionDecl::Extern, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002171}
2172
Steve Naroff2e4e3852008-05-08 22:02:18 +00002173// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002174void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002175 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2176 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002177 QualType argT = Context->getObjCIdType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002178 assert(!argT.isNull() && "Can't find 'id' type");
2179 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002180 argT = Context->getObjCSelType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002181 assert(!argT.isNull() && "Can't find 'SEL' type");
2182 ArgTys.push_back(argT);
Steve Naroff2e4e3852008-05-08 22:02:18 +00002183 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002184 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002185 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002186 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002187 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002188 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002189 FunctionDecl::Extern, false);
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002190}
2191
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002192// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002193void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002194 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2195 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002196 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002197 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002198 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002199 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002200 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002201 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002202 getClassIdent, getClassType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002203 FunctionDecl::Extern, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002204}
2205
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002206// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002207void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002208 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2209 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002210 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002211 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002212 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002213 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002214 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002215 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002216 getClassIdent, getClassType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002217 FunctionDecl::Extern, false);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002218}
2219
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002220Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffce8e8862008-03-15 00:55:56 +00002221 QualType strType = getConstantStringStructType();
2222
2223 std::string S = "__NSConstantStringImpl_";
Steve Naroffa6141f02008-05-31 03:35:42 +00002224
2225 std::string tmpName = InFileName;
2226 unsigned i;
2227 for (i=0; i < tmpName.length(); i++) {
2228 char c = tmpName.at(i);
2229 // replace any non alphanumeric characters with '_'.
2230 if (!isalpha(c) && (c < '0' || c > '9'))
2231 tmpName[i] = '_';
2232 }
2233 S += tmpName;
2234 S += "_";
Steve Naroffce8e8862008-03-15 00:55:56 +00002235 S += utostr(NumObjCStringLiterals++);
2236
Steve Naroff00a31762008-03-27 22:29:16 +00002237 Preamble += "static __NSConstantStringImpl " + S;
2238 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2239 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffce8e8862008-03-15 00:55:56 +00002240 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek2d470fc2008-09-13 05:16:45 +00002241 std::string prettyBufS;
2242 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00002243 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2244 PrintingPolicy(LangOpts));
Steve Naroff00a31762008-03-27 22:29:16 +00002245 Preamble += prettyBuf.str();
2246 Preamble += ",";
Steve Naroff94ed6dc2009-12-06 01:48:44 +00002247 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002248
2249 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2250 &Context->Idents.get(S.c_str()), strType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002251 VarDecl::Static);
Ted Kremenek5a201952009-02-07 01:47:29 +00002252 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2253 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002254 Context->getPointerType(DRE->getType()),
Steve Naroffce8e8862008-03-15 00:55:56 +00002255 SourceLocation());
Steve Naroff265a6b92007-11-08 14:30:50 +00002256 // cast to NSConstantString *
Mike Stump11289f42009-09-09 15:08:12 +00002257 CastExpr *cast = new (Context) CStyleCastExpr(Exp->getType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002258 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002259 Unop, Exp->getType(),
2260 SourceLocation(),
Anders Carlssona2615922009-07-31 00:48:10 +00002261 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002262 ReplaceStmt(Exp, cast);
Steve Naroff22216db2008-12-04 23:50:32 +00002263 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff265a6b92007-11-08 14:30:50 +00002264 return cast;
Steve Naroffa397efd2007-11-03 11:27:19 +00002265}
2266
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002267ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002268 // check if we are sending a message to 'super'
Douglas Gregorffca3a22009-01-09 17:18:27 +00002269 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002270
Douglas Gregor8ea1f532008-11-04 14:56:14 +00002271 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
Mike Stump11289f42009-09-09 15:08:12 +00002272 const ObjCObjectPointerType *OPT =
John McCall9dd450b2009-09-21 23:43:11 +00002273 Super->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00002274 assert(OPT);
2275 const ObjCInterfaceType *IT = OPT->getInterfaceType();
Chris Lattnera9b3cae2008-06-21 18:04:54 +00002276 return IT->getDecl();
2277 }
2278 return 0;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002279}
2280
2281// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002282QualType RewriteObjC::getSuperStructType() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002283 if (!SuperStructDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002284 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002285 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002286 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002287 QualType FieldTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002288
Steve Naroff7fa2f042007-11-15 10:28:18 +00002289 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002290 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002291 // struct objc_class *super;
Mike Stump11289f42009-09-09 15:08:12 +00002292 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor91f84212008-12-11 16:49:14 +00002293
Steve Naroff7fa2f042007-11-15 10:28:18 +00002294 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002295 for (unsigned i = 0; i < 2; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002296 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2297 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002298 FieldTypes[i], 0,
2299 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002300 /*Mutable=*/false));
Douglas Gregor91f84212008-12-11 16:49:14 +00002301 }
Mike Stump11289f42009-09-09 15:08:12 +00002302
Douglas Gregor91f84212008-12-11 16:49:14 +00002303 SuperStructDecl->completeDefinition(*Context);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002304 }
2305 return Context->getTagDeclType(SuperStructDecl);
2306}
2307
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002308QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffce8e8862008-03-15 00:55:56 +00002309 if (!ConstantStringDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002310 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002311 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002312 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffce8e8862008-03-15 00:55:56 +00002313 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002314
Steve Naroffce8e8862008-03-15 00:55:56 +00002315 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002316 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffce8e8862008-03-15 00:55:56 +00002317 // int flags;
Mike Stump11289f42009-09-09 15:08:12 +00002318 FieldTypes[1] = Context->IntTy;
Steve Naroffce8e8862008-03-15 00:55:56 +00002319 // char *str;
Mike Stump11289f42009-09-09 15:08:12 +00002320 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffce8e8862008-03-15 00:55:56 +00002321 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002322 FieldTypes[3] = Context->LongTy;
Douglas Gregor91f84212008-12-11 16:49:14 +00002323
Steve Naroffce8e8862008-03-15 00:55:56 +00002324 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002325 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002326 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2327 ConstantStringDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002328 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002329 FieldTypes[i], 0,
Douglas Gregor91f84212008-12-11 16:49:14 +00002330 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002331 /*Mutable=*/true));
Douglas Gregor91f84212008-12-11 16:49:14 +00002332 }
2333
2334 ConstantStringDecl->completeDefinition(*Context);
Steve Naroffce8e8862008-03-15 00:55:56 +00002335 }
2336 return Context->getTagDeclType(ConstantStringDecl);
2337}
2338
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002339Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002340 if (!SelGetUidFunctionDecl)
2341 SynthSelGetUidFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002342 if (!MsgSendFunctionDecl)
2343 SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002344 if (!MsgSendSuperFunctionDecl)
2345 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002346 if (!MsgSendStretFunctionDecl)
2347 SynthMsgSendStretFunctionDecl();
2348 if (!MsgSendSuperStretFunctionDecl)
2349 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002350 if (!MsgSendFpretFunctionDecl)
2351 SynthMsgSendFpretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002352 if (!GetClassFunctionDecl)
2353 SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002354 if (!GetMetaClassFunctionDecl)
2355 SynthGetMetaClassFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002356
Steve Naroff7fa2f042007-11-15 10:28:18 +00002357 // default to objc_msgSend().
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002358 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2359 // May need to use objc_msgSend_stret() as well.
2360 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroffd9803712009-04-29 16:37:50 +00002361 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2362 QualType resultType = mDecl->getResultType();
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002363 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002364 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002365 else if (resultType->isRealFloatingType())
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002366 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002367 }
Mike Stump11289f42009-09-09 15:08:12 +00002368
Steve Naroff574440f2007-10-24 22:48:43 +00002369 // Synthesize a call to objc_msgSend().
2370 llvm::SmallVector<Expr*, 8> MsgExprs;
2371 IdentifierInfo *clsName = Exp->getClassName();
Mike Stump11289f42009-09-09 15:08:12 +00002372
Steve Naroff574440f2007-10-24 22:48:43 +00002373 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2374 if (clsName) { // class message.
Steve Naroff6c79f972008-07-24 19:44:33 +00002375 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2376 // the 'super' idiom within a class method.
Daniel Dunbar07d07852009-10-18 21:17:35 +00002377 if (clsName->getName() == "super") {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002378 MsgSendFlavor = MsgSendSuperFunctionDecl;
2379 if (MsgSendStretFlavor)
2380 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2381 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002382
2383 ObjCInterfaceDecl *SuperDecl =
Steve Naroff677ab3a2008-10-27 17:20:55 +00002384 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002385
2386 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002387
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002388 // set the receiver to self, the first argument to all methods.
Steve Naroffd9803712009-04-29 16:37:50 +00002389 InitExprs.push_back(
Mike Stump11289f42009-09-09 15:08:12 +00002390 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002391 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002392 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroffd9803712009-04-29 16:37:50 +00002393 Context->getObjCIdType(),
2394 SourceLocation()),
2395 Context->getObjCIdType(),
2396 SourceLocation(), SourceLocation())); // set the 'receiver'.
2397
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002398 llvm::SmallVector<Expr*, 8> ClsExprs;
2399 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002400 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002401 SuperDecl->getIdentifier()->getNameStart(),
2402 SuperDecl->getIdentifier()->getLength(),
2403 false, argType, SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002404 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002405 &ClsExprs[0],
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002406 ClsExprs.size());
2407 // To turn off a warning, type-cast to 'id'
Douglas Gregore200adc2008-10-27 19:41:14 +00002408 InitExprs.push_back( // set 'super class', using objc_getClass().
Mike Stump11289f42009-09-09 15:08:12 +00002409 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002410 CastExpr::CK_Unknown,
Douglas Gregore200adc2008-10-27 19:41:14 +00002411 Cls, Context->getObjCIdType(),
Mike Stump11289f42009-09-09 15:08:12 +00002412 SourceLocation(), SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002413 // struct objc_super
2414 QualType superType = getSuperStructType();
Steve Naroff0b844f02008-03-11 18:14:26 +00002415 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002416
Steve Naroff0b844f02008-03-11 18:14:26 +00002417 if (LangOpts.Microsoft) {
2418 SynthSuperContructorFunctionDecl();
2419 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002420 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff0b844f02008-03-11 18:14:26 +00002421 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002422 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002423 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002424 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002425 // The code for super is a little tricky to prevent collision with
2426 // the structure definition in the header. The rewriter has it's own
2427 // internal definition (__rw_objc_super) that is uses. This is why
2428 // we need the cast below. For example:
2429 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2430 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002431 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002432 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002433 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002434 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
2435 CastExpr::CK_Unknown, SuperRep,
Anders Carlssona2615922009-07-31 00:48:10 +00002436 Context->getPointerType(superType),
Mike Stump11289f42009-09-09 15:08:12 +00002437 SourceLocation(), SourceLocation());
2438 } else {
Steve Naroff0b844f02008-03-11 18:14:26 +00002439 // (struct objc_super) { <exprs from above> }
Mike Stump11289f42009-09-09 15:08:12 +00002440 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2441 &InitExprs[0], InitExprs.size(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002442 SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00002443 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE,
Chris Lattner07d754a2008-10-26 23:43:26 +00002444 false);
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002445 // struct objc_super *
Ted Kremenek5a201952009-02-07 01:47:29 +00002446 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002447 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002448 SourceLocation());
Steve Naroff0b844f02008-03-11 18:14:26 +00002449 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002450 MsgExprs.push_back(SuperRep);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002451 } else {
2452 llvm::SmallVector<Expr*, 8> ClsExprs;
2453 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002454 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002455 clsName->getNameStart(),
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002456 clsName->getLength(),
2457 false, argType,
2458 SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002459 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002460 &ClsExprs[0],
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002461 ClsExprs.size());
2462 MsgExprs.push_back(Cls);
2463 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002464 } else { // instance message.
2465 Expr *recExpr = Exp->getReceiver();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002466
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002467 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002468 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002469 if (MsgSendStretFlavor)
2470 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002471 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002472
Steve Naroff7fa2f042007-11-15 10:28:18 +00002473 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002474
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002475 InitExprs.push_back(
Mike Stump11289f42009-09-09 15:08:12 +00002476 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002477 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002478 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff97adf602008-07-16 22:35:27 +00002479 Context->getObjCIdType(),
Douglas Gregore200adc2008-10-27 19:41:14 +00002480 SourceLocation()),
2481 Context->getObjCIdType(),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002482 SourceLocation(), SourceLocation())); // set the 'receiver'.
Mike Stump11289f42009-09-09 15:08:12 +00002483
Steve Naroff7fa2f042007-11-15 10:28:18 +00002484 llvm::SmallVector<Expr*, 8> ClsExprs;
2485 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002486 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002487 SuperDecl->getIdentifier()->getNameStart(),
2488 SuperDecl->getIdentifier()->getLength(),
2489 false, argType, SourceLocation()));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002490 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002491 &ClsExprs[0],
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002492 ClsExprs.size());
Fariborz Jahaniand5db92b2007-12-05 17:29:46 +00002493 // To turn off a warning, type-cast to 'id'
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002494 InitExprs.push_back(
Douglas Gregore200adc2008-10-27 19:41:14 +00002495 // set 'super class', using objc_getClass().
Mike Stump11289f42009-09-09 15:08:12 +00002496 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002497 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002498 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002499 // struct objc_super
2500 QualType superType = getSuperStructType();
Steve Naroff17978c42008-03-11 17:37:02 +00002501 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002502
Steve Naroff17978c42008-03-11 17:37:02 +00002503 if (LangOpts.Microsoft) {
2504 SynthSuperContructorFunctionDecl();
2505 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002506 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff17978c42008-03-11 17:37:02 +00002507 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002508 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002509 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002510 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002511 // The code for super is a little tricky to prevent collision with
2512 // the structure definition in the header. The rewriter has it's own
2513 // internal definition (__rw_objc_super) that is uses. This is why
2514 // we need the cast below. For example:
2515 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2516 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002517 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002518 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002519 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002520 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Anders Carlssona2615922009-07-31 00:48:10 +00002521 CastExpr::CK_Unknown,
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002522 SuperRep, Context->getPointerType(superType),
Mike Stump11289f42009-09-09 15:08:12 +00002523 SourceLocation(), SourceLocation());
Steve Naroff17978c42008-03-11 17:37:02 +00002524 } else {
2525 // (struct objc_super) { <exprs from above> }
Mike Stump11289f42009-09-09 15:08:12 +00002526 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2527 &InitExprs[0], InitExprs.size(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002528 SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00002529 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002530 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002531 MsgExprs.push_back(SuperRep);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002532 } else {
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002533 // Remove all type-casts because it may contain objc-style types; e.g.
2534 // Foo<Proto> *.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002535 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002536 recExpr = CE->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002537 recExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002538 CastExpr::CK_Unknown, recExpr,
Mike Stump11289f42009-09-09 15:08:12 +00002539 Context->getObjCIdType(),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002540 SourceLocation(), SourceLocation());
Steve Naroff7fa2f042007-11-15 10:28:18 +00002541 MsgExprs.push_back(recExpr);
2542 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002543 }
Steve Naroffa397efd2007-11-03 11:27:19 +00002544 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff574440f2007-10-24 22:48:43 +00002545 llvm::SmallVector<Expr*, 8> SelExprs;
2546 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002547 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002548 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002549 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00002550 false, argType, SourceLocation()));
Steve Naroff574440f2007-10-24 22:48:43 +00002551 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2552 &SelExprs[0], SelExprs.size());
2553 MsgExprs.push_back(SelExp);
Mike Stump11289f42009-09-09 15:08:12 +00002554
Steve Naroff574440f2007-10-24 22:48:43 +00002555 // Now push any user supplied arguments.
2556 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroffe7f18192007-11-14 23:54:14 +00002557 Expr *userExpr = Exp->getArg(i);
Steve Narofff60782b2007-11-15 02:58:25 +00002558 // Make all implicit casts explicit...ICE comes in handy:-)
2559 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2560 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregore200adc2008-10-27 19:41:14 +00002561 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002562 ? Context->getObjCIdType()
Douglas Gregore200adc2008-10-27 19:41:14 +00002563 : ICE->getType();
Anders Carlssona2615922009-07-31 00:48:10 +00002564 userExpr = new (Context) CStyleCastExpr(type, CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002565 userExpr, type, SourceLocation(),
Anders Carlssona2615922009-07-31 00:48:10 +00002566 SourceLocation());
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002567 }
2568 // Make id<P...> cast into an 'id' cast.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002569 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002570 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregorf19b2312008-10-28 15:36:24 +00002571 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002572 userExpr = CE->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002573 userExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002574 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002575 userExpr, Context->getObjCIdType(),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002576 SourceLocation(), SourceLocation());
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002577 }
Mike Stump11289f42009-09-09 15:08:12 +00002578 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002579 MsgExprs.push_back(userExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00002580 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2581 // out the argument in the original expression (since we aren't deleting
2582 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2583 //Exp->setArg(i, 0);
Steve Naroff574440f2007-10-24 22:48:43 +00002584 }
Steve Narofff36987c2007-11-04 22:37:50 +00002585 // Generate the funky cast.
2586 CastExpr *cast;
2587 llvm::SmallVector<QualType, 8> ArgTypes;
2588 QualType returnType;
Mike Stump11289f42009-09-09 15:08:12 +00002589
Steve Narofff36987c2007-11-04 22:37:50 +00002590 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff44864e42007-11-15 10:43:57 +00002591 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2592 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2593 else
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002594 ArgTypes.push_back(Context->getObjCIdType());
2595 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattnera4997152009-02-20 18:43:26 +00002596 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Narofff36987c2007-11-04 22:37:50 +00002597 // Push any user argument types.
Chris Lattnera4997152009-02-20 18:43:26 +00002598 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2599 E = OMD->param_end(); PI != E; ++PI) {
2600 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump11289f42009-09-09 15:08:12 +00002601 ? Context->getObjCIdType()
Chris Lattnera4997152009-02-20 18:43:26 +00002602 : (*PI)->getType();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002603 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00002604 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002605 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002606 t = Context->getPointerType(BPT->getPointeeType());
2607 }
Steve Naroff98eb8d12007-11-05 14:36:37 +00002608 ArgTypes.push_back(t);
2609 }
Chris Lattnera4997152009-02-20 18:43:26 +00002610 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2611 ? Context->getObjCIdType() : OMD->getResultType();
Steve Narofff36987c2007-11-04 22:37:50 +00002612 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002613 returnType = Context->getObjCIdType();
Steve Narofff36987c2007-11-04 22:37:50 +00002614 }
2615 // Get the type, we will need to reference it in a couple spots.
Steve Naroff7fa2f042007-11-15 10:28:18 +00002616 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002617
Steve Narofff36987c2007-11-04 22:37:50 +00002618 // Create a reference to the objc_msgSend() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002619 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002620 SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002621
Mike Stump11289f42009-09-09 15:08:12 +00002622 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Narofff36987c2007-11-04 22:37:50 +00002623 // If we don't do this cast, we get the following bizarre warning/note:
2624 // xx.m:13: warning: function called through a non-compatible type
2625 // xx.m:13: note: if this code is reached, the program will abort
Mike Stump11289f42009-09-09 15:08:12 +00002626 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy),
2627 CastExpr::CK_Unknown, DRE,
Douglas Gregore200adc2008-10-27 19:41:14 +00002628 Context->getPointerType(Context->VoidTy),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002629 SourceLocation(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002630
Steve Narofff36987c2007-11-04 22:37:50 +00002631 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002632 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002633 &ArgTypes[0], ArgTypes.size(),
Steve Naroff327f0f42008-03-18 02:02:04 +00002634 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002635 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Narofff36987c2007-11-04 22:37:50 +00002636 castType = Context->getPointerType(castType);
Mike Stump11289f42009-09-09 15:08:12 +00002637 cast = new (Context) CStyleCastExpr(castType, CastExpr::CK_Unknown, cast,
2638 castType, SourceLocation(),
Anders Carlssona2615922009-07-31 00:48:10 +00002639 SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002640
2641 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00002642 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00002643
John McCall9dd450b2009-09-21 23:43:11 +00002644 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002645 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002646 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002647 FT->getResultType(), SourceLocation());
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002648 Stmt *ReplacingStmt = CE;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002649 if (MsgSendStretFlavor) {
2650 // We have the method which returns a struct/union. Must also generate
2651 // call to objc_msgSend_stret and hang both varieties on a conditional
2652 // expression which dictate which one to envoke depending on size of
2653 // method's return type.
Mike Stump11289f42009-09-09 15:08:12 +00002654
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002655 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002656 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002657 SourceLocation());
2658 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Mike Stump11289f42009-09-09 15:08:12 +00002659 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy),
2660 CastExpr::CK_Unknown, STDRE,
Douglas Gregore200adc2008-10-27 19:41:14 +00002661 Context->getPointerType(Context->VoidTy),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002662 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002663 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002664 castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002665 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002666 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002667 castType = Context->getPointerType(castType);
Anders Carlssona2615922009-07-31 00:48:10 +00002668 cast = new (Context) CStyleCastExpr(castType, CastExpr::CK_Unknown,
2669 cast, castType, SourceLocation(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002670
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002671 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00002672 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00002673
John McCall9dd450b2009-09-21 23:43:11 +00002674 FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002675 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002676 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002677 FT->getResultType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002678
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002679 // Build sizeof(returnType)
Mike Stump11289f42009-09-09 15:08:12 +00002680 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCall4c98fd82009-11-04 07:28:41 +00002681 Context->getTrivialDeclaratorInfo(returnType),
Sebastian Redl6f282892008-11-11 17:56:53 +00002682 Context->getSizeType(),
2683 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002684 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2685 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2686 // For X86 it is more complicated and some kind of target specific routine
2687 // is needed to decide what to do.
Mike Stump11289f42009-09-09 15:08:12 +00002688 unsigned IntSize =
Chris Lattner37e05872008-03-05 18:54:05 +00002689 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Mike Stump11289f42009-09-09 15:08:12 +00002690 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002691 Context->IntTy,
2692 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002693 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
2694 BinaryOperator::LE,
2695 Context->IntTy,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002696 SourceLocation());
2697 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump11289f42009-09-09 15:08:12 +00002698 ConditionalOperator *CondExpr =
Douglas Gregor7e112b02009-08-26 14:37:04 +00002699 new (Context) ConditionalOperator(lessThanExpr,
2700 SourceLocation(), CE,
2701 SourceLocation(), STCE, returnType);
Ted Kremenek5a201952009-02-07 01:47:29 +00002702 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002703 }
Mike Stump11289f42009-09-09 15:08:12 +00002704 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002705 return ReplacingStmt;
2706}
2707
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002708Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002709 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Mike Stump11289f42009-09-09 15:08:12 +00002710
Steve Naroff574440f2007-10-24 22:48:43 +00002711 // Now do the actual rewrite.
Chris Lattner2e0d2602008-01-31 19:37:57 +00002712 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00002713
2714 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002715 return ReplacingStmt;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002716}
2717
Steve Naroffd9803712009-04-29 16:37:50 +00002718// typedef struct objc_object Protocol;
2719QualType RewriteObjC::getProtocolType() {
2720 if (!ProtocolTypeDecl) {
John McCall703a3f82009-10-24 08:00:42 +00002721 DeclaratorInfo *DInfo
2722 = Context->getTrivialDeclaratorInfo(Context->getObjCIdType());
Steve Naroffd9803712009-04-29 16:37:50 +00002723 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002724 SourceLocation(),
Steve Naroffd9803712009-04-29 16:37:50 +00002725 &Context->Idents.get("Protocol"),
John McCall703a3f82009-10-24 08:00:42 +00002726 DInfo);
Steve Naroffd9803712009-04-29 16:37:50 +00002727 }
2728 return Context->getTypeDeclType(ProtocolTypeDecl);
2729}
2730
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00002731/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroffd9803712009-04-29 16:37:50 +00002732/// a synthesized/forward data reference (to the protocol's metadata).
2733/// The forward references (and metadata) are generated in
2734/// RewriteObjC::HandleTranslationUnit().
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002735Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroffd9803712009-04-29 16:37:50 +00002736 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
2737 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump11289f42009-09-09 15:08:12 +00002738 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregored6c7442009-11-23 11:41:28 +00002739 ID, getProtocolType(), 0, VarDecl::Extern);
Steve Naroffd9803712009-04-29 16:37:50 +00002740 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
2741 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
2742 Context->getPointerType(DRE->getType()),
2743 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002744 CastExpr *castExpr = new (Context) CStyleCastExpr(DerefExpr->getType(),
2745 CastExpr::CK_Unknown,
2746 DerefExpr, DerefExpr->getType(),
Steve Naroffd9803712009-04-29 16:37:50 +00002747 SourceLocation(), SourceLocation());
2748 ReplaceStmt(Exp, castExpr);
2749 ProtocolExprDecls.insert(Exp->getProtocol());
Mike Stump11289f42009-09-09 15:08:12 +00002750 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00002751 return castExpr;
Mike Stump11289f42009-09-09 15:08:12 +00002752
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00002753}
2754
Mike Stump11289f42009-09-09 15:08:12 +00002755bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002756 const char *endBuf) {
2757 while (startBuf < endBuf) {
2758 if (*startBuf == '#') {
2759 // Skip whitespace.
2760 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2761 ;
2762 if (!strncmp(startBuf, "if", strlen("if")) ||
2763 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2764 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2765 !strncmp(startBuf, "define", strlen("define")) ||
2766 !strncmp(startBuf, "undef", strlen("undef")) ||
2767 !strncmp(startBuf, "else", strlen("else")) ||
2768 !strncmp(startBuf, "elif", strlen("elif")) ||
2769 !strncmp(startBuf, "endif", strlen("endif")) ||
2770 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2771 !strncmp(startBuf, "include", strlen("include")) ||
2772 !strncmp(startBuf, "import", strlen("import")) ||
2773 !strncmp(startBuf, "include_next", strlen("include_next")))
2774 return true;
2775 }
2776 startBuf++;
2777 }
2778 return false;
2779}
2780
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002781/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002782/// an objective-c class with ivars.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002783void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002784 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002785 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Mike Stump11289f42009-09-09 15:08:12 +00002786 assert(CDecl->getNameAsCString() &&
Douglas Gregor77324f32008-11-17 14:58:09 +00002787 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00002788 // Do not synthesize more than once.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002789 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00002790 return;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002791 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattner8d1c04f2008-03-16 21:08:55 +00002792 int NumIvars = CDecl->ivar_size();
Steve Naroffdde78982007-11-14 19:25:57 +00002793 SourceLocation LocStart = CDecl->getLocStart();
2794 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00002795
Steve Naroffdde78982007-11-14 19:25:57 +00002796 const char *startBuf = SM->getCharacterData(LocStart);
2797 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00002798
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002799 // If no ivars and no root or if its root, directly or indirectly,
2800 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattner8d1c04f2008-03-16 21:08:55 +00002801 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2802 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner184e65d2009-04-14 23:22:57 +00002803 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Chris Lattner9cc55f52008-01-31 19:51:04 +00002804 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002805 return;
2806 }
Mike Stump11289f42009-09-09 15:08:12 +00002807
2808 // FIXME: This has potential of causing problem. If
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002809 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002810 Result += "\nstruct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002811 Result += CDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00002812 if (LangOpts.Microsoft)
2813 Result += "_IMPL";
Steve Naroffdc5b6b22008-03-12 00:25:36 +00002814
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002815 if (NumIvars > 0) {
Steve Naroffdde78982007-11-14 19:25:57 +00002816 const char *cursor = strchr(startBuf, '{');
Mike Stump11289f42009-09-09 15:08:12 +00002817 assert((cursor && endBuf)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002818 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002819 // If the buffer contains preprocessor directives, we do more fine-grained
2820 // rewrites. This is intended to fix code that looks like (which occurs in
2821 // NSURL.h, for example):
2822 //
2823 // #ifdef XYZ
2824 // @interface Foo : NSObject
2825 // #else
2826 // @interface FooBar : NSObject
2827 // #endif
2828 // {
2829 // int i;
2830 // }
2831 // @end
2832 //
2833 // This clause is segregated to avoid breaking the common case.
2834 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump11289f42009-09-09 15:08:12 +00002835 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002836 CDecl->getClassLoc();
2837 const char *endHeader = SM->getCharacterData(L);
Chris Lattner184e65d2009-04-14 23:22:57 +00002838 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002839
Chris Lattnerf5b77512009-02-20 18:18:36 +00002840 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002841 // advance to the end of the referenced protocols.
2842 while (endHeader < cursor && *endHeader != '>') endHeader++;
2843 endHeader++;
2844 }
2845 // rewrite the original header
2846 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2847 } else {
2848 // rewrite the original header *without* disturbing the '{'
Steve Naroffb0e33902009-12-04 21:36:32 +00002849 ReplaceText(LocStart, cursor-startBuf, Result.c_str(), Result.size());
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002850 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002851 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroffdde78982007-11-14 19:25:57 +00002852 Result = "\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002853 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00002854 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002855 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00002856 Result += "_IVARS;\n";
Mike Stump11289f42009-09-09 15:08:12 +00002857
Steve Naroffdde78982007-11-14 19:25:57 +00002858 // insert the super class structure definition.
Chris Lattner1780a852008-01-31 19:42:41 +00002859 SourceLocation OnePastCurly =
2860 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2861 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Naroffdde78982007-11-14 19:25:57 +00002862 }
2863 cursor++; // past '{'
Mike Stump11289f42009-09-09 15:08:12 +00002864
Steve Naroffdde78982007-11-14 19:25:57 +00002865 // Now comment out any visibility specifiers.
2866 while (cursor < endBuf) {
2867 if (*cursor == '@') {
2868 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner174a8252007-11-14 22:57:51 +00002869 // Skip whitespace.
2870 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2871 /*scan*/;
2872
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002873 // FIXME: presence of @public, etc. inside comment results in
2874 // this transformation as well, which is still correct c-code.
Steve Naroffdde78982007-11-14 19:25:57 +00002875 if (!strncmp(cursor, "public", strlen("public")) ||
2876 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffaf91b9a2008-04-04 22:34:24 +00002877 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002878 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattner1780a852008-01-31 19:42:41 +00002879 InsertText(atLoc, "// ", 3);
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002880 }
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002881 // FIXME: If there are cases where '<' is used in ivar declaration part
2882 // of user code, then scan the ivar list and use needToScanForQualifiers
2883 // for type checking.
2884 else if (*cursor == '<') {
2885 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner1780a852008-01-31 19:42:41 +00002886 InsertText(atLoc, "/* ", 3);
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002887 cursor = strchr(cursor, '>');
2888 cursor++;
2889 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner1780a852008-01-31 19:42:41 +00002890 InsertText(atLoc, " */", 3);
Steve Naroff295570a2008-10-30 12:09:33 +00002891 } else if (*cursor == '^') { // rewrite block specifier.
2892 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2893 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002894 }
Steve Naroffdde78982007-11-14 19:25:57 +00002895 cursor++;
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002896 }
Steve Naroffdde78982007-11-14 19:25:57 +00002897 // Don't forget to add a ';'!!
Chris Lattner1780a852008-01-31 19:42:41 +00002898 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Naroffdde78982007-11-14 19:25:57 +00002899 } else { // we don't have any instance variables - insert super struct.
Chris Lattner184e65d2009-04-14 23:22:57 +00002900 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroffdde78982007-11-14 19:25:57 +00002901 Result += " {\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002902 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00002903 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002904 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00002905 Result += "_IVARS;\n};\n";
Chris Lattner9cc55f52008-01-31 19:51:04 +00002906 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002907 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002908 // Mark this struct as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002909 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff13e74872008-05-06 18:26:51 +00002910 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002911}
2912
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002913// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002914/// class methods.
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002915template<typename MethodIterator>
2916void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
2917 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +00002918 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002919 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +00002920 const char *ClassName,
2921 std::string &Result) {
Chris Lattner31bc07e2007-12-12 07:46:12 +00002922 if (MethodBegin == MethodEnd) return;
Mike Stump11289f42009-09-09 15:08:12 +00002923
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00002924 static bool objc_impl_method = false;
Chris Lattner31bc07e2007-12-12 07:46:12 +00002925 if (!objc_impl_method) {
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002926 /* struct _objc_method {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00002927 SEL _cmd;
2928 char *method_types;
2929 void *_imp;
2930 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002931 */
Chris Lattner211f8b82007-10-25 17:07:24 +00002932 Result += "\nstruct _objc_method {\n";
2933 Result += "\tSEL _cmd;\n";
2934 Result += "\tchar *method_types;\n";
2935 Result += "\tvoid *_imp;\n";
2936 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002937
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002938 objc_impl_method = true;
Fariborz Jahanian74a1cfa2007-10-19 00:36:46 +00002939 }
Mike Stump11289f42009-09-09 15:08:12 +00002940
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002941 // Build _objc_method_list for class's methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00002942
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002943 /* struct {
2944 struct _objc_method_list *next_method;
2945 int method_count;
2946 struct _objc_method method_list[];
2947 }
2948 */
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002949 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002950 Result += "\nstatic struct {\n";
2951 Result += "\tstruct _objc_method_list *next_method;\n";
2952 Result += "\tint method_count;\n";
2953 Result += "\tstruct _objc_method method_list[";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002954 Result += utostr(NumMethods);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002955 Result += "];\n} _OBJC_";
Chris Lattner31bc07e2007-12-12 07:46:12 +00002956 Result += prefix;
2957 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2958 Result += "_METHODS_";
2959 Result += ClassName;
Steve Naroffb327e492008-03-12 17:18:30 +00002960 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattner31bc07e2007-12-12 07:46:12 +00002961 Result += IsInstanceMethod ? "inst" : "cls";
2962 Result += "_meth\")))= ";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002963 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00002964
Chris Lattner31bc07e2007-12-12 07:46:12 +00002965 Result += "\t,{{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00002966 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattner31bc07e2007-12-12 07:46:12 +00002967 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002968 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattner31bc07e2007-12-12 07:46:12 +00002969 Result += "\", \"";
2970 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002971 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00002972 Result += MethodInternalNames[*MethodBegin];
2973 Result += "}\n";
2974 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2975 Result += "\t ,{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00002976 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00002977 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002978 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00002979 Result += "\", \"";
2980 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002981 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00002982 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanian56338352007-11-13 21:02:00 +00002983 Result += "}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00002984 }
Chris Lattner31bc07e2007-12-12 07:46:12 +00002985 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002986}
2987
Steve Naroffd9803712009-04-29 16:37:50 +00002988/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner390d39a2008-07-21 21:32:27 +00002989void RewriteObjC::
Steve Naroffd9803712009-04-29 16:37:50 +00002990RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
2991 const char *ClassName, std::string &Result) {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00002992 static bool objc_protocol_methods = false;
Steve Naroffd9803712009-04-29 16:37:50 +00002993
2994 // Output struct protocol_methods holder of method selector and type.
2995 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2996 /* struct protocol_methods {
2997 SEL _cmd;
2998 char *method_types;
2999 }
3000 */
3001 Result += "\nstruct _protocol_methods {\n";
3002 Result += "\tstruct objc_selector *_cmd;\n";
3003 Result += "\tchar *method_types;\n";
3004 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003005
Steve Naroffd9803712009-04-29 16:37:50 +00003006 objc_protocol_methods = true;
3007 }
3008 // Do not synthesize the protocol more than once.
3009 if (ObjCSynthesizedProtocols.count(PDecl))
3010 return;
Mike Stump11289f42009-09-09 15:08:12 +00003011
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003012 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3013 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3014 PDecl->instmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003015 /* struct _objc_protocol_method_list {
3016 int protocol_method_count;
3017 struct protocol_methods protocols[];
3018 }
Steve Naroff251084d2008-03-12 01:06:30 +00003019 */
Steve Naroffd9803712009-04-29 16:37:50 +00003020 Result += "\nstatic struct {\n";
3021 Result += "\tint protocol_method_count;\n";
3022 Result += "\tstruct _protocol_methods protocol_methods[";
3023 Result += utostr(NumMethods);
3024 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3025 Result += PDecl->getNameAsString();
3026 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3027 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003028
Steve Naroffd9803712009-04-29 16:37:50 +00003029 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003030 for (ObjCProtocolDecl::instmeth_iterator
3031 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003032 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003033 if (I == PDecl->instmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003034 Result += "\t ,{{(struct objc_selector *)\"";
3035 else
3036 Result += "\t ,{(struct objc_selector *)\"";
3037 Result += (*I)->getSelector().getAsString().c_str();
3038 std::string MethodTypeString;
3039 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3040 Result += "\", \"";
3041 Result += MethodTypeString;
3042 Result += "\"}\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003043 }
Steve Naroffd9803712009-04-29 16:37:50 +00003044 Result += "\t }\n};\n";
3045 }
Mike Stump11289f42009-09-09 15:08:12 +00003046
Steve Naroffd9803712009-04-29 16:37:50 +00003047 // Output class methods declared in this protocol.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003048 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3049 PDecl->classmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003050 if (NumMethods > 0) {
3051 /* struct _objc_protocol_method_list {
3052 int protocol_method_count;
3053 struct protocol_methods protocols[];
3054 }
3055 */
3056 Result += "\nstatic struct {\n";
3057 Result += "\tint protocol_method_count;\n";
3058 Result += "\tstruct _protocol_methods protocol_methods[";
3059 Result += utostr(NumMethods);
3060 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3061 Result += PDecl->getNameAsString();
3062 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3063 "{\n\t";
3064 Result += utostr(NumMethods);
3065 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003066
Steve Naroffd9803712009-04-29 16:37:50 +00003067 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003068 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003069 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003070 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003071 if (I == PDecl->classmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003072 Result += "\t ,{{(struct objc_selector *)\"";
3073 else
3074 Result += "\t ,{(struct objc_selector *)\"";
3075 Result += (*I)->getSelector().getAsString().c_str();
3076 std::string MethodTypeString;
3077 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3078 Result += "\", \"";
3079 Result += MethodTypeString;
3080 Result += "\"}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003081 }
Steve Naroffd9803712009-04-29 16:37:50 +00003082 Result += "\t }\n};\n";
3083 }
3084
3085 // Output:
3086 /* struct _objc_protocol {
3087 // Objective-C 1.0 extensions
3088 struct _objc_protocol_extension *isa;
3089 char *protocol_name;
3090 struct _objc_protocol **protocol_list;
3091 struct _objc_protocol_method_list *instance_methods;
3092 struct _objc_protocol_method_list *class_methods;
Mike Stump11289f42009-09-09 15:08:12 +00003093 };
Steve Naroffd9803712009-04-29 16:37:50 +00003094 */
3095 static bool objc_protocol = false;
3096 if (!objc_protocol) {
3097 Result += "\nstruct _objc_protocol {\n";
3098 Result += "\tstruct _objc_protocol_extension *isa;\n";
3099 Result += "\tchar *protocol_name;\n";
3100 Result += "\tstruct _objc_protocol **protocol_list;\n";
3101 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3102 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003103 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003104
Steve Naroffd9803712009-04-29 16:37:50 +00003105 objc_protocol = true;
Chris Lattner388f6e92008-07-21 21:33:21 +00003106 }
Mike Stump11289f42009-09-09 15:08:12 +00003107
Steve Naroffd9803712009-04-29 16:37:50 +00003108 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3109 Result += PDecl->getNameAsString();
3110 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3111 "{\n\t0, \"";
3112 Result += PDecl->getNameAsString();
3113 Result += "\", 0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003114 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003115 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3116 Result += PDecl->getNameAsString();
3117 Result += ", ";
3118 }
3119 else
3120 Result += "0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003121 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003122 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3123 Result += PDecl->getNameAsString();
3124 Result += "\n";
3125 }
3126 else
3127 Result += "0\n";
3128 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003129
Steve Naroffd9803712009-04-29 16:37:50 +00003130 // Mark this protocol as having been generated.
3131 if (!ObjCSynthesizedProtocols.insert(PDecl))
3132 assert(false && "protocol already synthesized");
3133
3134}
3135
3136void RewriteObjC::
3137RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3138 const char *prefix, const char *ClassName,
3139 std::string &Result) {
3140 if (Protocols.empty()) return;
Mike Stump11289f42009-09-09 15:08:12 +00003141
Steve Naroffd9803712009-04-29 16:37:50 +00003142 for (unsigned i = 0; i != Protocols.size(); i++)
3143 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3144
Chris Lattner388f6e92008-07-21 21:33:21 +00003145 // Output the top lovel protocol meta-data for the class.
3146 /* struct _objc_protocol_list {
3147 struct _objc_protocol_list *next;
3148 int protocol_count;
3149 struct _objc_protocol *class_protocols[];
3150 }
3151 */
3152 Result += "\nstatic struct {\n";
3153 Result += "\tstruct _objc_protocol_list *next;\n";
3154 Result += "\tint protocol_count;\n";
3155 Result += "\tstruct _objc_protocol *class_protocols[";
3156 Result += utostr(Protocols.size());
3157 Result += "];\n} _OBJC_";
3158 Result += prefix;
3159 Result += "_PROTOCOLS_";
3160 Result += ClassName;
3161 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3162 "{\n\t0, ";
3163 Result += utostr(Protocols.size());
3164 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003165
Chris Lattner388f6e92008-07-21 21:33:21 +00003166 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003167 Result += Protocols[0]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003168 Result += " \n";
Mike Stump11289f42009-09-09 15:08:12 +00003169
Chris Lattner388f6e92008-07-21 21:33:21 +00003170 for (unsigned i = 1; i != Protocols.size(); i++) {
3171 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003172 Result += Protocols[i]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003173 Result += "\n";
3174 }
3175 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003176}
3177
Steve Naroffd9803712009-04-29 16:37:50 +00003178
Mike Stump11289f42009-09-09 15:08:12 +00003179/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003180/// implementation.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003181void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003182 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003183 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003184 // Find category declaration for this implementation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003185 ObjCCategoryDecl *CDecl;
Mike Stump11289f42009-09-09 15:08:12 +00003186 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003187 CDecl = CDecl->getNextClassCategory())
3188 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3189 break;
Mike Stump11289f42009-09-09 15:08:12 +00003190
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003191 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003192 FullCategoryName += '_';
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003193 FullCategoryName += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003194
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003195 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003196 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003197 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003198
3199 // If any of our property implementations have associated getters or
3200 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003201 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3202 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003203 Prop != PropEnd; ++Prop) {
3204 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3205 continue;
3206 if (!(*Prop)->getPropertyIvarDecl())
3207 continue;
3208 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3209 if (!PD)
3210 continue;
3211 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3212 InstanceMethods.push_back(Getter);
3213 if (PD->isReadOnly())
3214 continue;
3215 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3216 InstanceMethods.push_back(Setter);
3217 }
3218 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003219 true, "CATEGORY_", FullCategoryName.c_str(),
3220 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003221
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003222 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003223 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003224 false, "CATEGORY_", FullCategoryName.c_str(),
3225 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003226
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003227 // Protocols referenced in class declaration?
Fariborz Jahanian989e0392007-11-13 22:09:49 +00003228 // Null CDecl is case of a category implementation with no category interface
3229 if (CDecl)
Steve Naroffd9803712009-04-29 16:37:50 +00003230 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3231 FullCategoryName.c_str(), Result);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003232 /* struct _objc_category {
3233 char *category_name;
3234 char *class_name;
3235 struct _objc_method_list *instance_methods;
3236 struct _objc_method_list *class_methods;
3237 struct _objc_protocol_list *protocols;
3238 // Objective-C 1.0 extensions
3239 uint32_t size; // sizeof (struct _objc_category)
Mike Stump11289f42009-09-09 15:08:12 +00003240 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003241 // @property decl.
Mike Stump11289f42009-09-09 15:08:12 +00003242 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003243 */
Mike Stump11289f42009-09-09 15:08:12 +00003244
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003245 static bool objc_category = false;
3246 if (!objc_category) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003247 Result += "\nstruct _objc_category {\n";
3248 Result += "\tchar *category_name;\n";
3249 Result += "\tchar *class_name;\n";
3250 Result += "\tstruct _objc_method_list *instance_methods;\n";
3251 Result += "\tstruct _objc_method_list *class_methods;\n";
3252 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003253 Result += "\tunsigned int size;\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003254 Result += "\tstruct _objc_property_list *instance_properties;\n";
3255 Result += "};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003256 objc_category = true;
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003257 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003258 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3259 Result += FullCategoryName;
Steve Naroffb327e492008-03-12 17:18:30 +00003260 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003261 Result += IDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003262 Result += "\"\n\t, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003263 Result += ClassDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003264 Result += "\"\n";
Mike Stump11289f42009-09-09 15:08:12 +00003265
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003266 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003267 Result += "\t, (struct _objc_method_list *)"
3268 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3269 Result += FullCategoryName;
3270 Result += "\n";
3271 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003272 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003273 Result += "\t, 0\n";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003274 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003275 Result += "\t, (struct _objc_method_list *)"
3276 "&_OBJC_CATEGORY_CLASS_METHODS_";
3277 Result += FullCategoryName;
3278 Result += "\n";
3279 }
3280 else
3281 Result += "\t, 0\n";
Mike Stump11289f42009-09-09 15:08:12 +00003282
Chris Lattnerf5b77512009-02-20 18:18:36 +00003283 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump11289f42009-09-09 15:08:12 +00003284 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003285 Result += FullCategoryName;
3286 Result += "\n";
3287 }
3288 else
3289 Result += "\t, 0\n";
3290 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003291}
3292
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003293/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3294/// ivar offset.
Mike Stump11289f42009-09-09 15:08:12 +00003295void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
3296 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003297 std::string &Result) {
Steve Naroffde7d0f62008-07-16 18:22:22 +00003298 if (ivar->isBitField()) {
3299 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3300 // place all bitfields at offset 0.
3301 Result += "0";
3302 } else {
3303 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003304 Result += IDecl->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003305 if (LangOpts.Microsoft)
3306 Result += "_IMPL";
3307 Result += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003308 Result += ivar->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003309 Result += ")";
3310 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003311}
3312
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003313//===----------------------------------------------------------------------===//
3314// Meta Data Emission
3315//===----------------------------------------------------------------------===//
3316
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003317void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003318 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003319 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00003320
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003321 // Explictly declared @interface's are already synthesized.
Steve Naroffaac654a2009-04-20 20:09:33 +00003322 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump11289f42009-09-09 15:08:12 +00003323 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003324 // produce correct synthesis as yet.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003325 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003326 }
Mike Stump11289f42009-09-09 15:08:12 +00003327
Chris Lattner30d23e82007-12-12 07:56:42 +00003328 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003329 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump11289f42009-09-09 15:08:12 +00003330 ? IDecl->ivar_size()
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003331 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003332 if (NumIvars > 0) {
3333 static bool objc_ivar = false;
3334 if (!objc_ivar) {
3335 /* struct _objc_ivar {
3336 char *ivar_name;
3337 char *ivar_type;
3338 int ivar_offset;
Mike Stump11289f42009-09-09 15:08:12 +00003339 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003340 */
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003341 Result += "\nstruct _objc_ivar {\n";
3342 Result += "\tchar *ivar_name;\n";
3343 Result += "\tchar *ivar_type;\n";
3344 Result += "\tint ivar_offset;\n";
3345 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003346
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003347 objc_ivar = true;
3348 }
3349
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003350 /* struct {
3351 int ivar_count;
3352 struct _objc_ivar ivar_list[nIvars];
Mike Stump11289f42009-09-09 15:08:12 +00003353 };
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003354 */
Mike Stump11289f42009-09-09 15:08:12 +00003355 Result += "\nstatic struct {\n";
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003356 Result += "\tint ivar_count;\n";
3357 Result += "\tstruct _objc_ivar ivar_list[";
3358 Result += utostr(NumIvars);
3359 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003360 Result += IDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003361 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003362 "{\n\t";
3363 Result += utostr(NumIvars);
3364 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003365
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003366 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor5f662052009-04-23 03:23:08 +00003367 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003368 if (!IDecl->ivar_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00003369 for (ObjCImplementationDecl::ivar_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003370 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor5f662052009-04-23 03:23:08 +00003371 IV != IVEnd; ++IV)
3372 IVars.push_back(*IV);
3373 IVI = IVars.begin();
3374 IVE = IVars.end();
Chris Lattner30d23e82007-12-12 07:56:42 +00003375 } else {
3376 IVI = CDecl->ivar_begin();
3377 IVE = CDecl->ivar_end();
3378 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003379 Result += "\t,{{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003380 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003381 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003382 std::string TmpString, StrEncoding;
3383 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3384 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003385 Result += StrEncoding;
3386 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003387 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003388 Result += "}\n";
Chris Lattner30d23e82007-12-12 07:56:42 +00003389 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003390 Result += "\t ,{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003391 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003392 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003393 std::string TmpString, StrEncoding;
3394 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3395 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003396 Result += StrEncoding;
3397 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003398 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003399 Result += "}\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003400 }
Mike Stump11289f42009-09-09 15:08:12 +00003401
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003402 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003403 }
Mike Stump11289f42009-09-09 15:08:12 +00003404
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003405 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003406 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003407 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003408
3409 // If any of our property implementations have associated getters or
3410 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003411 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3412 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003413 Prop != PropEnd; ++Prop) {
3414 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3415 continue;
3416 if (!(*Prop)->getPropertyIvarDecl())
3417 continue;
3418 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3419 if (!PD)
3420 continue;
3421 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3422 InstanceMethods.push_back(Getter);
3423 if (PD->isReadOnly())
3424 continue;
3425 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3426 InstanceMethods.push_back(Setter);
3427 }
3428 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003429 true, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003430
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003431 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003432 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003433 false, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003434
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003435 // Protocols referenced in class declaration?
Steve Naroffd9803712009-04-29 16:37:50 +00003436 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3437 "CLASS", CDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003438
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003439 // Declaration of class/meta-class metadata
3440 /* struct _objc_class {
3441 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003442 const char *super_class_name;
3443 char *name;
3444 long version;
3445 long info;
3446 long instance_size;
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003447 struct _objc_ivar_list *ivars;
3448 struct _objc_method_list *methods;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003449 struct objc_cache *cache;
3450 struct objc_protocol_list *protocols;
3451 const char *ivar_layout;
3452 struct _objc_class_ext *ext;
Mike Stump11289f42009-09-09 15:08:12 +00003453 };
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003454 */
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003455 static bool objc_class = false;
3456 if (!objc_class) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003457 Result += "\nstruct _objc_class {\n";
3458 Result += "\tstruct _objc_class *isa;\n";
3459 Result += "\tconst char *super_class_name;\n";
3460 Result += "\tchar *name;\n";
3461 Result += "\tlong version;\n";
3462 Result += "\tlong info;\n";
3463 Result += "\tlong instance_size;\n";
3464 Result += "\tstruct _objc_ivar_list *ivars;\n";
3465 Result += "\tstruct _objc_method_list *methods;\n";
3466 Result += "\tstruct objc_cache *cache;\n";
3467 Result += "\tstruct _objc_protocol_list *protocols;\n";
3468 Result += "\tconst char *ivar_layout;\n";
3469 Result += "\tstruct _objc_class_ext *ext;\n";
3470 Result += "};\n";
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003471 objc_class = true;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003472 }
Mike Stump11289f42009-09-09 15:08:12 +00003473
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003474 // Meta-class metadata generation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003475 ObjCInterfaceDecl *RootClass = 0;
3476 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003477 while (SuperClass) {
3478 RootClass = SuperClass;
3479 SuperClass = SuperClass->getSuperClass();
3480 }
3481 SuperClass = CDecl->getSuperClass();
Mike Stump11289f42009-09-09 15:08:12 +00003482
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003483 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003484 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003485 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003486 "{\n\t(struct _objc_class *)\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003487 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003488 Result += "\"";
3489
3490 if (SuperClass) {
3491 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003492 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003493 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003494 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003495 Result += "\"";
3496 }
3497 else {
3498 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003499 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003500 Result += "\"";
3501 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003502 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003503 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003504 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003505 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff0b844f02008-03-11 18:14:26 +00003506 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003507 Result += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003508 Result += "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003509 }
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003510 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003511 Result += ", 0\n";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003512 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003513 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003514 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003515 Result += ",0,0\n";
3516 }
Fariborz Jahanian486f7182007-10-24 20:54:23 +00003517 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003518 Result += "\t,0,0,0,0\n";
3519 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003520
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003521 // class metadata generation.
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003522 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003523 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003524 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003525 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003526 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003527 if (SuperClass) {
3528 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003529 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003530 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003531 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003532 Result += "\"";
3533 }
3534 else {
3535 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003536 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003537 Result += "\"";
3538 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003539 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003540 Result += ", 0,1";
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003541 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003542 Result += ",0";
3543 else {
3544 // class has size. Must synthesize its size.
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00003545 Result += ",sizeof(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003546 Result += CDecl->getNameAsString();
Steve Naroff14a07462008-03-10 23:33:22 +00003547 if (LangOpts.Microsoft)
3548 Result += "_IMPL";
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003549 Result += ")";
3550 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003551 if (NumIvars > 0) {
Steve Naroff17978c42008-03-11 17:37:02 +00003552 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003553 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003554 Result += "\n\t";
3555 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003556 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003557 Result += ",0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003558 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003559 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003560 Result += CDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003561 Result += ", 0\n\t";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003562 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003563 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003564 Result += ",0,0";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003565 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003566 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003567 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003568 Result += ", 0,0\n";
3569 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003570 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003571 Result += ",0,0,0\n";
3572 Result += "};\n";
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003573}
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003574
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003575/// RewriteImplementations - This routine rewrites all method implementations
3576/// and emits meta-data.
3577
Steve Narofff8cfd162008-11-13 20:07:04 +00003578void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003579 int ClsDefCount = ClassImplementation.size();
3580 int CatDefCount = CategoryImplementation.size();
Mike Stump11289f42009-09-09 15:08:12 +00003581
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003582 // Rewrite implemented methods
3583 for (int i = 0; i < ClsDefCount; i++)
3584 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003585
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00003586 for (int i = 0; i < CatDefCount; i++)
3587 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofff8cfd162008-11-13 20:07:04 +00003588}
Mike Stump11289f42009-09-09 15:08:12 +00003589
Steve Narofff8cfd162008-11-13 20:07:04 +00003590void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3591 int ClsDefCount = ClassImplementation.size();
3592 int CatDefCount = CategoryImplementation.size();
3593
Steve Naroff30ac2222008-05-07 21:23:49 +00003594 // This is needed for determining instance variable offsets.
Mike Stump11289f42009-09-09 15:08:12 +00003595 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003596 // For each implemented class, write out all its meta data.
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003597 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003598 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump11289f42009-09-09 15:08:12 +00003599
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003600 // For each implemented category, write out all its meta data.
3601 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003602 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroffd9803712009-04-29 16:37:50 +00003603
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003604 // Write objc_symtab metadata
3605 /*
3606 struct _objc_symtab
3607 {
3608 long sel_ref_cnt;
3609 SEL *refs;
3610 short cls_def_cnt;
3611 short cat_def_cnt;
3612 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump11289f42009-09-09 15:08:12 +00003613 };
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003614 */
Mike Stump11289f42009-09-09 15:08:12 +00003615
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003616 Result += "\nstruct _objc_symtab {\n";
3617 Result += "\tlong sel_ref_cnt;\n";
3618 Result += "\tSEL *refs;\n";
3619 Result += "\tshort cls_def_cnt;\n";
3620 Result += "\tshort cat_def_cnt;\n";
3621 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3622 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003623
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003624 Result += "static struct _objc_symtab "
Steve Naroffb327e492008-03-12 17:18:30 +00003625 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003626 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003627 + ", " + utostr(CatDefCount) + "\n";
3628 for (int i = 0; i < ClsDefCount; i++) {
3629 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003630 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003631 Result += "\n";
3632 }
Mike Stump11289f42009-09-09 15:08:12 +00003633
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003634 for (int i = 0; i < CatDefCount; i++) {
3635 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003636 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003637 Result += "_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003638 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003639 Result += "\n";
3640 }
Mike Stump11289f42009-09-09 15:08:12 +00003641
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003642 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003643
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003644 // Write objc_module metadata
Mike Stump11289f42009-09-09 15:08:12 +00003645
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003646 /*
3647 struct _objc_module {
3648 long version;
3649 long size;
3650 const char *name;
3651 struct _objc_symtab *symtab;
3652 }
3653 */
Mike Stump11289f42009-09-09 15:08:12 +00003654
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003655 Result += "\nstruct _objc_module {\n";
3656 Result += "\tlong version;\n";
3657 Result += "\tlong size;\n";
3658 Result += "\tconst char *name;\n";
3659 Result += "\tstruct _objc_symtab *symtab;\n";
3660 Result += "};\n\n";
3661 Result += "static struct _objc_module "
Steve Naroffb327e492008-03-12 17:18:30 +00003662 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003663 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003664 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003665 Result += "};\n\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003666
3667 if (LangOpts.Microsoft) {
Steve Naroffd9803712009-04-29 16:37:50 +00003668 if (ProtocolExprDecls.size()) {
3669 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
3670 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump11289f42009-09-09 15:08:12 +00003671 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00003672 E = ProtocolExprDecls.end(); I != E; ++I) {
3673 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
3674 Result += (*I)->getNameAsString();
3675 Result += " = &_OBJC_PROTOCOL_";
3676 Result += (*I)->getNameAsString();
3677 Result += ";\n";
3678 }
3679 Result += "#pragma data_seg(pop)\n\n";
3680 }
Steve Naroff945a3b12008-03-10 20:43:59 +00003681 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffcab93d52008-05-07 00:06:16 +00003682 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003683 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3684 Result += "&_OBJC_MODULES;\n";
3685 Result += "#pragma data_seg(pop)\n\n";
3686 }
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003687}
Chris Lattnera7c19fe2007-10-16 22:36:42 +00003688
Steve Naroff677ab3a2008-10-27 17:20:55 +00003689std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3690 const char *funcName,
3691 std::string Tag) {
3692 const FunctionType *AFT = CE->getFunctionType();
3693 QualType RT = AFT->getResultType();
3694 std::string StructRef = "struct " + Tag;
3695 std::string S = "static " + RT.getAsString() + " __" +
3696 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00003697
Steve Naroff677ab3a2008-10-27 17:20:55 +00003698 BlockDecl *BD = CE->getBlockDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003699
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003700 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump11289f42009-09-09 15:08:12 +00003701 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Narofff26a1d42009-02-02 17:19:26 +00003702 // block (to reference imported block decl refs).
3703 S += "(" + StructRef + " *__cself)";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003704 } else if (BD->param_empty()) {
3705 S += "(" + StructRef + " *__cself)";
3706 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003707 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003708 assert(FT && "SynthesizeBlockFunc: No function proto");
3709 S += '(';
3710 // first add the implicit argument.
3711 S += StructRef + " *__cself, ";
3712 std::string ParamStr;
3713 for (BlockDecl::param_iterator AI = BD->param_begin(),
3714 E = BD->param_end(); AI != E; ++AI) {
3715 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003716 ParamStr = (*AI)->getNameAsString();
Douglas Gregor7de59662009-05-29 20:38:28 +00003717 (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003718 S += ParamStr;
3719 }
3720 if (FT->isVariadic()) {
3721 if (!BD->param_empty()) S += ", ";
3722 S += "...";
3723 }
3724 S += ')';
3725 }
3726 S += " {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003727
Steve Naroff677ab3a2008-10-27 17:20:55 +00003728 // Create local declarations to avoid rewriting all closure decl ref exprs.
3729 // First, emit a declaration for all "by ref" decls.
Mike Stump11289f42009-09-09 15:08:12 +00003730 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003731 E = BlockByRefDecls.end(); I != E; ++I) {
3732 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003733 std::string Name = (*I)->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003734 Context->getPointerType((*I)->getType()).getAsStringInternal(Name,
Douglas Gregor7de59662009-05-29 20:38:28 +00003735 Context->PrintingPolicy);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003736 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump11289f42009-09-09 15:08:12 +00003737 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003738 // Next, emit a declaration for all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003739 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003740 E = BlockByCopyDecls.end(); I != E; ++I) {
3741 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003742 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003743 // Handle nested closure invocation. For example:
3744 //
3745 // void (^myImportedClosure)(void);
3746 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003747 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003748 // void (^anotherClosure)(void);
3749 // anotherClosure = ^(void) {
3750 // myImportedClosure(); // import and invoke the closure
3751 // };
3752 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003753 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003754 S += "struct __block_impl *";
3755 else
Douglas Gregor7de59662009-05-29 20:38:28 +00003756 (*I)->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003757 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003758 }
3759 std::string RewrittenStr = RewrittenBlockExprs[CE];
3760 const char *cstr = RewrittenStr.c_str();
3761 while (*cstr++ != '{') ;
3762 S += cstr;
3763 S += "\n";
3764 return S;
3765}
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00003766
Steve Naroff677ab3a2008-10-27 17:20:55 +00003767std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3768 const char *funcName,
3769 std::string Tag) {
3770 std::string StructRef = "struct " + Tag;
3771 std::string S = "static void __";
Mike Stump11289f42009-09-09 15:08:12 +00003772
Steve Naroff677ab3a2008-10-27 17:20:55 +00003773 S += funcName;
3774 S += "_block_copy_" + utostr(i);
3775 S += "(" + StructRef;
3776 S += "*dst, " + StructRef;
3777 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003778 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003779 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003780 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003781 S += (*I)->getNameAsString();
Steve Naroff5ac4eac2008-12-11 20:51:38 +00003782 S += ", (void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003783 S += (*I)->getNameAsString();
Steve Naroff61d879e2008-12-16 15:50:30 +00003784 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);}";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003785 }
3786 S += "\nstatic void __";
3787 S += funcName;
3788 S += "_block_dispose_" + utostr(i);
3789 S += "(" + StructRef;
3790 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003791 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003792 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003793 S += "_Block_object_dispose((void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003794 S += (*I)->getNameAsString();
Steve Naroff61d879e2008-12-16 15:50:30 +00003795 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003796 }
Mike Stump11289f42009-09-09 15:08:12 +00003797 S += "}\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003798 return S;
3799}
3800
Steve Naroff30484702009-12-06 21:14:13 +00003801std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3802 std::string Desc) {
Steve Naroff295570a2008-10-30 12:09:33 +00003803 std::string S = "\nstruct " + Tag;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003804 std::string Constructor = " " + Tag;
Mike Stump11289f42009-09-09 15:08:12 +00003805
Steve Naroff677ab3a2008-10-27 17:20:55 +00003806 S += " {\n struct __block_impl impl;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003807 S += " struct " + Desc;
3808 S += "* Desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003809
Steve Naroff30484702009-12-06 21:14:13 +00003810 Constructor += "(void *fp, "; // Invoke function pointer.
3811 Constructor += "struct " + Desc; // Descriptor pointer.
3812 Constructor += " *desc";
Mike Stump11289f42009-09-09 15:08:12 +00003813
Steve Naroff677ab3a2008-10-27 17:20:55 +00003814 if (BlockDeclRefs.size()) {
3815 // Output all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003816 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003817 E = BlockByCopyDecls.end(); I != E; ++I) {
3818 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003819 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003820 std::string ArgName = "_" + FieldName;
3821 // Handle nested closure invocation. For example:
3822 //
3823 // void (^myImportedBlock)(void);
3824 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003825 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003826 // void (^anotherBlock)(void);
3827 // anotherBlock = ^(void) {
3828 // myImportedBlock(); // import and invoke the closure
3829 // };
3830 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003831 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003832 S += "struct __block_impl *";
3833 Constructor += ", void *" + ArgName;
3834 } else {
Douglas Gregor7de59662009-05-29 20:38:28 +00003835 (*I)->getType().getAsStringInternal(FieldName, Context->PrintingPolicy);
3836 (*I)->getType().getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003837 Constructor += ", " + ArgName;
3838 }
3839 S += FieldName + ";\n";
3840 }
3841 // Output all "by ref" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003842 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003843 E = BlockByRefDecls.end(); I != E; ++I) {
3844 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003845 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003846 std::string ArgName = "_" + FieldName;
3847 // Handle nested closure invocation. For example:
3848 //
3849 // void (^myImportedBlock)(void);
3850 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003851 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003852 // void (^anotherBlock)(void);
3853 // anotherBlock = ^(void) {
3854 // myImportedBlock(); // import and invoke the closure
3855 // };
3856 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003857 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003858 S += "struct __block_impl *";
3859 Constructor += ", void *" + ArgName;
3860 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003861 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName,
Douglas Gregor7de59662009-05-29 20:38:28 +00003862 Context->PrintingPolicy);
Mike Stump11289f42009-09-09 15:08:12 +00003863 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName,
Douglas Gregor7de59662009-05-29 20:38:28 +00003864 Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003865 Constructor += ", " + ArgName;
3866 }
3867 S += FieldName + "; // by ref\n";
3868 }
3869 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00003870 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00003871 if (GlobalVarDecl)
3872 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3873 else
3874 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003875 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003876
Steve Naroff30484702009-12-06 21:14:13 +00003877 Constructor += " Desc = desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003878
Steve Naroff677ab3a2008-10-27 17:20:55 +00003879 // Initialize all "by copy" arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003880 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003881 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003882 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003883 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00003884 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003885 Constructor += Name + " = (struct __block_impl *)_";
3886 else
3887 Constructor += Name + " = _";
3888 Constructor += Name + ";\n";
3889 }
3890 // Initialize all "by ref" arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003891 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003892 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003893 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003894 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00003895 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003896 Constructor += Name + " = (struct __block_impl *)_";
3897 else
3898 Constructor += Name + " = _";
3899 Constructor += Name + ";\n";
3900 }
3901 } else {
3902 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00003903 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00003904 if (GlobalVarDecl)
3905 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3906 else
3907 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003908 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3909 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003910 }
3911 Constructor += " ";
3912 Constructor += "}\n";
3913 S += Constructor;
3914 S += "};\n";
3915 return S;
3916}
3917
Steve Naroff30484702009-12-06 21:14:13 +00003918std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
3919 std::string ImplTag, int i,
3920 const char *FunName,
3921 unsigned hasCopy) {
3922 std::string S = "\nstatic struct " + DescTag;
3923
3924 S += " {\n unsigned long reserved;\n";
3925 S += " unsigned long Block_size;\n";
3926 if (hasCopy) {
3927 S += " void *copy;\n void *dispose;\n";
3928 }
3929 S += "} ";
3930
3931 S += DescTag + "_DATA = { 0, sizeof(struct ";
3932 S += ImplTag + ")";
3933 if (hasCopy) {
3934 S += ", __" + std::string(FunName) + "_block_copy_" + utostr(i);
3935 S += ", __" + std::string(FunName) + "_block_dispose_" + utostr(i);
3936 }
3937 S += "};\n";
3938 return S;
3939}
3940
Steve Naroff677ab3a2008-10-27 17:20:55 +00003941void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3942 const char *FunName) {
3943 // Insert closures that were part of the function.
3944 for (unsigned i = 0; i < Blocks.size(); i++) {
3945
3946 CollectBlockDeclRefInfo(Blocks[i]);
3947
Steve Naroff30484702009-12-06 21:14:13 +00003948 std::string ImplTag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3949 std::string DescTag = "__" + std::string(FunName) + "_block_desc_" + utostr(i);
Mike Stump11289f42009-09-09 15:08:12 +00003950
Steve Naroff30484702009-12-06 21:14:13 +00003951 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003952
3953 InsertText(FunLocStart, CI.c_str(), CI.size());
3954
Steve Naroff30484702009-12-06 21:14:13 +00003955 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump11289f42009-09-09 15:08:12 +00003956
Steve Naroff677ab3a2008-10-27 17:20:55 +00003957 InsertText(FunLocStart, CF.c_str(), CF.size());
3958
3959 if (ImportedBlockDecls.size()) {
Steve Naroff30484702009-12-06 21:14:13 +00003960 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003961 InsertText(FunLocStart, HF.c_str(), HF.size());
3962 }
Steve Naroff30484702009-12-06 21:14:13 +00003963 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3964 ImportedBlockDecls.size() > 0);
3965 InsertText(FunLocStart, BD.c_str(), BD.size());
Mike Stump11289f42009-09-09 15:08:12 +00003966
Steve Naroff677ab3a2008-10-27 17:20:55 +00003967 BlockDeclRefs.clear();
3968 BlockByRefDecls.clear();
3969 BlockByCopyDecls.clear();
3970 BlockCallExprs.clear();
3971 ImportedBlockDecls.clear();
3972 }
3973 Blocks.clear();
3974 RewrittenBlockExprs.clear();
3975}
3976
3977void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3978 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner86d7d912008-11-24 03:54:41 +00003979 const char *FuncName = FD->getNameAsCString();
Mike Stump11289f42009-09-09 15:08:12 +00003980
Steve Naroff677ab3a2008-10-27 17:20:55 +00003981 SynthesizeBlockLiterals(FunLocStart, FuncName);
3982}
3983
3984void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff295570a2008-10-30 12:09:33 +00003985 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3986 //SourceLocation FunLocStart = MD->getLocStart();
3987 // FIXME: This hack works around a bug in Rewrite.InsertText().
3988 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattnere4b95692008-11-24 03:33:13 +00003989 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003990 // Convert colons to underscores.
3991 std::string::size_type loc = 0;
3992 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3993 FuncName.replace(loc, 1, "_");
Mike Stump11289f42009-09-09 15:08:12 +00003994
Steve Naroff677ab3a2008-10-27 17:20:55 +00003995 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3996}
3997
3998void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3999 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4000 CI != E; ++CI)
4001 if (*CI) {
4002 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4003 GetBlockDeclRefExprs(CBE->getBody());
4004 else
4005 GetBlockDeclRefExprs(*CI);
4006 }
4007 // Handle specific things.
4008 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
4009 // FIXME: Handle enums.
4010 if (!isa<FunctionDecl>(CDRE->getDecl()))
4011 BlockDeclRefs.push_back(CDRE);
4012 return;
4013}
4014
4015void RewriteObjC::GetBlockCallExprs(Stmt *S) {
4016 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4017 CI != E; ++CI)
4018 if (*CI) {
4019 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4020 GetBlockCallExprs(CBE->getBody());
4021 else
4022 GetBlockCallExprs(*CI);
4023 }
Mike Stump11289f42009-09-09 15:08:12 +00004024
Steve Naroff677ab3a2008-10-27 17:20:55 +00004025 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4026 if (CE->getCallee()->getType()->isBlockPointerType()) {
4027 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
4028 }
4029 }
4030 return;
4031}
4032
Steve Naroff350b6652008-10-30 10:07:53 +00004033Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004034 // Navigate to relevant type information.
4035 const char *closureName = 0;
4036 const BlockPointerType *CPT = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004037
Steve Naroff677ab3a2008-10-27 17:20:55 +00004038 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004039 closureName = DRE->getDecl()->getNameAsCString();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004040 CPT = DRE->getType()->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004041 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004042 closureName = CDRE->getDecl()->getNameAsCString();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004043 CPT = CDRE->getType()->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004044 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004045 closureName = MExpr->getMemberDecl()->getNameAsCString();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004046 CPT = MExpr->getType()->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004047 } else {
4048 assert(1 && "RewriteBlockClass: Bad type");
4049 }
4050 assert(CPT && "RewriteBlockClass: Bad type");
John McCall9dd450b2009-09-21 23:43:11 +00004051 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004052 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004053 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004054 // FTP will be null for closures that don't take arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004055
Steve Naroff350b6652008-10-30 10:07:53 +00004056 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
4057 SourceLocation(),
4058 &Context->Idents.get("__block_impl"));
4059 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff677ab3a2008-10-27 17:20:55 +00004060
Steve Naroff350b6652008-10-30 10:07:53 +00004061 // Generate a funky cast.
4062 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00004063
Steve Naroff350b6652008-10-30 10:07:53 +00004064 // Push the block argument type.
4065 ArgTypes.push_back(PtrBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004066 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004067 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff350b6652008-10-30 10:07:53 +00004068 E = FTP->arg_type_end(); I && (I != E); ++I) {
4069 QualType t = *I;
4070 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00004071 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004072 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff350b6652008-10-30 10:07:53 +00004073 t = Context->getPointerType(BPT->getPointeeType());
4074 }
4075 ArgTypes.push_back(t);
4076 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004077 }
Steve Naroff350b6652008-10-30 10:07:53 +00004078 // Now do the pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00004079 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Steve Naroff350b6652008-10-30 10:07:53 +00004080 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004081
Steve Naroff350b6652008-10-30 10:07:53 +00004082 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump11289f42009-09-09 15:08:12 +00004083
4084 CastExpr *BlkCast = new (Context) CStyleCastExpr(PtrBlock,
Anders Carlssona2615922009-07-31 00:48:10 +00004085 CastExpr::CK_Unknown,
4086 Exp->getCallee(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004087 PtrBlock, SourceLocation(),
4088 SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004089 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00004090 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4091 BlkCast);
Steve Naroff350b6652008-10-30 10:07:53 +00004092 //PE->dump();
Mike Stump11289f42009-09-09 15:08:12 +00004093
Douglas Gregor91f84212008-12-11 16:49:14 +00004094 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00004095 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004096 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek5a201952009-02-07 01:47:29 +00004097 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4098 FD->getType());
Mike Stump11289f42009-09-09 15:08:12 +00004099
Anders Carlssona2615922009-07-31 00:48:10 +00004100 CastExpr *FunkCast = new (Context) CStyleCastExpr(PtrToFuncCastType,
4101 CastExpr::CK_Unknown, ME,
Ted Kremenek5a201952009-02-07 01:47:29 +00004102 PtrToFuncCastType,
4103 SourceLocation(),
4104 SourceLocation());
4105 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump11289f42009-09-09 15:08:12 +00004106
Steve Naroff350b6652008-10-30 10:07:53 +00004107 llvm::SmallVector<Expr*, 8> BlkExprs;
4108 // Add the implicit argument.
4109 BlkExprs.push_back(BlkCast);
4110 // Add the user arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004111 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004112 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00004113 BlkExprs.push_back(*I);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004114 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004115 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4116 BlkExprs.size(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004117 Exp->getType(), SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004118 return CE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004119}
4120
4121void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Steve Naroff350b6652008-10-30 10:07:53 +00004122 Stmt *BlockCall = SynthesizeBlockCall(Exp);
4123 ReplaceStmt(Exp, BlockCall);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004124}
4125
Steve Naroffd9803712009-04-29 16:37:50 +00004126// We need to return the rewritten expression to handle cases where the
4127// BlockDeclRefExpr is embedded in another expression being rewritten.
4128// For example:
4129//
4130// int main() {
4131// __block Foo *f;
4132// __block int i;
Mike Stump11289f42009-09-09 15:08:12 +00004133//
Steve Naroffd9803712009-04-29 16:37:50 +00004134// void (^myblock)() = ^() {
4135// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4136// i = 77;
4137// };
4138//}
4139Stmt *RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004140 // FIXME: Add more elaborate code generation required by the ABI.
Ted Kremenek5a201952009-02-07 01:47:29 +00004141 Expr *DerefExpr = new (Context) UnaryOperator(BDRE, UnaryOperator::Deref,
Steve Narofff26a1d42009-02-02 17:19:26 +00004142 Context->getPointerType(BDRE->getType()),
4143 SourceLocation());
4144 // Need parens to enforce precedence.
Ted Kremenek5a201952009-02-07 01:47:29 +00004145 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), DerefExpr);
Steve Narofff26a1d42009-02-02 17:19:26 +00004146 ReplaceStmt(BDRE, PE);
Steve Naroffd9803712009-04-29 16:37:50 +00004147 return PE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004148}
4149
Steve Naroffc989a7b2008-11-03 23:29:32 +00004150void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4151 SourceLocation LocStart = CE->getLParenLoc();
4152 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofff4b992a2008-10-28 20:29:00 +00004153
4154 // Need to avoid trying to rewrite synthesized casts.
4155 if (LocStart.isInvalid())
4156 return;
Steve Naroff3e7ced12008-11-03 11:20:24 +00004157 // Need to avoid trying to rewrite casts contained in macros.
4158 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4159 return;
Mike Stump11289f42009-09-09 15:08:12 +00004160
Steve Naroff677ab3a2008-10-27 17:20:55 +00004161 const char *startBuf = SM->getCharacterData(LocStart);
4162 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00004163
Steve Naroff677ab3a2008-10-27 17:20:55 +00004164 // advance the location to startArgList.
4165 const char *argPtr = startBuf;
Mike Stump11289f42009-09-09 15:08:12 +00004166
Steve Naroff677ab3a2008-10-27 17:20:55 +00004167 while (*argPtr++ && (argPtr < endBuf)) {
4168 switch (*argPtr) {
Mike Stump11289f42009-09-09 15:08:12 +00004169 case '^':
Steve Naroff677ab3a2008-10-27 17:20:55 +00004170 // Replace the '^' with '*'.
4171 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
4172 ReplaceText(LocStart, 1, "*", 1);
4173 break;
4174 }
4175 }
4176 return;
4177}
4178
4179void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4180 SourceLocation DeclLoc = FD->getLocation();
4181 unsigned parenCount = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004182
Steve Naroff677ab3a2008-10-27 17:20:55 +00004183 // We have 1 or more arguments that have closure pointers.
4184 const char *startBuf = SM->getCharacterData(DeclLoc);
4185 const char *startArgList = strchr(startBuf, '(');
Mike Stump11289f42009-09-09 15:08:12 +00004186
Steve Naroff677ab3a2008-10-27 17:20:55 +00004187 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004188
Steve Naroff677ab3a2008-10-27 17:20:55 +00004189 parenCount++;
4190 // advance the location to startArgList.
4191 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4192 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump11289f42009-09-09 15:08:12 +00004193
Steve Naroff677ab3a2008-10-27 17:20:55 +00004194 const char *argPtr = startArgList;
Mike Stump11289f42009-09-09 15:08:12 +00004195
Steve Naroff677ab3a2008-10-27 17:20:55 +00004196 while (*argPtr++ && parenCount) {
4197 switch (*argPtr) {
Mike Stump11289f42009-09-09 15:08:12 +00004198 case '^':
Steve Naroff677ab3a2008-10-27 17:20:55 +00004199 // Replace the '^' with '*'.
4200 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
4201 ReplaceText(DeclLoc, 1, "*", 1);
4202 break;
Mike Stump11289f42009-09-09 15:08:12 +00004203 case '(':
4204 parenCount++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004205 break;
Mike Stump11289f42009-09-09 15:08:12 +00004206 case ')':
Steve Naroff677ab3a2008-10-27 17:20:55 +00004207 parenCount--;
4208 break;
4209 }
4210 }
4211 return;
4212}
4213
4214bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004215 const FunctionProtoType *FTP;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004216 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004217 if (PT) {
John McCall9dd450b2009-09-21 23:43:11 +00004218 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004219 } else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004220 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004221 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall9dd450b2009-09-21 23:43:11 +00004222 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004223 }
4224 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004225 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004226 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +00004227 if (isTopLevelBlockPointerType(*I))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004228 return true;
4229 }
4230 return false;
4231}
4232
Ted Kremenek5a201952009-02-07 01:47:29 +00004233void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4234 const char *&RParen) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004235 const char *argPtr = strchr(Name, '(');
4236 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004237
Steve Naroff677ab3a2008-10-27 17:20:55 +00004238 LParen = argPtr; // output the start.
4239 argPtr++; // skip past the left paren.
4240 unsigned parenCount = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004241
Steve Naroff677ab3a2008-10-27 17:20:55 +00004242 while (*argPtr && parenCount) {
4243 switch (*argPtr) {
4244 case '(': parenCount++; break;
4245 case ')': parenCount--; break;
4246 default: break;
4247 }
4248 if (parenCount) argPtr++;
4249 }
4250 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4251 RParen = argPtr; // output the end
4252}
4253
4254void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4255 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4256 RewriteBlockPointerFunctionArgs(FD);
4257 return;
Mike Stump11289f42009-09-09 15:08:12 +00004258 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004259 // Handle Variables and Typedefs.
4260 SourceLocation DeclLoc = ND->getLocation();
4261 QualType DeclT;
4262 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4263 DeclT = VD->getType();
4264 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4265 DeclT = TDD->getUnderlyingType();
4266 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4267 DeclT = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004268 else
Steve Naroff677ab3a2008-10-27 17:20:55 +00004269 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump11289f42009-09-09 15:08:12 +00004270
Steve Naroff677ab3a2008-10-27 17:20:55 +00004271 const char *startBuf = SM->getCharacterData(DeclLoc);
4272 const char *endBuf = startBuf;
4273 // scan backward (from the decl location) for the end of the previous decl.
4274 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4275 startBuf--;
Mike Stump11289f42009-09-09 15:08:12 +00004276
Steve Naroff677ab3a2008-10-27 17:20:55 +00004277 // *startBuf != '^' if we are dealing with a pointer to function that
4278 // may take block argument types (which will be handled below).
4279 if (*startBuf == '^') {
4280 // Replace the '^' with '*', computing a negative offset.
4281 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4282 ReplaceText(DeclLoc, 1, "*", 1);
4283 }
4284 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4285 // Replace the '^' with '*' for arguments.
4286 DeclLoc = ND->getLocation();
4287 startBuf = SM->getCharacterData(DeclLoc);
4288 const char *argListBegin, *argListEnd;
4289 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4290 while (argListBegin < argListEnd) {
4291 if (*argListBegin == '^') {
4292 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
4293 ReplaceText(CaretLoc, 1, "*", 1);
4294 }
4295 argListBegin++;
4296 }
4297 }
4298 return;
4299}
4300
Mike Stump11289f42009-09-09 15:08:12 +00004301void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004302 // Add initializers for any closure decl refs.
4303 GetBlockDeclRefExprs(Exp->getBody());
4304 if (BlockDeclRefs.size()) {
4305 // Unique all "by copy" declarations.
4306 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4307 if (!BlockDeclRefs[i]->isByRef())
4308 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
4309 // Unique all "by ref" declarations.
4310 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4311 if (BlockDeclRefs[i]->isByRef()) {
4312 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
4313 }
4314 // Find any imported blocks...they will need special attention.
4315 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Steve Naroff5ac4eac2008-12-11 20:51:38 +00004316 if (BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroff832d8902008-11-13 17:40:07 +00004317 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004318 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4319 }
4320 }
4321}
4322
Steve Narofff4b992a2008-10-28 20:29:00 +00004323FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4324 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004325 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump11289f42009-09-09 15:08:12 +00004326 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004327 ID, FType, 0, FunctionDecl::Extern, false,
Douglas Gregor739ef0c2009-02-25 16:33:18 +00004328 false);
Steve Narofff4b992a2008-10-28 20:29:00 +00004329}
4330
Steve Naroffd8907b72008-10-29 18:15:37 +00004331Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004332 Blocks.push_back(Exp);
4333
4334 CollectBlockDeclRefInfo(Exp);
4335 std::string FuncName;
Mike Stump11289f42009-09-09 15:08:12 +00004336
Steve Narofff4b992a2008-10-28 20:29:00 +00004337 if (CurFunctionDef)
Chris Lattnere4b95692008-11-24 03:33:13 +00004338 FuncName = CurFunctionDef->getNameAsString();
Steve Narofff4b992a2008-10-28 20:29:00 +00004339 else if (CurMethodDef) {
Chris Lattnere4b95692008-11-24 03:33:13 +00004340 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofff4b992a2008-10-28 20:29:00 +00004341 // Convert colons to underscores.
4342 std::string::size_type loc = 0;
4343 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4344 FuncName.replace(loc, 1, "_");
Steve Naroffd8907b72008-10-29 18:15:37 +00004345 } else if (GlobalVarDecl)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004346 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump11289f42009-09-09 15:08:12 +00004347
Steve Narofff4b992a2008-10-28 20:29:00 +00004348 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump11289f42009-09-09 15:08:12 +00004349
Steve Narofff4b992a2008-10-28 20:29:00 +00004350 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4351 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump11289f42009-09-09 15:08:12 +00004352
Steve Narofff4b992a2008-10-28 20:29:00 +00004353 // Get a pointer to the function type so we can cast appropriately.
4354 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4355
4356 FunctionDecl *FD;
4357 Expr *NewRep;
Mike Stump11289f42009-09-09 15:08:12 +00004358
Steve Narofff4b992a2008-10-28 20:29:00 +00004359 // Simulate a contructor call...
4360 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004361 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004362
Steve Narofff4b992a2008-10-28 20:29:00 +00004363 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00004364
Steve Naroffe2514232008-10-29 21:23:59 +00004365 // Initialize the block function.
Steve Narofff4b992a2008-10-28 20:29:00 +00004366 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004367 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4368 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004369 CastExpr *castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4370 CastExpr::CK_Unknown, Arg,
Ted Kremenek5a201952009-02-07 01:47:29 +00004371 Context->VoidPtrTy, SourceLocation(),
4372 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004373 InitExprs.push_back(castExpr);
4374
Steve Naroff30484702009-12-06 21:14:13 +00004375 // Initialize the block descriptor.
4376 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump11289f42009-09-09 15:08:12 +00004377
Steve Naroff30484702009-12-06 21:14:13 +00004378 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
4379 &Context->Idents.get(DescData.c_str()),
4380 Context->VoidPtrTy, 0,
4381 VarDecl::Static);
4382 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
4383 new (Context) DeclRefExpr(NewVD,
4384 Context->VoidPtrTy, SourceLocation()),
4385 UnaryOperator::AddrOf,
4386 Context->getPointerType(Context->VoidPtrTy),
4387 SourceLocation());
4388 InitExprs.push_back(DescRefExpr);
4389
Steve Narofff4b992a2008-10-28 20:29:00 +00004390 // Add initializers for any closure decl refs.
4391 if (BlockDeclRefs.size()) {
Steve Naroffe2514232008-10-29 21:23:59 +00004392 Expr *Exp;
Steve Narofff4b992a2008-10-28 20:29:00 +00004393 // Output all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004394 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004395 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004396 if (isObjCType((*I)->getType())) {
Steve Naroffe2514232008-10-29 21:23:59 +00004397 // FIXME: Conform to ABI ([[obj retain] autorelease]).
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());
Steve Naroffa5c0db82008-12-11 21:05:33 +00004400 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004401 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004402 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004403 Exp = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4404 CastExpr::CK_Unknown, Arg,
4405 Context->VoidPtrTy,
Anders Carlssona2615922009-07-31 00:48:10 +00004406 SourceLocation(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004407 SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004408 } else {
Chris Lattner86d7d912008-11-24 03:54:41 +00004409 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004410 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004411 }
Mike Stump11289f42009-09-09 15:08:12 +00004412 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004413 }
4414 // Output all "by ref" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004415 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004416 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004417 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004418 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4419 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004420 Context->getPointerType(Exp->getType()),
Steve Naroffe2514232008-10-29 21:23:59 +00004421 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004422 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004423 }
4424 }
Steve Naroff30484702009-12-06 21:14:13 +00004425 if (ImportedBlockDecls.size()) { // generate "1<<25" to indicate we have helper functions.
4426 unsigned IntSize =
4427 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4428 BinaryOperator *Exp = new (Context) BinaryOperator(
4429 new (Context) IntegerLiteral(llvm::APInt(IntSize, 1),
4430 Context->IntTy,SourceLocation()),
4431 new (Context) IntegerLiteral(llvm::APInt(IntSize, 25),
4432 Context->IntTy, SourceLocation()),
4433 BinaryOperator::Shl, Context->IntTy, SourceLocation());
4434 InitExprs.push_back(Exp);
4435 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004436 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4437 FType, SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00004438 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004439 Context->getPointerType(NewRep->getType()),
Steve Narofff4b992a2008-10-28 20:29:00 +00004440 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004441 NewRep = new (Context) CStyleCastExpr(FType, CastExpr::CK_Unknown, NewRep,
Anders Carlssona2615922009-07-31 00:48:10 +00004442 FType, SourceLocation(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004443 SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004444 BlockDeclRefs.clear();
4445 BlockByRefDecls.clear();
4446 BlockByCopyDecls.clear();
4447 ImportedBlockDecls.clear();
4448 return NewRep;
4449}
4450
4451//===----------------------------------------------------------------------===//
4452// Function Body / Expression rewriting
4453//===----------------------------------------------------------------------===//
4454
Steve Naroff4588d0f2008-12-04 16:24:46 +00004455// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4456// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4457// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4458// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4459// Since the rewriter isn't capable of rewriting rewritten code, it's important
4460// we get this right.
4461void RewriteObjC::CollectPropertySetters(Stmt *S) {
4462 // Perform a bottom up traversal of all children.
4463 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4464 CI != E; ++CI)
4465 if (*CI)
4466 CollectPropertySetters(*CI);
4467
4468 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4469 if (BinOp->isAssignmentOp()) {
4470 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4471 PropSetters[PRE] = BinOp;
4472 }
4473 }
4474}
4475
Steve Narofff4b992a2008-10-28 20:29:00 +00004476Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump11289f42009-09-09 15:08:12 +00004477 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004478 isa<DoStmt>(S) || isa<ForStmt>(S))
4479 Stmts.push_back(S);
4480 else if (isa<ObjCForCollectionStmt>(S)) {
4481 Stmts.push_back(S);
4482 ObjCBcLabelNo.push_back(++BcLabelCount);
4483 }
Mike Stump11289f42009-09-09 15:08:12 +00004484
Steve Narofff4b992a2008-10-28 20:29:00 +00004485 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004486
Steve Narofff4b992a2008-10-28 20:29:00 +00004487 // Perform a bottom up rewrite of all children.
4488 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4489 CI != E; ++CI)
4490 if (*CI) {
4491 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Mike Stump11289f42009-09-09 15:08:12 +00004492 if (newStmt)
Steve Narofff4b992a2008-10-28 20:29:00 +00004493 *CI = newStmt;
4494 }
Mike Stump11289f42009-09-09 15:08:12 +00004495
Steve Narofff4b992a2008-10-28 20:29:00 +00004496 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4497 // Rewrite the block body in place.
4498 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Mike Stump11289f42009-09-09 15:08:12 +00004499
Steve Narofff4b992a2008-10-28 20:29:00 +00004500 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroffd8907b72008-10-29 18:15:37 +00004501 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
4502 RewrittenBlockExprs[BE] = Str;
Mike Stump11289f42009-09-09 15:08:12 +00004503
Steve Narofff4b992a2008-10-28 20:29:00 +00004504 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4505 //blockTranscribed->dump();
Steve Naroffd8907b72008-10-29 18:15:37 +00004506 ReplaceStmt(S, blockTranscribed);
Steve Narofff4b992a2008-10-28 20:29:00 +00004507 return blockTranscribed;
4508 }
4509 // Handle specific things.
4510 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4511 return RewriteAtEncode(AtEncode);
Mike Stump11289f42009-09-09 15:08:12 +00004512
Steve Narofff4b992a2008-10-28 20:29:00 +00004513 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4514 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4515
Steve Naroff4588d0f2008-12-04 16:24:46 +00004516 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4517 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4518 if (BinOp) {
4519 // Because the rewriter doesn't allow us to rewrite rewritten code,
4520 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroff08628db2008-12-09 12:56:34 +00004521 DisableReplaceStmt = true;
4522 // Save the source range. Even if we disable the replacement, the
4523 // rewritten node will have been inserted into the tree. If the synthesized
4524 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump11289f42009-09-09 15:08:12 +00004525 // self.errorHandler = handler ? handler :
Steve Naroff08628db2008-12-09 12:56:34 +00004526 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4527 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroff4588d0f2008-12-04 16:24:46 +00004528 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroff08628db2008-12-09 12:56:34 +00004529 DisableReplaceStmt = false;
Steve Naroff22216db2008-12-04 23:50:32 +00004530 //
4531 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4532 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4533 // to see the original expression). Consider this example:
4534 //
4535 // Foo *obj1, *obj2;
4536 //
4537 // obj1.i = [obj2 rrrr];
4538 //
4539 // 'BinOp' for the previous expression looks like:
4540 //
4541 // (BinaryOperator 0x231ccf0 'int' '='
4542 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4543 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4544 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4545 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4546 //
4547 // 'newStmt' represents the rewritten message expression. For example:
4548 //
4549 // (CallExpr 0x231d300 'id':'struct objc_object *'
4550 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4551 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4552 // (CStyleCastExpr 0x231d220 'void *'
4553 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4554 //
4555 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4556 // can be used as the setter argument. ReplaceStmt() will still 'see'
4557 // the original RHS (since we haven't altered BinOp).
4558 //
Mike Stump11289f42009-09-09 15:08:12 +00004559 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff22216db2008-12-04 23:50:32 +00004560 // node. As a result, we now leak the original AST nodes.
4561 //
Steve Naroff08628db2008-12-09 12:56:34 +00004562 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroff4588d0f2008-12-04 16:24:46 +00004563 } else {
4564 return RewritePropertyGetter(PropRefExpr);
Steve Narofff326f402008-12-03 00:56:33 +00004565 }
4566 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004567 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4568 return RewriteAtSelector(AtSelector);
Mike Stump11289f42009-09-09 15:08:12 +00004569
Steve Narofff4b992a2008-10-28 20:29:00 +00004570 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4571 return RewriteObjCStringLiteral(AtString);
Mike Stump11289f42009-09-09 15:08:12 +00004572
Steve Narofff4b992a2008-10-28 20:29:00 +00004573 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00004574#if 0
Steve Narofff4b992a2008-10-28 20:29:00 +00004575 // Before we rewrite it, put the original message expression in a comment.
4576 SourceLocation startLoc = MessExpr->getLocStart();
4577 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00004578
Steve Narofff4b992a2008-10-28 20:29:00 +00004579 const char *startBuf = SM->getCharacterData(startLoc);
4580 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004581
Steve Narofff4b992a2008-10-28 20:29:00 +00004582 std::string messString;
4583 messString += "// ";
4584 messString.append(startBuf, endBuf-startBuf+1);
4585 messString += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00004586
4587 // FIXME: Missing definition of
Steve Narofff4b992a2008-10-28 20:29:00 +00004588 // InsertText(clang::SourceLocation, char const*, unsigned int).
4589 // InsertText(startLoc, messString.c_str(), messString.size());
4590 // Tried this, but it didn't work either...
4591 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff4588d0f2008-12-04 16:24:46 +00004592#endif
Steve Narofff4b992a2008-10-28 20:29:00 +00004593 return RewriteMessageExpr(MessExpr);
4594 }
Mike Stump11289f42009-09-09 15:08:12 +00004595
Steve Narofff4b992a2008-10-28 20:29:00 +00004596 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4597 return RewriteObjCTryStmt(StmtTry);
4598
4599 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4600 return RewriteObjCSynchronizedStmt(StmtTry);
4601
4602 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4603 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump11289f42009-09-09 15:08:12 +00004604
Steve Narofff4b992a2008-10-28 20:29:00 +00004605 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4606 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump11289f42009-09-09 15:08:12 +00004607
4608 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofff4b992a2008-10-28 20:29:00 +00004609 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump11289f42009-09-09 15:08:12 +00004610 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofff4b992a2008-10-28 20:29:00 +00004611 OrigStmtRange.getEnd());
4612 if (BreakStmt *StmtBreakStmt =
4613 dyn_cast<BreakStmt>(S))
4614 return RewriteBreakStmt(StmtBreakStmt);
4615 if (ContinueStmt *StmtContinueStmt =
4616 dyn_cast<ContinueStmt>(S))
4617 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump11289f42009-09-09 15:08:12 +00004618
4619 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofff4b992a2008-10-28 20:29:00 +00004620 // and cast exprs.
4621 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4622 // FIXME: What we're doing here is modifying the type-specifier that
4623 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump11289f42009-09-09 15:08:12 +00004624 // a separate type-specifier that we can rewrite.
Steve Naroffe70a52a2009-12-05 15:55:59 +00004625 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4626 // the context of an ObjCForCollectionStmt. For example:
4627 // NSArray *someArray;
4628 // for (id <FooProtocol> index in someArray) ;
4629 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4630 // and it depends on the original text locations/positions.
Benjamin Krameracc5fa12009-12-05 22:16:51 +00004631 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroffe70a52a2009-12-05 15:55:59 +00004632 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump11289f42009-09-09 15:08:12 +00004633
Steve Narofff4b992a2008-10-28 20:29:00 +00004634 // Blocks rewrite rules.
4635 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4636 DI != DE; ++DI) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004637 Decl *SD = *DI;
Steve Narofff4b992a2008-10-28 20:29:00 +00004638 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004639 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004640 RewriteBlockPointerDecl(ND);
Mike Stump11289f42009-09-09 15:08:12 +00004641 else if (ND->getType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004642 CheckFunctionPointerDecl(ND->getType(), ND);
4643 }
4644 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004645 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004646 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00004647 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004648 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4649 }
4650 }
4651 }
Mike Stump11289f42009-09-09 15:08:12 +00004652
Steve Narofff4b992a2008-10-28 20:29:00 +00004653 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4654 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump11289f42009-09-09 15:08:12 +00004655
4656 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004657 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4658 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump11289f42009-09-09 15:08:12 +00004659 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4660 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004661 && "Statement stack mismatch");
4662 Stmts.pop_back();
4663 }
4664 // Handle blocks rewriting.
4665 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4666 if (BDRE->isByRef())
Steve Naroffd9803712009-04-29 16:37:50 +00004667 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofff4b992a2008-10-28 20:29:00 +00004668 }
4669 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff350b6652008-10-30 10:07:53 +00004670 if (CE->getCallee()->getType()->isBlockPointerType()) {
4671 Stmt *BlockCall = SynthesizeBlockCall(CE);
4672 ReplaceStmt(S, BlockCall);
4673 return BlockCall;
4674 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004675 }
Steve Naroffc989a7b2008-11-03 23:29:32 +00004676 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004677 RewriteCastExpr(CE);
4678 }
4679#if 0
4680 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek5a201952009-02-07 01:47:29 +00004681 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004682 // Get the new text.
4683 std::string SStr;
4684 llvm::raw_string_ostream Buf(SStr);
Eli Friedman0905f142009-05-30 05:19:26 +00004685 Replacement->printPretty(Buf, *Context);
Steve Narofff4b992a2008-10-28 20:29:00 +00004686 const std::string &Str = Buf.str();
4687
4688 printf("CAST = %s\n", &Str[0]);
4689 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4690 delete S;
4691 return Replacement;
4692 }
4693#endif
4694 // Return this stmt unmodified.
4695 return S;
4696}
4697
Steve Naroffe70a52a2009-12-05 15:55:59 +00004698void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
4699 for (RecordDecl::field_iterator i = RD->field_begin(),
4700 e = RD->field_end(); i != e; ++i) {
4701 FieldDecl *FD = *i;
4702 if (isTopLevelBlockPointerType(FD->getType()))
4703 RewriteBlockPointerDecl(FD);
4704 if (FD->getType()->isObjCQualifiedIdType() ||
4705 FD->getType()->isObjCQualifiedInterfaceType())
4706 RewriteObjCQualifiedInterfaceTypes(FD);
4707 }
4708}
4709
Steve Narofff4b992a2008-10-28 20:29:00 +00004710/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4711/// main file of the input.
4712void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4713 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffb1368882008-12-17 00:20:22 +00004714 if (FD->isOverloadedOperator())
4715 return;
Mike Stump11289f42009-09-09 15:08:12 +00004716
Steve Narofff4b992a2008-10-28 20:29:00 +00004717 // Since function prototypes don't have ParmDecl's, we check the function
4718 // prototype. This enables us to rewrite function declarations and
4719 // definitions using the same code.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004720 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofff4b992a2008-10-28 20:29:00 +00004721
Sebastian Redla7b98a72009-04-26 20:35:05 +00004722 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00004723 if (CompoundStmt *Body = FD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004724 CurFunctionDef = FD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00004725 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00004726 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00004727 Body =
4728 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4729 FD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00004730 CurrentBody = 0;
4731 if (PropParentMap) {
4732 delete PropParentMap;
4733 PropParentMap = 0;
4734 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004735 // This synthesizes and inserts the block "impl" struct, invoke function,
4736 // and any copy/dispose helper functions.
4737 InsertBlockLiteralsWithinFunction(FD);
4738 CurFunctionDef = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004739 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004740 return;
4741 }
4742 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00004743 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004744 CurMethodDef = MD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00004745 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00004746 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00004747 Body =
4748 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4749 MD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00004750 CurrentBody = 0;
4751 if (PropParentMap) {
4752 delete PropParentMap;
4753 PropParentMap = 0;
4754 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004755 InsertBlockLiteralsWithinMethod(MD);
4756 CurMethodDef = 0;
4757 }
4758 }
4759 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
4760 ClassImplementation.push_back(CI);
4761 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4762 CategoryImplementation.push_back(CI);
4763 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4764 RewriteForwardClassDecl(CD);
4765 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4766 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroffa5c0db82008-12-11 21:05:33 +00004767 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004768 RewriteBlockPointerDecl(VD);
Steve Naroffd8907b72008-10-29 18:15:37 +00004769 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004770 CheckFunctionPointerDecl(VD->getType(), VD);
4771 if (VD->getInit()) {
Steve Naroffc989a7b2008-11-03 23:29:32 +00004772 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004773 RewriteCastExpr(CE);
4774 }
4775 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00004776 } else if (VD->getType()->isRecordType()) {
4777 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4778 if (RD->isDefinition())
4779 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00004780 }
Steve Naroffd8907b72008-10-29 18:15:37 +00004781 if (VD->getInit()) {
4782 GlobalVarDecl = VD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00004783 CollectPropertySetters(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00004784 CurrentBody = VD->getInit();
Steve Naroffd8907b72008-10-29 18:15:37 +00004785 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00004786 CurrentBody = 0;
4787 if (PropParentMap) {
4788 delete PropParentMap;
4789 PropParentMap = 0;
4790 }
Mike Stump11289f42009-09-09 15:08:12 +00004791 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner86d7d912008-11-24 03:54:41 +00004792 VD->getNameAsCString());
Steve Naroffd8907b72008-10-29 18:15:37 +00004793 GlobalVarDecl = 0;
4794
4795 // This is needed for blocks.
Steve Naroffc989a7b2008-11-03 23:29:32 +00004796 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroffd8907b72008-10-29 18:15:37 +00004797 RewriteCastExpr(CE);
4798 }
4799 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004800 return;
4801 }
4802 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004803 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004804 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00004805 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004806 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Steve Naroffe70a52a2009-12-05 15:55:59 +00004807 else if (TD->getUnderlyingType()->isRecordType()) {
4808 RecordDecl *RD = TD->getUnderlyingType()->getAs<RecordType>()->getDecl();
4809 if (RD->isDefinition())
4810 RewriteRecordBody(RD);
4811 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004812 return;
4813 }
4814 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroffe70a52a2009-12-05 15:55:59 +00004815 if (RD->isDefinition())
4816 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00004817 return;
4818 }
4819 // Nothing yet.
4820}
4821
Chris Lattnercf169832009-03-28 04:11:33 +00004822void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004823 // Get the top-level buffer that this corresponds to.
Mike Stump11289f42009-09-09 15:08:12 +00004824
Steve Narofff4b992a2008-10-28 20:29:00 +00004825 // Rewrite tabs if we care.
4826 //RewriteTabs();
Mike Stump11289f42009-09-09 15:08:12 +00004827
Steve Narofff4b992a2008-10-28 20:29:00 +00004828 if (Diags.hasErrorOccurred())
4829 return;
Mike Stump11289f42009-09-09 15:08:12 +00004830
Steve Narofff4b992a2008-10-28 20:29:00 +00004831 RewriteInclude();
Mike Stump11289f42009-09-09 15:08:12 +00004832
Steve Naroffd9803712009-04-29 16:37:50 +00004833 // Here's a great place to add any extra declarations that may be needed.
4834 // Write out meta data for each @protocol(<expr>).
Mike Stump11289f42009-09-09 15:08:12 +00004835 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00004836 E = ProtocolExprDecls.end(); I != E; ++I)
4837 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
4838
Mike Stump11289f42009-09-09 15:08:12 +00004839 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Narofff4b992a2008-10-28 20:29:00 +00004840 Preamble.c_str(), Preamble.size(), false);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00004841 if (ClassImplementation.size() || CategoryImplementation.size())
4842 RewriteImplementations();
Steve Naroffd9803712009-04-29 16:37:50 +00004843
Steve Narofff4b992a2008-10-28 20:29:00 +00004844 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4845 // we are done.
Mike Stump11289f42009-09-09 15:08:12 +00004846 if (const RewriteBuffer *RewriteBuf =
Steve Narofff4b992a2008-10-28 20:29:00 +00004847 Rewrite.getRewriteBufferFor(MainFileID)) {
4848 //printf("Changed:\n");
4849 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4850 } else {
4851 fprintf(stderr, "No changes\n");
4852 }
Steve Narofff8cfd162008-11-13 20:07:04 +00004853
Steve Naroffd9803712009-04-29 16:37:50 +00004854 if (ClassImplementation.size() || CategoryImplementation.size() ||
4855 ProtocolExprDecls.size()) {
Steve Naroff2a2a41f2008-11-14 14:10:01 +00004856 // Rewrite Objective-c meta data*
4857 std::string ResultStr;
4858 SynthesizeMetaDataIntoBuffer(ResultStr);
4859 // Emit metadata.
4860 *OutFile << ResultStr;
4861 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004862 OutFile->flush();
4863}
4864