blob: 08b54b222248867e7429b4a48724944a961b3418 [file] [log] [blame]
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattnere99c8322007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnere99c8322007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Eli Friedman9f30fc32009-05-18 22:50:54 +000014#include "clang/Frontend/ASTConsumers.h"
Chris Lattner16a0de42007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattnere99c8322007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Steve Naroff1042ff32008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.h"
Chris Lattner16a0de42007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner4431a1b2007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattnerf3a59a12007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Benjamin Kramer89b422c2009-08-23 12:08:50 +000023#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
Chris Lattner211f8b82007-10-25 17:07:24 +000025#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian99e96b02007-10-26 19:46:17 +000026#include "llvm/ADT/SmallPtrSet.h"
Ted Kremenek2d470fc2008-09-13 05:16:45 +000027#include "llvm/ADT/OwningPtr.h"
Chris Lattnere99c8322007-10-11 00:43:27 +000028using namespace clang;
Chris Lattner211f8b82007-10-25 17:07:24 +000029using llvm::utostr;
Chris Lattnere99c8322007-10-11 00:43:27 +000030
Chris Lattnere99c8322007-10-11 00:43:27 +000031namespace {
Steve Naroff1dc53ef2008-04-14 22:03:09 +000032 class RewriteObjC : public ASTConsumer {
Chris Lattner0bd1c972007-10-16 21:07:07 +000033 Rewriter Rewrite;
Chris Lattnere9c810c2007-11-30 22:25:36 +000034 Diagnostic &Diags;
Steve Naroff945a3b12008-03-10 20:43:59 +000035 const LangOptions &LangOpts;
Steve Naroff7b3579b2008-01-30 19:17:43 +000036 unsigned RewriteFailedDiag;
Steve Naroff6d6da252008-12-05 17:03:39 +000037 unsigned TryFinallyContainsReturnDiag;
Mike Stump11289f42009-09-09 15:08:12 +000038
Chris Lattnerc6d91c02007-10-17 22:35:30 +000039 ASTContext *Context;
Chris Lattnere99c8322007-10-11 00:43:27 +000040 SourceManager *SM;
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +000041 TranslationUnitDecl *TUDecl;
Chris Lattnerd32480d2009-01-17 06:22:33 +000042 FileID MainFileID;
Chris Lattnerf3a59a12007-12-02 01:13:47 +000043 const char *MainFileStart, *MainFileEnd;
Chris Lattner0bd1c972007-10-16 21:07:07 +000044 SourceLocation LastIncLoc;
Mike Stump11289f42009-09-09 15:08:12 +000045
Ted Kremenek1b0ea822008-01-07 19:49:32 +000046 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
47 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
48 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Naroff13e74872008-05-06 18:26:51 +000049 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremenek1b0ea822008-01-07 19:49:32 +000050 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
51 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +000052 llvm::SmallVector<Stmt *, 32> Stmts;
53 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffd9803712009-04-29 16:37:50 +000054 // Remember all the @protocol(<expr>) expressions.
55 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Mike Stump11289f42009-09-09 15:08:12 +000056
Steve Naroffce8e8862008-03-15 00:55:56 +000057 unsigned NumObjCStringLiterals;
Mike Stump11289f42009-09-09 15:08:12 +000058
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000059 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff7fa2f042007-11-15 10:28:18 +000060 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +000061 FunctionDecl *MsgSendStretFunctionDecl;
62 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanian4f76f222007-12-03 21:26:48 +000063 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000064 FunctionDecl *GetClassFunctionDecl;
Steve Naroffb2f8ff12007-12-07 03:50:46 +000065 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff574440f2007-10-24 22:48:43 +000066 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff265a6b92007-11-08 14:30:50 +000067 FunctionDecl *CFStringFunctionDecl;
Steve Naroff17978c42008-03-11 17:37:02 +000068 FunctionDecl *SuperContructorFunctionDecl;
Mike Stump11289f42009-09-09 15:08:12 +000069
Steve Naroffa397efd2007-11-03 11:27:19 +000070 // ObjC string constant support.
Steve Naroff08899ff2008-04-15 22:42:06 +000071 VarDecl *ConstantStringClassReference;
Steve Naroffa397efd2007-11-03 11:27:19 +000072 RecordDecl *NSStringRecord;
Mike Stump11289f42009-09-09 15:08:12 +000073
Fariborz Jahanian19d42bf2008-01-16 00:09:11 +000074 // ObjC foreach break/continue generation support.
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +000075 int BcLabelCount;
Mike Stump11289f42009-09-09 15:08:12 +000076
Steve Naroff7fa2f042007-11-15 10:28:18 +000077 // Needed for super.
Steve Naroff677ab3a2008-10-27 17:20:55 +000078 ObjCMethodDecl *CurMethodDef;
Steve Naroff7fa2f042007-11-15 10:28:18 +000079 RecordDecl *SuperStructDecl;
Steve Naroffce8e8862008-03-15 00:55:56 +000080 RecordDecl *ConstantStringDecl;
Mike Stump11289f42009-09-09 15:08:12 +000081
Steve Naroffd9803712009-04-29 16:37:50 +000082 TypeDecl *ProtocolTypeDecl;
83 QualType getProtocolType();
Mike Stump11289f42009-09-09 15:08:12 +000084
Fariborz Jahanian159ee392008-01-18 01:15:54 +000085 // Needed for header files being rewritten
86 bool IsHeader;
Mike Stump11289f42009-09-09 15:08:12 +000087
Steve Narofff9e7c902008-03-28 22:26:09 +000088 std::string InFileName;
Eli Friedman94cf21e2009-05-18 22:20:00 +000089 llvm::raw_ostream* OutFile;
Eli Friedmanf22439a2009-05-18 22:39:16 +000090
91 bool SilenceRewriteMacroWarning;
92
Steve Naroff00a31762008-03-27 22:29:16 +000093 std::string Preamble;
Steve Naroff677ab3a2008-10-27 17:20:55 +000094
95 // Block expressions.
96 llvm::SmallVector<BlockExpr *, 32> Blocks;
97 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
98 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Mike Stump11289f42009-09-09 15:08:12 +000099
Steve Naroff677ab3a2008-10-27 17:20:55 +0000100 // Block related declarations.
101 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
102 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
103 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
104
105 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
106
Steve Naroff4588d0f2008-12-04 16:24:46 +0000107 // This maps a property to it's assignment statement.
108 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Naroff1042ff32008-12-08 16:43:47 +0000109 // This maps a property to it's synthesied message expression.
110 // This allows us to rewrite chained getters (e.g. o.a.b.c).
111 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
Mike Stump11289f42009-09-09 15:08:12 +0000112
Steve Naroff22216db2008-12-04 23:50:32 +0000113 // This maps an original source AST to it's rewritten form. This allows
114 // us to avoid rewriting the same node twice (which is very uncommon).
115 // This is needed to support some of the exotic property rewriting.
116 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Narofff326f402008-12-03 00:56:33 +0000117
Steve Naroff677ab3a2008-10-27 17:20:55 +0000118 FunctionDecl *CurFunctionDef;
Steve Naroffd8907b72008-10-29 18:15:37 +0000119 VarDecl *GlobalVarDecl;
Mike Stump11289f42009-09-09 15:08:12 +0000120
Steve Naroff08628db2008-12-09 12:56:34 +0000121 bool DisableReplaceStmt;
Mike Stump11289f42009-09-09 15:08:12 +0000122
Fariborz Jahanian93191af2007-10-18 19:23:00 +0000123 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnere99c8322007-10-11 00:43:27 +0000124 public:
Ted Kremenek380df932008-05-31 20:11:04 +0000125 virtual void Initialize(ASTContext &context);
126
Chris Lattner3c799d72007-10-24 17:06:59 +0000127 // Top Level Driver code.
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000128 virtual void HandleTopLevelDecl(DeclGroupRef D) {
129 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
130 HandleTopLevelSingleDecl(*I);
131 }
132 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000133 void HandleDeclInMainFile(Decl *D);
Eli Friedman94cf21e2009-05-18 22:20:00 +0000134 RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000135 Diagnostic &D, const LangOptions &LOpts,
136 bool silenceMacroWarn);
Ted Kremenek6231e7e2008-08-08 04:15:52 +0000137
138 ~RewriteObjC() {}
Mike Stump11289f42009-09-09 15:08:12 +0000139
Chris Lattnercf169832009-03-28 04:11:33 +0000140 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump11289f42009-09-09 15:08:12 +0000141
Chris Lattner2e0d2602008-01-31 19:37:57 +0000142 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff22216db2008-12-04 23:50:32 +0000143 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump11289f42009-09-09 15:08:12 +0000144
Steve Naroff22216db2008-12-04 23:50:32 +0000145 if (ReplacingStmt)
146 return; // We can't rewrite the same node twice.
Chris Lattner2e0d2602008-01-31 19:37:57 +0000147
Steve Naroff08628db2008-12-09 12:56:34 +0000148 if (DisableReplaceStmt)
149 return; // Used when rewriting the assignment of a property setter.
150
Steve Naroff22216db2008-12-04 23:50:32 +0000151 // If replacement succeeded or warning disabled return with no warning.
152 if (!Rewrite.ReplaceStmt(Old, New)) {
153 ReplacedNodes[Old] = New;
154 return;
155 }
156 if (SilenceRewriteMacroWarning)
157 return;
Chris Lattner8488c822008-11-18 07:04:44 +0000158 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
159 << Old->getSourceRange();
Chris Lattner2e0d2602008-01-31 19:37:57 +0000160 }
Steve Naroff08628db2008-12-09 12:56:34 +0000161
162 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
163 // Measaure the old text.
164 int Size = Rewrite.getRangeSize(SrcRange);
165 if (Size == -1) {
166 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
167 << Old->getSourceRange();
168 return;
169 }
170 // Get the new text.
171 std::string SStr;
172 llvm::raw_string_ostream S(SStr);
Chris Lattnerc61089a2009-06-30 01:26:17 +0000173 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroff08628db2008-12-09 12:56:34 +0000174 const std::string &Str = S.str();
175
176 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000177 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroff08628db2008-12-09 12:56:34 +0000178 ReplacedNodes[Old] = New;
179 return;
180 }
181 if (SilenceRewriteMacroWarning)
182 return;
183 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
184 << Old->getSourceRange();
185 }
186
Steve Naroff00a31762008-03-27 22:29:16 +0000187 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
188 bool InsertAfter = true) {
Chris Lattner9cc55f52008-01-31 19:51:04 +0000189 // If insertion succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000190 if (!Rewrite.InsertText(Loc, llvm::StringRef(StrData, StrLen),
191 InsertAfter) ||
Chris Lattner1780a852008-01-31 19:42:41 +0000192 SilenceRewriteMacroWarning)
193 return;
Mike Stump11289f42009-09-09 15:08:12 +0000194
Chris Lattner1780a852008-01-31 19:42:41 +0000195 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
196 }
Mike Stump11289f42009-09-09 15:08:12 +0000197
Chris Lattner9cc55f52008-01-31 19:51:04 +0000198 void RemoveText(SourceLocation Loc, unsigned StrLen) {
199 // If removal succeeded or warning disabled return with no warning.
200 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
201 return;
Mike Stump11289f42009-09-09 15:08:12 +0000202
Chris Lattner9cc55f52008-01-31 19:51:04 +0000203 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
204 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000205
Chris Lattner9cc55f52008-01-31 19:51:04 +0000206 void ReplaceText(SourceLocation Start, unsigned OrigLength,
207 const char *NewStr, unsigned NewLength) {
208 // If removal succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000209 if (!Rewrite.ReplaceText(Start, OrigLength,
210 llvm::StringRef(NewStr, NewLength)) ||
Chris Lattner9cc55f52008-01-31 19:51:04 +0000211 SilenceRewriteMacroWarning)
212 return;
Mike Stump11289f42009-09-09 15:08:12 +0000213
Chris Lattner9cc55f52008-01-31 19:51:04 +0000214 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
215 }
Mike Stump11289f42009-09-09 15:08:12 +0000216
Chris Lattner3c799d72007-10-24 17:06:59 +0000217 // Syntactic Rewriting.
Steve Narofff36987c2007-11-04 22:37:50 +0000218 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000219 void RewriteInclude();
Chris Lattner3c799d72007-10-24 17:06:59 +0000220 void RewriteTabs();
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000221 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffc038b3a2008-12-02 17:36:43 +0000222 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
223 ObjCImplementationDecl *IMD,
224 ObjCCategoryImplDecl *CID);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000225 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000226 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000227 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
228 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
229 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
230 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
231 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000232 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000233 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000234 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff873bd842008-07-29 18:15:38 +0000235 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroff50d42052007-11-01 13:24:47 +0000236 bool needToScanForQualifiers(QualType T);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000237 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff7fa2f042007-11-15 10:28:18 +0000238 QualType getSuperStructType();
Steve Naroffce8e8862008-03-15 00:55:56 +0000239 QualType getConstantStringStructType();
Steve Naroffcd92aeb2008-05-31 14:15:04 +0000240 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump11289f42009-09-09 15:08:12 +0000241
Chris Lattner3c799d72007-10-24 17:06:59 +0000242 // Expression Rewriting.
Steve Naroff20113382007-11-09 15:20:18 +0000243 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroff4588d0f2008-12-04 16:24:46 +0000244 void CollectPropertySetters(Stmt *S);
Mike Stump11289f42009-09-09 15:08:12 +0000245
Steve Naroff1042ff32008-12-08 16:43:47 +0000246 Stmt *CurrentBody;
247 ParentMap *PropParentMap; // created lazily.
Mike Stump11289f42009-09-09 15:08:12 +0000248
Chris Lattner69534692007-10-24 16:57:36 +0000249 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner37f5b7d2008-05-23 20:40:52 +0000250 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroff4588d0f2008-12-04 16:24:46 +0000251 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Mike Stump11289f42009-09-09 15:08:12 +0000252 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroff08628db2008-12-09 12:56:34 +0000253 SourceRange SrcRange);
Steve Naroffe4f9b232007-11-05 14:50:49 +0000254 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner69534692007-10-24 16:57:36 +0000255 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffa397efd2007-11-03 11:27:19 +0000256 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian33c0e812007-12-07 18:47:10 +0000257 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffec60b432009-12-05 21:43:12 +0000258 void WarnAboutReturnGotoStmts(Stmt *S);
259 void HasReturnStmts(Stmt *S, bool &hasReturns);
260 void RewriteTryReturnStmts(Stmt *S);
261 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000262 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian284011b2008-01-29 22:59:37 +0000263 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000264 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
265 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
266 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattnera779d692008-01-31 05:10:40 +0000267 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
268 SourceLocation OrigEnd);
Mike Stump11289f42009-09-09 15:08:12 +0000269 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Steve Naroff574440f2007-10-24 22:48:43 +0000270 Expr **args, unsigned nargs);
Fariborz Jahanian965a8962008-01-08 22:06:28 +0000271 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +0000272 Stmt *RewriteBreakStmt(BreakStmt *S);
273 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian965a8962008-01-08 22:06:28 +0000274 void SynthCountByEnumWithState(std::string &buf);
Mike Stump11289f42009-09-09 15:08:12 +0000275
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000276 void SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +0000277 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000278 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +0000279 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000280 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000281 void SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +0000282 void SynthGetMetaClassFunctionDecl();
Fariborz Jahanian31e18502007-12-04 21:47:40 +0000283 void SynthSelGetUidFunctionDecl();
Steve Naroff17978c42008-03-11 17:37:02 +0000284 void SynthSuperContructorFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000285
Chris Lattner3c799d72007-10-24 17:06:59 +0000286 // Metadata emission.
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000287 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000288 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000289
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000290 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000291 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000292
Douglas Gregor29bd76f2009-04-23 01:02:12 +0000293 template<typename MethodIterator>
294 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
295 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +0000296 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +0000297 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +0000298 const char *ClassName,
299 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000300
Steve Naroffd9803712009-04-29 16:37:50 +0000301 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
302 const char *prefix,
303 const char *ClassName,
304 std::string &Result);
305 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Mike Stump11289f42009-09-09 15:08:12 +0000306 const char *prefix,
Steve Naroffd9803712009-04-29 16:37:50 +0000307 const char *ClassName,
308 std::string &Result);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000309 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000310 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000311 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
312 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000313 std::string &Result);
Steve Narofff8cfd162008-11-13 20:07:04 +0000314 void RewriteImplementations();
315 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000316
Steve Naroff677ab3a2008-10-27 17:20:55 +0000317 // Block rewriting.
Mike Stump11289f42009-09-09 15:08:12 +0000318 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000319 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump11289f42009-09-09 15:08:12 +0000320
Steve Naroff677ab3a2008-10-27 17:20:55 +0000321 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
322 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump11289f42009-09-09 15:08:12 +0000323
324 // Block specific rewrite rules.
Steve Naroff677ab3a2008-10-27 17:20:55 +0000325 void RewriteBlockCall(CallExpr *Exp);
326 void RewriteBlockPointerDecl(NamedDecl *VD);
Steve Naroffd9803712009-04-29 16:37:50 +0000327 Stmt *RewriteBlockDeclRefExpr(BlockDeclRefExpr *VD);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000328 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump11289f42009-09-09 15:08:12 +0000329
330 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Steve Naroff677ab3a2008-10-27 17:20:55 +0000331 const char *funcName, std::string Tag);
Mike Stump11289f42009-09-09 15:08:12 +0000332 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Steve Naroff677ab3a2008-10-27 17:20:55 +0000333 const char *funcName, std::string Tag);
Mike Stump11289f42009-09-09 15:08:12 +0000334 std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
Steve Naroff677ab3a2008-10-27 17:20:55 +0000335 bool hasCopyDisposeHelpers);
Steve Naroff350b6652008-10-30 10:07:53 +0000336 Stmt *SynthesizeBlockCall(CallExpr *Exp);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000337 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
338 const char *FunName);
Steve Naroffe70a52a2009-12-05 15:55:59 +0000339 void RewriteRecordBody(RecordDecl *RD);
Mike Stump11289f42009-09-09 15:08:12 +0000340
Steve Naroff677ab3a2008-10-27 17:20:55 +0000341 void CollectBlockDeclRefInfo(BlockExpr *Exp);
342 void GetBlockCallExprs(Stmt *S);
343 void GetBlockDeclRefExprs(Stmt *S);
Mike Stump11289f42009-09-09 15:08:12 +0000344
Steve Naroff677ab3a2008-10-27 17:20:55 +0000345 // We avoid calling Type::isBlockPointerType(), since it operates on the
346 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek5a201952009-02-07 01:47:29 +0000347 bool isTopLevelBlockPointerType(QualType T) {
348 return isa<BlockPointerType>(T);
349 }
Mike Stump11289f42009-09-09 15:08:12 +0000350
Steve Naroff677ab3a2008-10-27 17:20:55 +0000351 // FIXME: This predicate seems like it would be useful to add to ASTContext.
352 bool isObjCType(QualType T) {
353 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
354 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000355
Steve Naroff677ab3a2008-10-27 17:20:55 +0000356 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000357
Steve Naroff677ab3a2008-10-27 17:20:55 +0000358 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
359 OCT == Context->getCanonicalType(Context->getObjCClassType()))
360 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000361
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000362 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +0000363 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Narofffb4330f2009-06-17 22:40:22 +0000364 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff677ab3a2008-10-27 17:20:55 +0000365 return true;
366 }
367 return false;
368 }
369 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek5a201952009-02-07 01:47:29 +0000370 void GetExtentOfArgList(const char *Name, const char *&LParen,
371 const char *&RParen);
Steve Naroffc989a7b2008-11-03 23:29:32 +0000372 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump11289f42009-09-09 15:08:12 +0000373
Steve Narofff4b992a2008-10-28 20:29:00 +0000374 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroffd8907b72008-10-29 18:15:37 +0000375 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Mike Stump11289f42009-09-09 15:08:12 +0000376
Steve Naroffd9803712009-04-29 16:37:50 +0000377 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump11289f42009-09-09 15:08:12 +0000378 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroffd9803712009-04-29 16:37:50 +0000379 if (From[i] == '"')
380 To += "\\\"";
381 else
382 To += From[i];
383 }
384 }
Chris Lattnere99c8322007-10-11 00:43:27 +0000385 };
386}
387
Mike Stump11289f42009-09-09 15:08:12 +0000388void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
389 NamedDecl *D) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000390 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000391 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +0000392 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +0000393 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +0000394 // All the args are checked/rewritten. Don't call twice!
395 RewriteBlockPointerDecl(D);
396 break;
397 }
398 }
399}
400
401void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000402 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +0000403 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000404 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000405}
406
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000407static bool IsHeaderFile(const std::string &Filename) {
408 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump11289f42009-09-09 15:08:12 +0000409
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000410 if (DotPos == std::string::npos) {
411 // no file extension
Mike Stump11289f42009-09-09 15:08:12 +0000412 return false;
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000413 }
Mike Stump11289f42009-09-09 15:08:12 +0000414
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000415 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
416 // C header: .h
417 // C++ header: .hh or .H;
418 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump11289f42009-09-09 15:08:12 +0000419}
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000420
Eli Friedman94cf21e2009-05-18 22:20:00 +0000421RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000422 Diagnostic &D, const LangOptions &LOpts,
423 bool silenceMacroWarn)
424 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
425 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Narofff9e7c902008-03-28 22:26:09 +0000426 IsHeader = IsHeaderFile(inFile);
Mike Stump11289f42009-09-09 15:08:12 +0000427 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Narofff9e7c902008-03-28 22:26:09 +0000428 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump11289f42009-09-09 15:08:12 +0000429 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek5a201952009-02-07 01:47:29 +0000430 "rewriter doesn't support user-specified control flow semantics "
431 "for @try/@finally (code may not execute properly)");
Steve Narofff9e7c902008-03-28 22:26:09 +0000432}
433
Eli Friedmana63ab2d2009-05-18 22:29:17 +0000434ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
435 llvm::raw_ostream* OS,
Mike Stump11289f42009-09-09 15:08:12 +0000436 Diagnostic &Diags,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000437 const LangOptions &LOpts,
438 bool SilenceRewriteMacroWarning) {
439 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere9c810c2007-11-30 22:25:36 +0000440}
Chris Lattnere99c8322007-10-11 00:43:27 +0000441
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000442void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner187f6262008-01-31 19:38:44 +0000443 Context = &context;
444 SM = &Context->getSourceManager();
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +0000445 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner187f6262008-01-31 19:38:44 +0000446 MsgSendFunctionDecl = 0;
447 MsgSendSuperFunctionDecl = 0;
448 MsgSendStretFunctionDecl = 0;
449 MsgSendSuperStretFunctionDecl = 0;
450 MsgSendFpretFunctionDecl = 0;
451 GetClassFunctionDecl = 0;
452 GetMetaClassFunctionDecl = 0;
453 SelGetUidFunctionDecl = 0;
454 CFStringFunctionDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000455 ConstantStringClassReference = 0;
456 NSStringRecord = 0;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000457 CurMethodDef = 0;
458 CurFunctionDef = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000459 GlobalVarDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000460 SuperStructDecl = 0;
Steve Naroffd9803712009-04-29 16:37:50 +0000461 ProtocolTypeDecl = 0;
Steve Naroff60a9ef62008-03-27 22:59:54 +0000462 ConstantStringDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000463 BcLabelCount = 0;
Steve Naroff17978c42008-03-11 17:37:02 +0000464 SuperContructorFunctionDecl = 0;
Steve Naroffce8e8862008-03-15 00:55:56 +0000465 NumObjCStringLiterals = 0;
Steve Narofff1ab6002008-12-08 20:01:41 +0000466 PropParentMap = 0;
467 CurrentBody = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000468 DisableReplaceStmt = false;
Mike Stump11289f42009-09-09 15:08:12 +0000469
Chris Lattner187f6262008-01-31 19:38:44 +0000470 // Get the ID and start/end of the main file.
471 MainFileID = SM->getMainFileID();
472 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
473 MainFileStart = MainBuf->getBufferStart();
474 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000475
Chris Lattner184e65d2009-04-14 23:22:57 +0000476 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump11289f42009-09-09 15:08:12 +0000477
Chris Lattner187f6262008-01-31 19:38:44 +0000478 // declaring objc_selector outside the parameter list removes a silly
479 // scope related warning...
Steve Naroff00a31762008-03-27 22:29:16 +0000480 if (IsHeader)
Steve Narofffcc6fd52009-02-03 20:39:18 +0000481 Preamble = "#pragma once\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000482 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff6ab6dc72008-12-23 20:11:22 +0000483 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroff00a31762008-03-27 22:29:16 +0000484 Preamble += "struct objc_object *superClass; ";
Steve Naroff17978c42008-03-11 17:37:02 +0000485 if (LangOpts.Microsoft) {
486 // Add a constructor for creating temporary objects.
Ted Kremenek5a201952009-02-07 01:47:29 +0000487 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
488 ": ";
Steve Naroff00a31762008-03-27 22:29:16 +0000489 Preamble += "object(o), superClass(s) {} ";
Steve Naroff17978c42008-03-11 17:37:02 +0000490 }
Steve Naroff00a31762008-03-27 22:29:16 +0000491 Preamble += "};\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000492 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
493 Preamble += "typedef struct objc_object Protocol;\n";
494 Preamble += "#define _REWRITER_typedef_Protocol\n";
495 Preamble += "#endif\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000496 if (LangOpts.Microsoft) {
497 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
498 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
499 } else
500 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
501 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroff00a31762008-03-27 22:29:16 +0000502 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000503 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroff00a31762008-03-27 22:29:16 +0000504 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000505 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000506 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000507 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000508 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000509 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroff00a31762008-03-27 22:29:16 +0000510 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000511 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000512 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000513 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000514 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000515 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
516 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
517 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
518 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
519 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroffd30f8c52008-05-09 21:17:56 +0000520 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff8dd15252008-07-16 18:58:11 +0000521 // @synchronized hooks.
Steve Narofff122ff02008-12-08 17:30:33 +0000522 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
523 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
524 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000525 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
526 Preamble += "struct __objcFastEnumerationState {\n\t";
527 Preamble += "unsigned long state;\n\t";
Steve Naroff4dbab8a2008-04-04 22:58:22 +0000528 Preamble += "void **itemsPtr;\n\t";
Steve Naroff00a31762008-03-27 22:29:16 +0000529 Preamble += "unsigned long *mutationsPtr;\n\t";
530 Preamble += "unsigned long extra[5];\n};\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000531 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000532 Preamble += "#define __FASTENUMERATIONSTATE\n";
533 Preamble += "#endif\n";
534 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
535 Preamble += "struct __NSConstantStringImpl {\n";
536 Preamble += " int *isa;\n";
537 Preamble += " int flags;\n";
538 Preamble += " char *str;\n";
539 Preamble += " long length;\n";
540 Preamble += "};\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000541 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
542 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
543 Preamble += "#else\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000544 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000545 Preamble += "#endif\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000546 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
547 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000548 // Blocks preamble.
549 Preamble += "#ifndef BLOCK_IMPL\n";
550 Preamble += "#define BLOCK_IMPL\n";
551 Preamble += "struct __block_impl {\n";
552 Preamble += " void *isa;\n";
553 Preamble += " int Flags;\n";
554 Preamble += " int Size;\n";
555 Preamble += " void *FuncPtr;\n";
556 Preamble += "};\n";
Steve Naroff61d879e2008-12-16 15:50:30 +0000557 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
558 Preamble += "__OBJC_RW_STATICIMPORT void _Block_object_assign(void *, const void *, const int);\n";
559 Preamble += "__OBJC_RW_STATICIMPORT void _Block_object_dispose(const void *, const int);\n";
560 Preamble += "__OBJC_RW_STATICIMPORT void *_NSConcreteGlobalBlock[32];\n";
561 Preamble += "__OBJC_RW_STATICIMPORT void *_NSConcreteStackBlock[32];\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000562 Preamble += "#endif\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000563 if (LangOpts.Microsoft) {
Steve Narofff122ff02008-12-08 17:30:33 +0000564 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
565 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000566 Preamble += "#define __attribute__(X)\n";
567 }
Chris Lattner187f6262008-01-31 19:38:44 +0000568}
569
570
Chris Lattner3c799d72007-10-24 17:06:59 +0000571//===----------------------------------------------------------------------===//
572// Top Level Driver Code
573//===----------------------------------------------------------------------===//
574
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000575void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Chris Lattner0bd1c972007-10-16 21:07:07 +0000576 // Two cases: either the decl could be in the main file, or it could be in a
577 // #included file. If the former, rewrite it now. If the later, check to see
578 // if we rewrote the #include/#import.
579 SourceLocation Loc = D->getLocation();
Chris Lattner8a425862009-01-16 07:36:28 +0000580 Loc = SM->getInstantiationLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000581
Chris Lattner0bd1c972007-10-16 21:07:07 +0000582 // If this is for a builtin, ignore it.
583 if (Loc.isInvalid()) return;
584
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000585 // Look for built-in declarations that we need to refer during the rewrite.
586 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000587 RewriteFunctionDecl(FD);
Steve Naroff08899ff2008-04-15 22:42:06 +0000588 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000589 // declared in <Foundation/NSString.h>
Chris Lattner86d7d912008-11-24 03:54:41 +0000590 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000591 ConstantStringClassReference = FVD;
592 return;
593 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000594 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff161a92b2007-10-26 20:53:56 +0000595 RewriteInterfaceDecl(MD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000596 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000597 RewriteCategoryDecl(CD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000598 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff921385f2007-10-30 16:42:30 +0000599 RewriteProtocolDecl(PD);
Mike Stump11289f42009-09-09 15:08:12 +0000600 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000601 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000602 RewriteForwardProtocolDecl(FP);
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000603 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
604 // Recurse into linkage specifications
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000605 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
606 DIEnd = LSD->decls_end();
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000607 DI != DIEnd; ++DI)
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000608 HandleTopLevelSingleDecl(*DI);
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000609 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000610 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekd61ed3b2008-04-14 21:24:13 +0000611 if (SM->isFromMainFile(Loc))
Chris Lattner0bd1c972007-10-16 21:07:07 +0000612 return HandleDeclInMainFile(D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000613}
614
Chris Lattner3c799d72007-10-24 17:06:59 +0000615//===----------------------------------------------------------------------===//
616// Syntactic (non-AST) Rewriting Code
617//===----------------------------------------------------------------------===//
618
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000619void RewriteObjC::RewriteInclude() {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000620 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000621 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
622 const char *MainBufStart = MainBuf.first;
623 const char *MainBufEnd = MainBuf.second;
624 size_t ImportLen = strlen("import");
625 size_t IncludeLen = strlen("include");
Mike Stump11289f42009-09-09 15:08:12 +0000626
Fariborz Jahanian137d6932008-01-19 01:03:17 +0000627 // Loop over the whole file, looking for includes.
Fariborz Jahanian80258362008-01-19 00:30:35 +0000628 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
629 if (*BufPtr == '#') {
630 if (++BufPtr == MainBufEnd)
631 return;
632 while (*BufPtr == ' ' || *BufPtr == '\t')
633 if (++BufPtr == MainBufEnd)
634 return;
635 if (!strncmp(BufPtr, "import", ImportLen)) {
636 // replace import with include
Mike Stump11289f42009-09-09 15:08:12 +0000637 SourceLocation ImportLoc =
Fariborz Jahanian80258362008-01-19 00:30:35 +0000638 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000639 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000640 BufPtr += ImportLen;
641 }
642 }
643 }
Chris Lattner0bd1c972007-10-16 21:07:07 +0000644}
645
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000646void RewriteObjC::RewriteTabs() {
Chris Lattner3c799d72007-10-24 17:06:59 +0000647 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
648 const char *MainBufStart = MainBuf.first;
649 const char *MainBufEnd = MainBuf.second;
Mike Stump11289f42009-09-09 15:08:12 +0000650
Chris Lattner3c799d72007-10-24 17:06:59 +0000651 // Loop over the whole file, looking for tabs.
652 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
653 if (*BufPtr != '\t')
654 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000655
Chris Lattner3c799d72007-10-24 17:06:59 +0000656 // Okay, we found a tab. This tab will turn into at least one character,
657 // but it depends on which 'virtual column' it is in. Compute that now.
658 unsigned VCol = 0;
659 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
660 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
661 ++VCol;
Mike Stump11289f42009-09-09 15:08:12 +0000662
Chris Lattner3c799d72007-10-24 17:06:59 +0000663 // Okay, now that we know the virtual column, we know how many spaces to
664 // insert. We assume 8-character tab-stops.
665 unsigned Spaces = 8-(VCol & 7);
Mike Stump11289f42009-09-09 15:08:12 +0000666
Chris Lattner3c799d72007-10-24 17:06:59 +0000667 // Get the location of the tab.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000668 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
669 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Mike Stump11289f42009-09-09 15:08:12 +0000670
Chris Lattner3c799d72007-10-24 17:06:59 +0000671 // Rewrite the single tab character into a sequence of spaces.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000672 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattner3c799d72007-10-24 17:06:59 +0000673 }
Chris Lattner16a0de42007-10-11 18:38:32 +0000674}
675
Steve Naroff9af94912008-12-02 15:48:25 +0000676static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
677 ObjCIvarDecl *OID) {
678 std::string S;
679 S = "((struct ";
680 S += ClassDecl->getIdentifier()->getName();
681 S += "_IMPL *)self)->";
Daniel Dunbar70e7ead2009-10-18 20:26:27 +0000682 S += OID->getName();
Steve Naroff9af94912008-12-02 15:48:25 +0000683 return S;
684}
685
Steve Naroffc038b3a2008-12-02 17:36:43 +0000686void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
687 ObjCImplementationDecl *IMD,
688 ObjCCategoryImplDecl *CID) {
Steve Naroffe1908e32008-12-01 20:33:01 +0000689 SourceLocation startLoc = PID->getLocStart();
690 InsertText(startLoc, "// ", 3);
Steve Naroff9af94912008-12-02 15:48:25 +0000691 const char *startBuf = SM->getCharacterData(startLoc);
692 assert((*startBuf == '@') && "bogus @synthesize location");
693 const char *semiBuf = strchr(startBuf, ';');
694 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek5a201952009-02-07 01:47:29 +0000695 SourceLocation onePastSemiLoc =
696 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroff9af94912008-12-02 15:48:25 +0000697
698 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
699 return; // FIXME: is this correct?
Mike Stump11289f42009-09-09 15:08:12 +0000700
Steve Naroff9af94912008-12-02 15:48:25 +0000701 // Generate the 'getter' function.
Steve Naroff9af94912008-12-02 15:48:25 +0000702 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroff9af94912008-12-02 15:48:25 +0000703 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroff9af94912008-12-02 15:48:25 +0000704 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000705
Steve Naroff003d00e2008-12-02 16:05:55 +0000706 if (!OID)
707 return;
Mike Stump11289f42009-09-09 15:08:12 +0000708
Steve Naroff003d00e2008-12-02 16:05:55 +0000709 std::string Getr;
710 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
711 Getr += "{ ";
712 // Synthesize an explicit cast to gain access to the ivar.
Mike Stump11289f42009-09-09 15:08:12 +0000713 // FIXME: deal with code generation implications for various property
714 // attributes (copy, retain, nonatomic).
Steve Naroff06297042008-12-02 17:54:50 +0000715 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroff003d00e2008-12-02 16:05:55 +0000716 Getr += "return " + getIvarAccessString(ClassDecl, OID);
717 Getr += "; }";
Steve Naroff9af94912008-12-02 15:48:25 +0000718 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroff9af94912008-12-02 15:48:25 +0000719 if (PD->isReadOnly())
720 return;
Mike Stump11289f42009-09-09 15:08:12 +0000721
Steve Naroff9af94912008-12-02 15:48:25 +0000722 // Generate the 'setter' function.
723 std::string Setr;
724 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroff9af94912008-12-02 15:48:25 +0000725 Setr += "{ ";
Steve Naroff003d00e2008-12-02 16:05:55 +0000726 // Synthesize an explicit cast to initialize the ivar.
Mike Stump11289f42009-09-09 15:08:12 +0000727 // FIXME: deal with code generation implications for various property
728 // attributes (copy, retain, nonatomic).
Steve Narofff326f402008-12-03 00:56:33 +0000729 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroff003d00e2008-12-02 16:05:55 +0000730 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000731 Setr += PD->getNameAsCString();
Steve Naroff003d00e2008-12-02 16:05:55 +0000732 Setr += "; }";
Steve Naroff9af94912008-12-02 15:48:25 +0000733 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffe1908e32008-12-01 20:33:01 +0000734}
Chris Lattner16a0de42007-10-11 18:38:32 +0000735
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000736void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattner3c799d72007-10-24 17:06:59 +0000737 // Get the start location and compute the semi location.
738 SourceLocation startLoc = ClassDecl->getLocation();
739 const char *startBuf = SM->getCharacterData(startLoc);
740 const char *semiPtr = strchr(startBuf, ';');
Mike Stump11289f42009-09-09 15:08:12 +0000741
Chris Lattner3c799d72007-10-24 17:06:59 +0000742 // Translate to typedef's that forward reference structs with the same name
743 // as the class. As a convenience, we include the original declaration
744 // as a comment.
745 std::string typedefString;
746 typedefString += "// ";
Steve Naroff574440f2007-10-24 22:48:43 +0000747 typedefString.append(startBuf, semiPtr-startBuf+1);
748 typedefString += "\n";
Chris Lattner9ee23b72009-02-20 18:04:31 +0000749 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
750 I != E; ++I) {
Ted Kremenek9b124e12009-11-18 00:28:11 +0000751 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff1b232132007-11-09 12:50:28 +0000752 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000753 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000754 typedefString += "\n";
755 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000756 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000757 typedefString += "\n";
Steve Naroff98eb8d12007-11-05 14:36:37 +0000758 typedefString += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000759 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000760 typedefString += ";\n#endif\n";
Steve Naroff574440f2007-10-24 22:48:43 +0000761 }
Mike Stump11289f42009-09-09 15:08:12 +0000762
Steve Naroff574440f2007-10-24 22:48:43 +0000763 // Replace the @class with typedefs corresponding to the classes.
Mike Stump11289f42009-09-09 15:08:12 +0000764 ReplaceText(startLoc, semiPtr-startBuf+1,
Chris Lattner9cc55f52008-01-31 19:51:04 +0000765 typedefString.c_str(), typedefString.size());
Chris Lattner3c799d72007-10-24 17:06:59 +0000766}
767
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000768void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff3ce37a62007-12-14 23:37:57 +0000769 SourceLocation LocStart = Method->getLocStart();
770 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000771
Chris Lattner88ea93e2009-02-04 01:06:56 +0000772 if (SM->getInstantiationLineNumber(LocEnd) >
773 SM->getInstantiationLineNumber(LocStart)) {
Steve Naroffe020fa12008-10-21 13:37:27 +0000774 InsertText(LocStart, "#if 0\n", 6);
775 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff3ce37a62007-12-14 23:37:57 +0000776 } else {
Chris Lattner1780a852008-01-31 19:42:41 +0000777 InsertText(LocStart, "// ", 3);
Steve Naroff5448cf62007-10-30 13:30:57 +0000778 }
779}
780
Mike Stump11289f42009-09-09 15:08:12 +0000781void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000782 SourceLocation Loc = prop->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000783
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000784 ReplaceText(Loc, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000785
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000786 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahaniane8a30162007-11-07 00:09:37 +0000787}
788
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000789void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000790 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000791
Steve Naroff5448cf62007-10-30 13:30:57 +0000792 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000793 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000794
795 for (ObjCCategoryDecl::instmeth_iterator
796 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000797 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000798 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +0000799 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000800 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000801 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000802 RewriteMethodDeclaration(*I);
803
Steve Naroff5448cf62007-10-30 13:30:57 +0000804 // Lastly, comment out the @end.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000805 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff5448cf62007-10-30 13:30:57 +0000806}
807
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000808void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000809 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Mike Stump11289f42009-09-09 15:08:12 +0000810
Steve Narofff921385f2007-10-30 16:42:30 +0000811 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000812
Steve Narofff921385f2007-10-30 16:42:30 +0000813 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000814 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000815
816 for (ObjCProtocolDecl::instmeth_iterator
817 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000818 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000819 RewriteMethodDeclaration(*I);
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000820 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000821 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000822 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000823 RewriteMethodDeclaration(*I);
824
Steve Narofff921385f2007-10-30 16:42:30 +0000825 // Lastly, comment out the @end.
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000826 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattner9cc55f52008-01-31 19:51:04 +0000827 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroffa509f042007-11-14 15:03:57 +0000828
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000829 // Must comment out @optional/@required
830 const char *startBuf = SM->getCharacterData(LocStart);
831 const char *endBuf = SM->getCharacterData(LocEnd);
832 for (const char *p = startBuf; p < endBuf; p++) {
833 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
834 std::string CommentedOptional = "/* @optional */";
Steve Naroffa509f042007-11-14 15:03:57 +0000835 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000836 ReplaceText(OptionalLoc, strlen("@optional"),
837 CommentedOptional.c_str(), CommentedOptional.size());
Mike Stump11289f42009-09-09 15:08:12 +0000838
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000839 }
840 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
841 std::string CommentedRequired = "/* @required */";
Steve Naroffa509f042007-11-14 15:03:57 +0000842 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000843 ReplaceText(OptionalLoc, strlen("@required"),
844 CommentedRequired.c_str(), CommentedRequired.size());
Mike Stump11289f42009-09-09 15:08:12 +0000845
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000846 }
847 }
Steve Narofff921385f2007-10-30 16:42:30 +0000848}
849
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000850void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000851 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffc17b0562007-11-14 03:37:28 +0000852 if (LocStart.isInvalid())
853 assert(false && "Invalid SourceLocation");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000854 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000855 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000856}
857
Mike Stump11289f42009-09-09 15:08:12 +0000858void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000859 std::string &ResultStr) {
Steve Naroff295570a2008-10-30 12:09:33 +0000860 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroffb067bbd2008-07-16 14:40:40 +0000861 const FunctionType *FPRetType = 0;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000862 ResultStr += "\nstatic ";
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000863 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +0000864 ResultStr += "id";
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000865 else if (OMD->getResultType()->isFunctionPointerType() ||
866 OMD->getResultType()->isBlockPointerType()) {
Steve Naroffb067bbd2008-07-16 14:40:40 +0000867 // needs special handling, since pointer-to-functions have special
868 // syntax (where a decaration models use).
869 QualType retType = OMD->getResultType();
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000870 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000871 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000872 PointeeTy = PT->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000873 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000874 PointeeTy = BPT->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +0000875 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000876 ResultStr += FPRetType->getResultType().getAsString();
877 ResultStr += "(*";
Steve Naroffb067bbd2008-07-16 14:40:40 +0000878 }
879 } else
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +0000880 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian7262fca2008-01-10 01:39:52 +0000881 ResultStr += " ";
Mike Stump11289f42009-09-09 15:08:12 +0000882
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000883 // Unique method name
Fariborz Jahanian56338352007-11-13 21:02:00 +0000884 std::string NameStr;
Mike Stump11289f42009-09-09 15:08:12 +0000885
Douglas Gregorffca3a22009-01-09 17:18:27 +0000886 if (OMD->isInstanceMethod())
Fariborz Jahanian56338352007-11-13 21:02:00 +0000887 NameStr += "_I_";
888 else
889 NameStr += "_C_";
Mike Stump11289f42009-09-09 15:08:12 +0000890
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000891 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +0000892 NameStr += "_";
Mike Stump11289f42009-09-09 15:08:12 +0000893
894 if (ObjCCategoryImplDecl *CID =
Steve Naroff11b387f2009-01-08 19:41:02 +0000895 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000896 NameStr += CID->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +0000897 NameStr += "_";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000898 }
Mike Stump11289f42009-09-09 15:08:12 +0000899 // Append selector names, replacing ':' with '_'
Chris Lattnere4b95692008-11-24 03:33:13 +0000900 {
901 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000902 int len = selString.size();
903 for (int i = 0; i < len; i++)
904 if (selString[i] == ':')
905 selString[i] = '_';
Fariborz Jahanian56338352007-11-13 21:02:00 +0000906 NameStr += selString;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000907 }
Fariborz Jahanian56338352007-11-13 21:02:00 +0000908 // Remember this name for metadata emission
909 MethodInternalNames[OMD] = NameStr;
910 ResultStr += NameStr;
Mike Stump11289f42009-09-09 15:08:12 +0000911
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000912 // Rewrite arguments
913 ResultStr += "(";
Mike Stump11289f42009-09-09 15:08:12 +0000914
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000915 // invisible arguments
Douglas Gregorffca3a22009-01-09 17:18:27 +0000916 if (OMD->isInstanceMethod()) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000917 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000918 selfTy = Context->getPointerType(selfTy);
Steve Naroffdc5b6b22008-03-12 00:25:36 +0000919 if (!LangOpts.Microsoft) {
920 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
921 ResultStr += "struct ";
922 }
923 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000924 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +0000925 ResultStr += " *";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000926 }
927 else
Steve Naroffd9803712009-04-29 16:37:50 +0000928 ResultStr += Context->getObjCClassType().getAsString();
Mike Stump11289f42009-09-09 15:08:12 +0000929
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000930 ResultStr += " self, ";
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000931 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000932 ResultStr += " _cmd";
Mike Stump11289f42009-09-09 15:08:12 +0000933
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000934 // Method arguments.
Chris Lattnera4997152009-02-20 18:43:26 +0000935 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
936 E = OMD->param_end(); PI != E; ++PI) {
937 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000938 ResultStr += ", ";
Steve Naroffdcdcdcd2008-04-18 21:13:19 +0000939 if (PDecl->getType()->isObjCQualifiedIdType()) {
940 ResultStr += "id ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000941 ResultStr += PDecl->getNameAsString();
Steve Naroffdcdcdcd2008-04-18 21:13:19 +0000942 } else {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000943 std::string Name = PDecl->getNameAsString();
Steve Naroffa5c0db82008-12-11 21:05:33 +0000944 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroff44df6a22008-10-30 14:45:29 +0000945 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000946 const BlockPointerType *BPT = PDecl->getType()->getAs<BlockPointerType>();
Douglas Gregor7de59662009-05-29 20:38:28 +0000947 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name,
948 Context->PrintingPolicy);
Steve Naroff44df6a22008-10-30 14:45:29 +0000949 } else
Douglas Gregor7de59662009-05-29 20:38:28 +0000950 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroffdcdcdcd2008-04-18 21:13:19 +0000951 ResultStr += Name;
952 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000953 }
Fariborz Jahanianeab81cd2008-01-21 20:14:23 +0000954 if (OMD->isVariadic())
955 ResultStr += ", ...";
Fariborz Jahanian7262fca2008-01-10 01:39:52 +0000956 ResultStr += ") ";
Mike Stump11289f42009-09-09 15:08:12 +0000957
Steve Naroffb067bbd2008-07-16 14:40:40 +0000958 if (FPRetType) {
959 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump11289f42009-09-09 15:08:12 +0000960
Steve Naroffb067bbd2008-07-16 14:40:40 +0000961 // Now, emit the argument types (if any).
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000962 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroffb067bbd2008-07-16 14:40:40 +0000963 ResultStr += "(";
964 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
965 if (i) ResultStr += ", ";
966 std::string ParamStr = FT->getArgType(i).getAsString();
967 ResultStr += ParamStr;
968 }
969 if (FT->isVariadic()) {
970 if (FT->getNumArgs()) ResultStr += ", ";
971 ResultStr += "...";
972 }
973 ResultStr += ")";
974 } else {
975 ResultStr += "()";
976 }
977 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000978}
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000979void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000980 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
981 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump11289f42009-09-09 15:08:12 +0000982
Fariborz Jahanianc54d8462007-11-13 20:04:28 +0000983 if (IMD)
Chris Lattner1780a852008-01-31 19:42:41 +0000984 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanianc54d8462007-11-13 20:04:28 +0000985 else
Chris Lattner1780a852008-01-31 19:42:41 +0000986 InsertText(CID->getLocStart(), "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000987
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000988 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000989 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
990 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +0000991 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000992 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000993 ObjCMethodDecl *OMD = *I;
994 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000995 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +0000996 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redla7b98a72009-04-26 20:35:05 +0000997
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000998 const char *startBuf = SM->getCharacterData(LocStart);
999 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattner9cc55f52008-01-31 19:51:04 +00001000 ReplaceText(LocStart, endBuf-startBuf,
1001 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001002 }
Mike Stump11289f42009-09-09 15:08:12 +00001003
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001004 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001005 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1006 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001007 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001008 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001009 ObjCMethodDecl *OMD = *I;
1010 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001011 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001012 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +00001013
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001014 const char *startBuf = SM->getCharacterData(LocStart);
1015 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattner9cc55f52008-01-31 19:51:04 +00001016 ReplaceText(LocStart, endBuf-startBuf,
Mike Stump11289f42009-09-09 15:08:12 +00001017 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001018 }
Steve Naroffe1908e32008-12-01 20:33:01 +00001019 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001020 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001021 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001022 I != E; ++I) {
Steve Naroffc038b3a2008-12-02 17:36:43 +00001023 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffe1908e32008-12-01 20:33:01 +00001024 }
1025
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001026 if (IMD)
Chris Lattner1780a852008-01-31 19:42:41 +00001027 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001028 else
Mike Stump11289f42009-09-09 15:08:12 +00001029 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001030}
1031
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001032void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffc5484042007-10-30 02:23:23 +00001033 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001034 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff2f55b982007-11-01 03:35:41 +00001035 // we haven't seen a forward decl - generate a typedef.
Steve Naroff03f27672007-11-14 23:02:56 +00001036 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001037 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001038 ResultStr += "\n";
1039 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001040 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001041 ResultStr += "\n";
Steve Naroffa1e115e2008-03-10 23:16:54 +00001042 ResultStr += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001043 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001044 ResultStr += ";\n#endif\n";
Steve Naroff2f55b982007-11-01 03:35:41 +00001045 // Mark this typedef as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001046 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff2f55b982007-11-01 03:35:41 +00001047 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001048 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump11289f42009-09-09 15:08:12 +00001049
1050 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001051 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff0c0f5ba2009-01-11 01:06:09 +00001052 RewriteProperty(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001053 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001054 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001055 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001056 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001057 for (ObjCInterfaceDecl::classmeth_iterator
1058 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001059 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001060 RewriteMethodDeclaration(*I);
1061
Steve Naroff4cd61ac2007-10-30 03:43:13 +00001062 // Lastly, comment out the @end.
Chris Lattner9cc55f52008-01-31 19:51:04 +00001063 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff161a92b2007-10-26 20:53:56 +00001064}
1065
Steve Naroff08628db2008-12-09 12:56:34 +00001066Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1067 SourceRange SrcRange) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00001068 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1069 // This allows us to reuse all the fun and games in SynthMessageExpr().
1070 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1071 ObjCMessageExpr *MsgExpr;
1072 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1073 llvm::SmallVector<Expr *, 1> ExprVec;
1074 ExprVec.push_back(newStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001075
Steve Naroff1042ff32008-12-08 16:43:47 +00001076 Stmt *Receiver = PropRefExpr->getBase();
1077 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1078 if (PRE && PropGetters[PRE]) {
1079 // This allows us to handle chain/nested property getters.
1080 Receiver = PropGetters[PRE];
1081 }
Mike Stump11289f42009-09-09 15:08:12 +00001082 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1083 PDecl->getSetterName(), PDecl->getType(),
1084 PDecl->getSetterMethodDecl(),
1085 SourceLocation(), SourceLocation(),
Steve Naroff4588d0f2008-12-04 16:24:46 +00001086 &ExprVec[0], 1);
1087 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001088
Steve Naroff4588d0f2008-12-04 16:24:46 +00001089 // Now do the actual rewrite.
Steve Naroff08628db2008-12-09 12:56:34 +00001090 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffdf705772008-12-10 14:53:27 +00001091 //delete BinOp;
Ted Kremenek5a201952009-02-07 01:47:29 +00001092 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1093 // to things that stay around.
1094 Context->Deallocate(MsgExpr);
Steve Naroff4588d0f2008-12-04 16:24:46 +00001095 return ReplacingStmt;
Steve Narofff326f402008-12-03 00:56:33 +00001096}
1097
Steve Naroff4588d0f2008-12-04 16:24:46 +00001098Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Narofff326f402008-12-03 00:56:33 +00001099 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1100 // This allows us to reuse all the fun and games in SynthMessageExpr().
1101 ObjCMessageExpr *MsgExpr;
1102 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
Mike Stump11289f42009-09-09 15:08:12 +00001103
Steve Naroff1042ff32008-12-08 16:43:47 +00001104 Stmt *Receiver = PropRefExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00001105
Steve Naroff1042ff32008-12-08 16:43:47 +00001106 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1107 if (PRE && PropGetters[PRE]) {
1108 // This allows us to handle chain/nested property getters.
1109 Receiver = PropGetters[PRE];
1110 }
Mike Stump11289f42009-09-09 15:08:12 +00001111 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1112 PDecl->getGetterName(), PDecl->getType(),
1113 PDecl->getGetterMethodDecl(),
1114 SourceLocation(), SourceLocation(),
Steve Narofff326f402008-12-03 00:56:33 +00001115 0, 0);
1116
Steve Naroff22216db2008-12-04 23:50:32 +00001117 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001118
1119 if (!PropParentMap)
1120 PropParentMap = new ParentMap(CurrentBody);
1121
1122 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1123 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1124 // We stash away the ReplacingStmt since actually doing the
1125 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1126 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek5a201952009-02-07 01:47:29 +00001127 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1128 // to things that stay around.
1129 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001130 return PropRefExpr; // return the original...
1131 } else {
1132 ReplaceStmt(PropRefExpr, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001133 // delete PropRefExpr; elsewhere...
Ted Kremenek5a201952009-02-07 01:47:29 +00001134 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1135 // to things that stay around.
1136 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001137 return ReplacingStmt;
1138 }
Steve Narofff326f402008-12-03 00:56:33 +00001139}
1140
Mike Stump11289f42009-09-09 15:08:12 +00001141Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001142 SourceLocation OrigStart) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001143 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff677ab3a2008-10-27 17:20:55 +00001144 if (CurMethodDef) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001145 if (const PointerType *pType = IV->getBase()->getType()->getAs<PointerType>()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001146 ObjCInterfaceType *iFaceDecl =
1147 dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroffb1c02372008-05-08 17:52:16 +00001148 // lookup which class implements the instance variable.
1149 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001150 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001151 clsDeclared);
Steve Naroffb1c02372008-05-08 17:52:16 +00001152 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001153
Steve Naroffb1c02372008-05-08 17:52:16 +00001154 // Synthesize an explicit cast to gain access to the ivar.
1155 std::string RecName = clsDeclared->getIdentifier()->getName();
1156 RecName += "_IMPL";
1157 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001158 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001159 SourceLocation(), II);
Steve Naroffb1c02372008-05-08 17:52:16 +00001160 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1161 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Mike Stump11289f42009-09-09 15:08:12 +00001162 CastExpr *castExpr = new (Context) CStyleCastExpr(castT,
Anders Carlssona2615922009-07-31 00:48:10 +00001163 CastExpr::CK_Unknown,
1164 IV->getBase(),
1165 castT,SourceLocation(),
1166 SourceLocation());
Steve Naroffb1c02372008-05-08 17:52:16 +00001167 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001168 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1169 IV->getBase()->getLocEnd(),
1170 castExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001171 if (IV->isFreeIvar() &&
Steve Naroff677ab3a2008-10-27 17:20:55 +00001172 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001173 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1174 IV->getLocation(),
1175 D->getType());
Steve Naroffb1c02372008-05-08 17:52:16 +00001176 ReplaceStmt(IV, ME);
Steve Naroff22216db2008-12-04 23:50:32 +00001177 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb1c02372008-05-08 17:52:16 +00001178 return ME;
Steve Naroff05caa482007-11-15 11:33:00 +00001179 }
Mike Stump11289f42009-09-09 15:08:12 +00001180
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001181 ReplaceStmt(IV->getBase(), PE);
1182 // Cannot delete IV->getBase(), since PE points to it.
1183 // Replace the old base with the cast. This is important when doing
1184 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001185 IV->setBase(PE);
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001186 return IV;
Steve Naroff05caa482007-11-15 11:33:00 +00001187 }
Steve Naroff24840f62008-04-18 21:55:08 +00001188 } else { // we are outside a method.
Steve Naroff29ce4e52008-05-06 23:20:07 +00001189 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump11289f42009-09-09 15:08:12 +00001190
Steve Naroff29ce4e52008-05-06 23:20:07 +00001191 // Explicit ivar refs need to have a cast inserted.
1192 // FIXME: consider sharing some of this code with the code above.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001193 if (const PointerType *pType = IV->getBase()->getType()->getAs<PointerType>()) {
Steve Naroffb1c02372008-05-08 17:52:16 +00001194 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001195 // lookup which class implements the instance variable.
1196 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001197 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001198 clsDeclared);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001199 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001200
Steve Naroff29ce4e52008-05-06 23:20:07 +00001201 // Synthesize an explicit cast to gain access to the ivar.
1202 std::string RecName = clsDeclared->getIdentifier()->getName();
1203 RecName += "_IMPL";
1204 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001205 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001206 SourceLocation(), II);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001207 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1208 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Mike Stump11289f42009-09-09 15:08:12 +00001209 CastExpr *castExpr = new (Context) CStyleCastExpr(castT,
Anders Carlssona2615922009-07-31 00:48:10 +00001210 CastExpr::CK_Unknown,
1211 IV->getBase(),
Ted Kremenek5a201952009-02-07 01:47:29 +00001212 castT, SourceLocation(),
1213 SourceLocation());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001214 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001215 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner34873d22008-05-28 16:38:23 +00001216 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001217 ReplaceStmt(IV->getBase(), PE);
1218 // Cannot delete IV->getBase(), since PE points to it.
1219 // Replace the old base with the cast. This is important when doing
1220 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001221 IV->setBase(PE);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001222 return IV;
1223 }
Steve Naroff05caa482007-11-15 11:33:00 +00001224 }
Steve Naroff24840f62008-04-18 21:55:08 +00001225 return IV;
Steve Narofff60782b2007-11-15 02:58:25 +00001226}
1227
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001228/// SynthCountByEnumWithState - To print:
1229/// ((unsigned int (*)
1230/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001231/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001232/// sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001233/// "countByEnumeratingWithState:objects:count:"),
1234/// &enumState,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001235/// (id *)items, (unsigned int)16)
1236///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001237void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001238 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1239 "id *, unsigned int))(void *)objc_msgSend)";
1240 buf += "\n\t\t";
1241 buf += "((id)l_collection,\n\t\t";
1242 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1243 buf += "\n\t\t";
1244 buf += "&enumState, "
1245 "(id *)items, (unsigned int)16)";
1246}
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001247
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001248/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1249/// statement to exit to its outer synthesized loop.
1250///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001251Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001252 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1253 return S;
1254 // replace break with goto __break_label
1255 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001256
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001257 SourceLocation startLoc = S->getLocStart();
1258 buf = "goto __break_label_";
1259 buf += utostr(ObjCBcLabelNo.back());
Chris Lattner9cc55f52008-01-31 19:51:04 +00001260 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001261
1262 return 0;
1263}
1264
1265/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1266/// statement to continue with its inner synthesized loop.
1267///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001268Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001269 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1270 return S;
1271 // replace continue with goto __continue_label
1272 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001273
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001274 SourceLocation startLoc = S->getLocStart();
1275 buf = "goto __continue_label_";
1276 buf += utostr(ObjCBcLabelNo.back());
Chris Lattner9cc55f52008-01-31 19:51:04 +00001277 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001278
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001279 return 0;
1280}
1281
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001282/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001283/// It rewrites:
1284/// for ( type elem in collection) { stmts; }
Mike Stump11289f42009-09-09 15:08:12 +00001285
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001286/// Into:
1287/// {
Mike Stump11289f42009-09-09 15:08:12 +00001288/// type elem;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001289/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001290/// id items[16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001291/// id l_collection = (id)collection;
Mike Stump11289f42009-09-09 15:08:12 +00001292/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001293/// objects:items count:16];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001294/// if (limit) {
1295/// unsigned long startMutations = *enumState.mutationsPtr;
1296/// do {
1297/// unsigned long counter = 0;
1298/// do {
Mike Stump11289f42009-09-09 15:08:12 +00001299/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001300/// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001301/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001302/// stmts;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001303/// __continue_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001304/// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001305/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001306/// objects:items count:16]);
1307/// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001308/// __break_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001309/// }
1310/// else
1311/// elem = nil;
1312/// }
1313///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001314Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattnera779d692008-01-31 05:10:40 +00001315 SourceLocation OrigEnd) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001316 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001317 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001318 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump11289f42009-09-09 15:08:12 +00001319 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001320 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001321
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001322 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001323 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001324 const char *elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001325 std::string elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001326 std::string buf;
1327 buf = "\n{\n\t";
1328 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1329 // type elem;
Chris Lattner529efc72009-03-28 06:33:19 +00001330 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek292b3842008-10-06 22:16:13 +00001331 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001332 if (ElementType->isObjCQualifiedIdType() ||
1333 ElementType->isObjCQualifiedInterfaceType())
1334 // Simply use 'id' for all qualified types.
1335 elementTypeAsString = "id";
1336 else
1337 elementTypeAsString = ElementType.getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001338 buf += elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001339 buf += " ";
Chris Lattner86d7d912008-11-24 03:54:41 +00001340 elementName = D->getNameAsCString();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001341 buf += elementName;
1342 buf += ";\n\t";
1343 }
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001344 else {
1345 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner86d7d912008-11-24 03:54:41 +00001346 elementName = DR->getDecl()->getNameAsCString();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001347 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1348 if (VD->getType()->isObjCQualifiedIdType() ||
1349 VD->getType()->isObjCQualifiedInterfaceType())
1350 // Simply use 'id' for all qualified types.
1351 elementTypeAsString = "id";
1352 else
1353 elementTypeAsString = VD->getType().getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001354 }
Mike Stump11289f42009-09-09 15:08:12 +00001355
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001356 // struct __objcFastEnumerationState enumState = { 0 };
1357 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1358 // id items[16];
1359 buf += "id items[16];\n\t";
1360 // id l_collection = (id)
1361 buf += "id l_collection = (id)";
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001362 // Find start location of 'collection' the hard way!
1363 const char *startCollectionBuf = startBuf;
1364 startCollectionBuf += 3; // skip 'for'
1365 startCollectionBuf = strchr(startCollectionBuf, '(');
1366 startCollectionBuf++; // skip '('
1367 // find 'in' and skip it.
1368 while (*startCollectionBuf != ' ' ||
1369 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1370 (*(startCollectionBuf+3) != ' ' &&
1371 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1372 startCollectionBuf++;
1373 startCollectionBuf += 3;
Mike Stump11289f42009-09-09 15:08:12 +00001374
1375 // Replace: "for (type element in" with string constructed thus far.
Chris Lattner9cc55f52008-01-31 19:51:04 +00001376 ReplaceText(startLoc, startCollectionBuf - startBuf,
1377 buf.c_str(), buf.size());
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001378 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001379 SourceLocation rightParenLoc = S->getRParenLoc();
1380 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1381 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001382 buf = ";\n\t";
Mike Stump11289f42009-09-09 15:08:12 +00001383
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001384 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1385 // objects:items count:16];
1386 // which is synthesized into:
Mike Stump11289f42009-09-09 15:08:12 +00001387 // unsigned int limit =
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001388 // ((unsigned int (*)
1389 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001390 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001391 // sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001392 // "countByEnumeratingWithState:objects:count:"),
1393 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001394 // (id *)items, (unsigned int)16);
1395 buf += "unsigned long limit =\n\t\t";
1396 SynthCountByEnumWithState(buf);
1397 buf += ";\n\t";
1398 /// if (limit) {
1399 /// unsigned long startMutations = *enumState.mutationsPtr;
1400 /// do {
1401 /// unsigned long counter = 0;
1402 /// do {
Mike Stump11289f42009-09-09 15:08:12 +00001403 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001404 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001405 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001406 buf += "if (limit) {\n\t";
1407 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1408 buf += "do {\n\t\t";
1409 buf += "unsigned long counter = 0;\n\t\t";
1410 buf += "do {\n\t\t\t";
1411 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1412 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1413 buf += elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001414 buf += " = (";
1415 buf += elementTypeAsString;
1416 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001417 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattner9cc55f52008-01-31 19:51:04 +00001418 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001419
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001420 /// __continue_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001421 /// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001422 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001423 /// objects:items count:16]);
1424 /// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001425 /// __break_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001426 /// }
1427 /// else
1428 /// elem = nil;
1429 /// }
Mike Stump11289f42009-09-09 15:08:12 +00001430 ///
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001431 buf = ";\n\t";
1432 buf += "__continue_label_";
1433 buf += utostr(ObjCBcLabelNo.back());
1434 buf += ": ;";
1435 buf += "\n\t\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001436 buf += "} while (counter < limit);\n\t";
1437 buf += "} while (limit = ";
1438 SynthCountByEnumWithState(buf);
1439 buf += ");\n\t";
1440 buf += elementName;
Steve Naroffd1a36792008-12-17 14:24:39 +00001441 buf += " = ((id)0);\n\t";
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001442 buf += "__break_label_";
1443 buf += utostr(ObjCBcLabelNo.back());
1444 buf += ": ;\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001445 buf += "}\n\t";
1446 buf += "else\n\t\t";
1447 buf += elementName;
Steve Naroffd1a36792008-12-17 14:24:39 +00001448 buf += " = ((id)0);\n";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001449 buf += "}\n";
Mike Stump11289f42009-09-09 15:08:12 +00001450
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001451 // Insert all these *after* the statement body.
Sebastian Redla7b98a72009-04-26 20:35:05 +00001452 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Narofff0ff8792008-07-21 18:26:02 +00001453 if (isa<CompoundStmt>(S->getBody())) {
1454 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1455 InsertText(endBodyLoc, buf.c_str(), buf.size());
1456 } else {
1457 /* Need to treat single statements specially. For example:
1458 *
1459 * for (A *a in b) if (stuff()) break;
1460 * for (A *a in b) xxxyy;
1461 *
1462 * The following code simply scans ahead to the semi to find the actual end.
1463 */
1464 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1465 const char *semiBuf = strchr(stmtBuf, ';');
1466 assert(semiBuf && "Can't find ';'");
1467 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1468 InsertText(endBodyLoc, buf.c_str(), buf.size());
1469 }
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001470 Stmts.pop_back();
1471 ObjCBcLabelNo.pop_back();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001472 return 0;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001473}
1474
Mike Stump11289f42009-09-09 15:08:12 +00001475/// RewriteObjCSynchronizedStmt -
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001476/// This routine rewrites @synchronized(expr) stmt;
1477/// into:
1478/// objc_sync_enter(expr);
1479/// @try stmt @finally { objc_sync_exit(expr); }
1480///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001481Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001482 // Get the start location and compute the semi location.
1483 SourceLocation startLoc = S->getLocStart();
1484 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001485
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001486 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump11289f42009-09-09 15:08:12 +00001487
1488 std::string buf;
Steve Naroffb2fc0522008-08-21 13:03:03 +00001489 buf = "objc_sync_enter((id)";
1490 const char *lparenBuf = startBuf;
1491 while (*lparenBuf != '(') lparenBuf++;
1492 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001493 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1494 // the sync expression is typically a message expression that's already
Steve Naroffad7013b2008-08-19 13:04:19 +00001495 // been rewritten! (which implies the SourceLocation's are invalid).
1496 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001497 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffad7013b2008-08-19 13:04:19 +00001498 while (*endBuf != ')') endBuf--;
1499 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001500 buf = ");\n";
1501 // declare a new scope with two variables, _stack and _rethrow.
1502 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1503 buf += "int buf[18/*32-bit i386*/];\n";
1504 buf += "char *pointers[4];} _stack;\n";
1505 buf += "id volatile _rethrow = 0;\n";
1506 buf += "objc_exception_try_enter(&_stack);\n";
1507 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001508 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001509 startLoc = S->getSynchBody()->getLocEnd();
1510 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001511
Steve Naroffad7013b2008-08-19 13:04:19 +00001512 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001513 SourceLocation lastCurlyLoc = startLoc;
1514 buf = "}\nelse {\n";
1515 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroffd9803712009-04-29 16:37:50 +00001516 buf += "}\n";
1517 buf += "{ /* implicit finally clause */\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001518 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffec60b432009-12-05 21:43:12 +00001519
1520 std::string syncBuf;
1521 syncBuf += " objc_sync_exit(";
Mike Stump11289f42009-09-09 15:08:12 +00001522 Expr *syncExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00001523 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00001524 S->getSynchExpr(),
Ted Kremenek5a201952009-02-07 01:47:29 +00001525 Context->getObjCIdType(),
1526 SourceLocation(),
1527 SourceLocation());
Ted Kremenek2d470fc2008-09-13 05:16:45 +00001528 std::string syncExprBufS;
1529 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00001530 syncExpr->printPretty(syncExprBuf, *Context, 0,
1531 PrintingPolicy(LangOpts));
Steve Naroffec60b432009-12-05 21:43:12 +00001532 syncBuf += syncExprBuf.str();
1533 syncBuf += ");";
1534
1535 buf += syncBuf;
1536 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001537 buf += "}\n";
1538 buf += "}";
Mike Stump11289f42009-09-09 15:08:12 +00001539
Chris Lattner9cc55f52008-01-31 19:51:04 +00001540 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffec60b432009-12-05 21:43:12 +00001541
1542 bool hasReturns = false;
1543 HasReturnStmts(S->getSynchBody(), hasReturns);
1544 if (hasReturns)
1545 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1546
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001547 return 0;
1548}
1549
Steve Naroffec60b432009-12-05 21:43:12 +00001550void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1551{
Steve Naroff6d6da252008-12-05 17:03:39 +00001552 // Perform a bottom up traversal of all children.
1553 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1554 CI != E; ++CI)
1555 if (*CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001556 WarnAboutReturnGotoStmts(*CI);
Steve Naroff6d6da252008-12-05 17:03:39 +00001557
Steve Naroffec60b432009-12-05 21:43:12 +00001558 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump11289f42009-09-09 15:08:12 +00001559 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff6d6da252008-12-05 17:03:39 +00001560 TryFinallyContainsReturnDiag);
1561 }
1562 return;
1563}
1564
Steve Naroffec60b432009-12-05 21:43:12 +00001565void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1566{
1567 // Perform a bottom up traversal of all children.
1568 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1569 CI != E; ++CI)
1570 if (*CI)
1571 HasReturnStmts(*CI, hasReturns);
1572
1573 if (isa<ReturnStmt>(S))
1574 hasReturns = true;
1575 return;
1576}
1577
1578void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1579 // Perform a bottom up traversal of all children.
1580 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1581 CI != E; ++CI)
1582 if (*CI) {
1583 RewriteTryReturnStmts(*CI);
1584 }
1585 if (isa<ReturnStmt>(S)) {
1586 SourceLocation startLoc = S->getLocStart();
1587 const char *startBuf = SM->getCharacterData(startLoc);
1588
1589 const char *semiBuf = strchr(startBuf, ';');
1590 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1591 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1592
1593 std::string buf;
1594 buf = "{ objc_exception_try_exit(&_stack); return";
1595
1596 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1597 InsertText(onePastSemiLoc, "}", 1);
1598 }
1599 return;
1600}
1601
1602void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1603 // Perform a bottom up traversal of all children.
1604 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1605 CI != E; ++CI)
1606 if (*CI) {
1607 RewriteSyncReturnStmts(*CI, syncExitBuf);
1608 }
1609 if (isa<ReturnStmt>(S)) {
1610 SourceLocation startLoc = S->getLocStart();
1611 const char *startBuf = SM->getCharacterData(startLoc);
1612
1613 const char *semiBuf = strchr(startBuf, ';');
1614 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1615 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1616
1617 std::string buf;
1618 buf = "{ objc_exception_try_exit(&_stack);";
1619 buf += syncExitBuf;
1620 buf += " return";
1621
1622 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1623 InsertText(onePastSemiLoc, "}", 1);
1624 }
1625 return;
1626}
1627
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001628Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001629 // Get the start location and compute the semi location.
1630 SourceLocation startLoc = S->getLocStart();
1631 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001632
Steve Naroffbf478ec2007-11-07 04:08:17 +00001633 assert((*startBuf == '@') && "bogus @try location");
1634
1635 std::string buf;
1636 // declare a new scope with two variables, _stack and _rethrow.
1637 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1638 buf += "int buf[18/*32-bit i386*/];\n";
1639 buf += "char *pointers[4];} _stack;\n";
1640 buf += "id volatile _rethrow = 0;\n";
1641 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff16018582007-11-07 18:43:40 +00001642 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffbf478ec2007-11-07 04:08:17 +00001643
Chris Lattner9cc55f52008-01-31 19:51:04 +00001644 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001645
Steve Naroffbf478ec2007-11-07 04:08:17 +00001646 startLoc = S->getTryBody()->getLocEnd();
1647 startBuf = SM->getCharacterData(startLoc);
1648
1649 assert((*startBuf == '}') && "bogus @try block");
Mike Stump11289f42009-09-09 15:08:12 +00001650
Steve Naroffbf478ec2007-11-07 04:08:17 +00001651 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffce2dca12008-07-16 15:31:30 +00001652 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1653 if (catchList) {
1654 startLoc = startLoc.getFileLocWithOffset(1);
1655 buf = " /* @catch begin */ else {\n";
1656 buf += " id _caught = objc_exception_extract(&_stack);\n";
1657 buf += " objc_exception_try_enter (&_stack);\n";
1658 buf += " if (_setjmp(_stack.buf))\n";
1659 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1660 buf += " else { /* @catch continue */";
Mike Stump11289f42009-09-09 15:08:12 +00001661
Steve Naroffce2dca12008-07-16 15:31:30 +00001662 InsertText(startLoc, buf.c_str(), buf.size());
Steve Narofffac18fe2008-09-09 19:59:12 +00001663 } else { /* no catch list */
1664 buf = "}\nelse {\n";
1665 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1666 buf += "}";
1667 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffce2dca12008-07-16 15:31:30 +00001668 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001669 bool sawIdTypedCatch = false;
1670 Stmt *lastCatchBody = 0;
Steve Naroffbf478ec2007-11-07 04:08:17 +00001671 while (catchList) {
Steve Naroff371b8fb2009-03-03 19:52:17 +00001672 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001673
Mike Stump11289f42009-09-09 15:08:12 +00001674 if (catchList == S->getCatchStmts())
Steve Naroffbf478ec2007-11-07 04:08:17 +00001675 buf = "if ("; // we are generating code for the first catch clause
1676 else
1677 buf = "else if (";
1678 startLoc = catchList->getLocStart();
1679 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001680
Steve Naroffbf478ec2007-11-07 04:08:17 +00001681 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump11289f42009-09-09 15:08:12 +00001682
Steve Naroffbf478ec2007-11-07 04:08:17 +00001683 const char *lParenLoc = strchr(startBuf, '(');
1684
Steve Naroffe6b7ffd2008-02-01 22:08:12 +00001685 if (catchList->hasEllipsis()) {
Steve Naroffedb5bc62008-02-01 20:02:07 +00001686 // Now rewrite the body...
1687 lastCatchBody = catchList->getCatchBody();
Steve Naroffedb5bc62008-02-01 20:02:07 +00001688 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1689 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001690 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1691 "bogus @catch paren location");
Steve Naroffedb5bc62008-02-01 20:02:07 +00001692 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001693
Steve Naroffedb5bc62008-02-01 20:02:07 +00001694 buf += "1) { id _tmp = _caught;";
Daniel Dunbardec484a2009-08-19 19:10:30 +00001695 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff371b8fb2009-03-03 19:52:17 +00001696 } else if (catchDecl) {
1697 QualType t = catchDecl->getType();
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001698 if (t == Context->getObjCIdType()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001699 buf += "1) { ";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001700 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001701 sawIdTypedCatch = true;
Mike Stump11289f42009-09-09 15:08:12 +00001702 } else if (const PointerType *pType = t->getAs<PointerType>()) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001703 ObjCInterfaceType *cls; // Should be a pointer to a class.
Mike Stump11289f42009-09-09 15:08:12 +00001704
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001705 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001706 if (cls) {
Steve Naroff16018582007-11-07 18:43:40 +00001707 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001708 buf += cls->getDecl()->getNameAsString();
Steve Naroff16018582007-11-07 18:43:40 +00001709 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001710 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001711 }
1712 }
1713 // Now rewrite the body...
1714 lastCatchBody = catchList->getCatchBody();
1715 SourceLocation rParenLoc = catchList->getRParenLoc();
1716 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1717 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1718 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1719 assert((*rParenBuf == ')') && "bogus @catch paren location");
1720 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001721
Steve Naroffbf478ec2007-11-07 04:08:17 +00001722 buf = " = _caught;";
Mike Stump11289f42009-09-09 15:08:12 +00001723 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroffbf478ec2007-11-07 04:08:17 +00001724 // declares the @catch parameter).
Chris Lattner9cc55f52008-01-31 19:51:04 +00001725 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff371b8fb2009-03-03 19:52:17 +00001726 } else {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001727 assert(false && "@catch rewrite bug");
Steve Naroffa733c7f2007-11-07 15:32:26 +00001728 }
Steve Naroffedb5bc62008-02-01 20:02:07 +00001729 // make sure all the catch bodies get rewritten!
Steve Naroffbf478ec2007-11-07 04:08:17 +00001730 catchList = catchList->getNextCatchStmt();
1731 }
1732 // Complete the catch list...
1733 if (lastCatchBody) {
1734 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001735 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1736 "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001737
Steve Naroff4adbe312008-09-11 15:29:03 +00001738 // Insert the last (implicit) else clause *before* the right curly brace.
1739 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1740 buf = "} /* last catch end */\n";
1741 buf += "else {\n";
1742 buf += " _rethrow = _caught;\n";
1743 buf += " objc_exception_try_exit(&_stack);\n";
1744 buf += "} } /* @catch end */\n";
1745 if (!S->getFinallyStmt())
1746 buf += "}\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001747 InsertText(bodyLoc, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001748
Steve Naroffbf478ec2007-11-07 04:08:17 +00001749 // Set lastCurlyLoc
1750 lastCurlyLoc = lastCatchBody->getLocEnd();
1751 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001752 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001753 startLoc = finalStmt->getLocStart();
1754 startBuf = SM->getCharacterData(startLoc);
1755 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump11289f42009-09-09 15:08:12 +00001756
Steve Naroffbf478ec2007-11-07 04:08:17 +00001757 buf = "/* @finally */";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001758 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001759
Steve Naroffbf478ec2007-11-07 04:08:17 +00001760 Stmt *body = finalStmt->getFinallyBody();
1761 SourceLocation startLoc = body->getLocStart();
1762 SourceLocation endLoc = body->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001763 assert(*SM->getCharacterData(startLoc) == '{' &&
1764 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001765 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001766 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001767
Steve Naroffbf478ec2007-11-07 04:08:17 +00001768 startLoc = startLoc.getFileLocWithOffset(1);
1769 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001770 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001771 endLoc = endLoc.getFileLocWithOffset(-1);
1772 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001773 InsertText(endLoc, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001774
Steve Naroffbf478ec2007-11-07 04:08:17 +00001775 // Set lastCurlyLoc
1776 lastCurlyLoc = body->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00001777
Steve Naroff6d6da252008-12-05 17:03:39 +00001778 // Now check for any return/continue/go statements within the @try.
Steve Naroffec60b432009-12-05 21:43:12 +00001779 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff4adbe312008-09-11 15:29:03 +00001780 } else { /* no finally clause - make sure we synthesize an implicit one */
1781 buf = "{ /* implicit finally clause */\n";
1782 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1783 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1784 buf += "}";
1785 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffec60b432009-12-05 21:43:12 +00001786
1787 // Now check for any return/continue/go statements within the @try.
1788 // The implicit finally clause won't called if the @try contains any
1789 // jump statements.
1790 bool hasReturns = false;
1791 HasReturnStmts(S->getTryBody(), hasReturns);
1792 if (hasReturns)
1793 RewriteTryReturnStmts(S->getTryBody());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001794 }
1795 // Now emit the final closing curly brace...
1796 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1797 buf = " } /* @try scope end */\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001798 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001799 return 0;
1800}
1801
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001802Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001803 return 0;
1804}
1805
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001806Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001807 return 0;
1808}
1809
Mike Stump11289f42009-09-09 15:08:12 +00001810// This can't be done with ReplaceStmt(S, ThrowExpr), since
1811// the throw expression is typically a message expression that's already
Steve Naroffa733c7f2007-11-07 15:32:26 +00001812// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001813Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroffa733c7f2007-11-07 15:32:26 +00001814 // Get the start location and compute the semi location.
1815 SourceLocation startLoc = S->getLocStart();
1816 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001817
Steve Naroffa733c7f2007-11-07 15:32:26 +00001818 assert((*startBuf == '@') && "bogus @throw location");
1819
1820 std::string buf;
1821 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffc7d2df22008-01-19 00:42:38 +00001822 if (S->getThrowExpr())
1823 buf = "objc_exception_throw(";
1824 else // add an implicit argument
1825 buf = "objc_exception_throw(_caught";
Mike Stump11289f42009-09-09 15:08:12 +00001826
Steve Naroff29788342008-07-25 15:41:30 +00001827 // handle "@ throw" correctly.
1828 const char *wBuf = strchr(startBuf, 'w');
1829 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1830 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001831
Steve Naroffa733c7f2007-11-07 15:32:26 +00001832 const char *semiBuf = strchr(startBuf, ';');
1833 assert((*semiBuf == ';') && "@throw: can't find ';'");
1834 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1835 buf = ");";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001836 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroffa733c7f2007-11-07 15:32:26 +00001837 return 0;
1838}
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001839
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001840Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerc6d91c02007-10-17 22:35:30 +00001841 // Create a new string expression.
1842 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlssond8499822007-10-29 05:01:08 +00001843 std::string StrEncoding;
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00001844 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00001845 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
1846 StrEncoding.length(), false,StrType,
1847 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00001848 ReplaceStmt(Exp, Replacement);
Mike Stump11289f42009-09-09 15:08:12 +00001849
Chris Lattner4431a1b2007-11-30 22:53:43 +00001850 // Replace this subexpr in the parent.
Steve Naroff22216db2008-12-04 23:50:32 +00001851 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattner69534692007-10-24 16:57:36 +00001852 return Replacement;
Chris Lattnera7c19fe2007-10-16 22:36:42 +00001853}
1854
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001855Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff2654e182008-12-22 22:16:07 +00001856 if (!SelGetUidFunctionDecl)
1857 SynthSelGetUidFunctionDecl();
Steve Naroffe4f9b232007-11-05 14:50:49 +00001858 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1859 // Create a call to sel_registerName("selName").
1860 llvm::SmallVector<Expr*, 8> SelExprs;
1861 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00001862 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00001863 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00001864 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00001865 false, argType, SourceLocation()));
Steve Naroffe4f9b232007-11-05 14:50:49 +00001866 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1867 &SelExprs[0], SelExprs.size());
Chris Lattner2e0d2602008-01-31 19:37:57 +00001868 ReplaceStmt(Exp, SelExp);
Steve Naroff22216db2008-12-04 23:50:32 +00001869 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffe4f9b232007-11-05 14:50:49 +00001870 return SelExp;
1871}
1872
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001873CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff574440f2007-10-24 22:48:43 +00001874 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001875 // Get the type, we will need to reference it in a couple spots.
Steve Naroff574440f2007-10-24 22:48:43 +00001876 QualType msgSendType = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001877
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001878 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek5a201952009-02-07 01:47:29 +00001879 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001880
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001881 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattner3c799d72007-10-24 17:06:59 +00001882 QualType pToFunc = Context->getPointerType(msgSendType);
Mike Stump11289f42009-09-09 15:08:12 +00001883 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc,
Anders Carlssona2615922009-07-31 00:48:10 +00001884 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00001885 DRE,
Douglas Gregora11693b2008-11-12 17:17:38 +00001886 /*isLvalue=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001887
John McCall9dd450b2009-09-21 23:43:11 +00001888 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00001889
Ted Kremenekd7b4f402009-02-09 20:51:47 +00001890 return new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
1891 SourceLocation());
Steve Naroff574440f2007-10-24 22:48:43 +00001892}
1893
Steve Naroff50d42052007-11-01 13:24:47 +00001894static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1895 const char *&startRef, const char *&endRef) {
1896 while (startBuf < endBuf) {
1897 if (*startBuf == '<')
1898 startRef = startBuf; // mark the start.
1899 if (*startBuf == '>') {
Steve Naroff1b232132007-11-09 12:50:28 +00001900 if (startRef && *startRef == '<') {
1901 endRef = startBuf; // mark the end.
1902 return true;
1903 }
1904 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00001905 }
1906 startBuf++;
1907 }
1908 return false;
1909}
1910
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001911static void scanToNextArgument(const char *&argRef) {
1912 int angle = 0;
1913 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1914 if (*argRef == '<')
1915 angle++;
1916 else if (*argRef == '>')
1917 angle--;
1918 argRef++;
1919 }
1920 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1921}
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00001922
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001923bool RewriteObjC::needToScanForQualifiers(QualType T) {
Steve Naroffc277ad12009-07-18 15:33:26 +00001924 return T->isObjCQualifiedIdType() || T->isObjCQualifiedInterfaceType();
Steve Naroff50d42052007-11-01 13:24:47 +00001925}
1926
Steve Naroff873bd842008-07-29 18:15:38 +00001927void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1928 QualType Type = E->getType();
1929 if (needToScanForQualifiers(Type)) {
Steve Naroffdbfc6932008-11-19 21:15:47 +00001930 SourceLocation Loc, EndLoc;
Mike Stump11289f42009-09-09 15:08:12 +00001931
Steve Naroffdbfc6932008-11-19 21:15:47 +00001932 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1933 Loc = ECE->getLParenLoc();
1934 EndLoc = ECE->getRParenLoc();
1935 } else {
1936 Loc = E->getLocStart();
1937 EndLoc = E->getLocEnd();
1938 }
1939 // This will defend against trying to rewrite synthesized expressions.
1940 if (Loc.isInvalid() || EndLoc.isInvalid())
1941 return;
1942
Steve Naroff873bd842008-07-29 18:15:38 +00001943 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffdbfc6932008-11-19 21:15:47 +00001944 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff873bd842008-07-29 18:15:38 +00001945 const char *startRef = 0, *endRef = 0;
1946 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1947 // Get the locations of the startRef, endRef.
1948 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1949 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1950 // Comment out the protocol references.
1951 InsertText(LessLoc, "/*", 2);
1952 InsertText(GreaterLoc, "*/", 2);
1953 }
1954 }
1955}
1956
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001957void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001958 SourceLocation Loc;
1959 QualType Type;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001960 const FunctionProtoType *proto = 0;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001961 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1962 Loc = VD->getLocation();
1963 Type = VD->getType();
1964 }
1965 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1966 Loc = FD->getLocation();
1967 // Check for ObjC 'id' and class types that have been adorned with protocol
1968 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall9dd450b2009-09-21 23:43:11 +00001969 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001970 assert(funcType && "missing function type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001971 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001972 if (!proto)
1973 return;
1974 Type = proto->getResultType();
1975 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00001976 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
1977 Loc = FD->getLocation();
1978 Type = FD->getType();
1979 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001980 else
1981 return;
Mike Stump11289f42009-09-09 15:08:12 +00001982
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001983 if (needToScanForQualifiers(Type)) {
Steve Naroff50d42052007-11-01 13:24:47 +00001984 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00001985
Steve Naroff50d42052007-11-01 13:24:47 +00001986 const char *endBuf = SM->getCharacterData(Loc);
1987 const char *startBuf = endBuf;
Steve Naroff930e0992008-05-31 05:02:17 +00001988 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroff50d42052007-11-01 13:24:47 +00001989 startBuf--; // scan backward (from the decl location) for return type.
1990 const char *startRef = 0, *endRef = 0;
1991 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1992 // Get the locations of the startRef, endRef.
1993 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1994 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1995 // Comment out the protocol references.
Chris Lattner1780a852008-01-31 19:42:41 +00001996 InsertText(LessLoc, "/*", 2);
1997 InsertText(GreaterLoc, "*/", 2);
Steve Naroff37e011c2007-10-31 04:38:33 +00001998 }
1999 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002000 if (!proto)
2001 return; // most likely, was a variable
Steve Naroff50d42052007-11-01 13:24:47 +00002002 // Now check arguments.
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002003 const char *startBuf = SM->getCharacterData(Loc);
2004 const char *startFuncBuf = startBuf;
Steve Naroff50d42052007-11-01 13:24:47 +00002005 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2006 if (needToScanForQualifiers(proto->getArgType(i))) {
2007 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002008
Steve Naroff50d42052007-11-01 13:24:47 +00002009 const char *endBuf = startBuf;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002010 // scan forward (from the decl location) for argument types.
2011 scanToNextArgument(endBuf);
Steve Naroff50d42052007-11-01 13:24:47 +00002012 const char *startRef = 0, *endRef = 0;
2013 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2014 // Get the locations of the startRef, endRef.
Mike Stump11289f42009-09-09 15:08:12 +00002015 SourceLocation LessLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002016 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump11289f42009-09-09 15:08:12 +00002017 SourceLocation GreaterLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002018 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002019 // Comment out the protocol references.
Chris Lattner1780a852008-01-31 19:42:41 +00002020 InsertText(LessLoc, "/*", 2);
2021 InsertText(GreaterLoc, "*/", 2);
Steve Naroff50d42052007-11-01 13:24:47 +00002022 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002023 startBuf = ++endBuf;
2024 }
2025 else {
Steve Naroffc884aa82008-08-06 15:58:23 +00002026 // If the function name is derived from a macro expansion, then the
2027 // argument buffer will not follow the name. Need to speak with Chris.
2028 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002029 startBuf++; // scan forward (from the decl location) for argument types.
2030 startBuf++;
2031 }
Steve Naroff50d42052007-11-01 13:24:47 +00002032 }
Steve Naroff37e011c2007-10-31 04:38:33 +00002033}
2034
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002035// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002036void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002037 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2038 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002039 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002040 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002041 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002042 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002043 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002044 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002045 SelGetUidIdent, getFuncType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002046 FunctionDecl::Extern, false);
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002047}
2048
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002049void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002050 // declared in <objc/objc.h>
Douglas Gregor1e21c192009-01-09 01:47:02 +00002051 if (FD->getIdentifier() &&
2052 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002053 SelGetUidFunctionDecl = FD;
Steve Naroff37e011c2007-10-31 04:38:33 +00002054 return;
2055 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002056 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002057}
2058
Steve Naroff17978c42008-03-11 17:37:02 +00002059// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002060void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroff17978c42008-03-11 17:37:02 +00002061 if (SuperContructorFunctionDecl)
2062 return;
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002063 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroff17978c42008-03-11 17:37:02 +00002064 llvm::SmallVector<QualType, 16> ArgTys;
2065 QualType argT = Context->getObjCIdType();
2066 assert(!argT.isNull() && "Can't find 'id' type");
2067 ArgTys.push_back(argT);
2068 ArgTys.push_back(argT);
2069 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2070 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002071 false, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002072 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002073 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002074 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002075 FunctionDecl::Extern, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002076}
2077
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002078// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002079void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002080 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2081 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002082 QualType argT = Context->getObjCIdType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002083 assert(!argT.isNull() && "Can't find 'id' type");
2084 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002085 argT = Context->getObjCSelType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002086 assert(!argT.isNull() && "Can't find 'SEL' type");
2087 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002088 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002089 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002090 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002091 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002092 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002093 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002094 FunctionDecl::Extern, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002095}
2096
Steve Naroff7fa2f042007-11-15 10:28:18 +00002097// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002098void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002099 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2100 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002101 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002102 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002103 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002104 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2105 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2106 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002107 argT = Context->getObjCSelType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002108 assert(!argT.isNull() && "Can't find 'SEL' type");
2109 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002110 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff7fa2f042007-11-15 10:28:18 +00002111 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002112 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002113 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002114 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002115 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002116 FunctionDecl::Extern, false);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002117}
2118
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002119// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002120void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002121 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2122 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002123 QualType argT = Context->getObjCIdType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002124 assert(!argT.isNull() && "Can't find 'id' type");
2125 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002126 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002127 assert(!argT.isNull() && "Can't find 'SEL' type");
2128 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002129 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002130 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002131 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002132 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002133 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002134 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002135 FunctionDecl::Extern, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002136}
2137
Mike Stump11289f42009-09-09 15:08:12 +00002138// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002139// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002140void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump11289f42009-09-09 15:08:12 +00002141 IdentifierInfo *msgSendIdent =
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002142 &Context->Idents.get("objc_msgSendSuper_stret");
2143 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002144 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002145 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002146 &Context->Idents.get("objc_super"));
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002147 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2148 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2149 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002150 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002151 assert(!argT.isNull() && "Can't find 'SEL' type");
2152 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002153 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002154 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002155 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002156 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002157 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002158 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002159 FunctionDecl::Extern, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002160}
2161
Steve Naroff2e4e3852008-05-08 22:02:18 +00002162// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002163void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002164 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2165 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002166 QualType argT = Context->getObjCIdType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002167 assert(!argT.isNull() && "Can't find 'id' type");
2168 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002169 argT = Context->getObjCSelType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002170 assert(!argT.isNull() && "Can't find 'SEL' type");
2171 ArgTys.push_back(argT);
Steve Naroff2e4e3852008-05-08 22:02:18 +00002172 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002173 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002174 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002175 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002176 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002177 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002178 FunctionDecl::Extern, false);
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002179}
2180
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002181// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002182void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002183 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2184 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002185 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002186 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002187 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002188 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002189 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002190 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002191 getClassIdent, getClassType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002192 FunctionDecl::Extern, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002193}
2194
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002195// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002196void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002197 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2198 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002199 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002200 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002201 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002202 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002203 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002204 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002205 getClassIdent, getClassType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002206 FunctionDecl::Extern, false);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002207}
2208
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002209Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffce8e8862008-03-15 00:55:56 +00002210 QualType strType = getConstantStringStructType();
2211
2212 std::string S = "__NSConstantStringImpl_";
Steve Naroffa6141f02008-05-31 03:35:42 +00002213
2214 std::string tmpName = InFileName;
2215 unsigned i;
2216 for (i=0; i < tmpName.length(); i++) {
2217 char c = tmpName.at(i);
2218 // replace any non alphanumeric characters with '_'.
2219 if (!isalpha(c) && (c < '0' || c > '9'))
2220 tmpName[i] = '_';
2221 }
2222 S += tmpName;
2223 S += "_";
Steve Naroffce8e8862008-03-15 00:55:56 +00002224 S += utostr(NumObjCStringLiterals++);
2225
Steve Naroff00a31762008-03-27 22:29:16 +00002226 Preamble += "static __NSConstantStringImpl " + S;
2227 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2228 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffce8e8862008-03-15 00:55:56 +00002229 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek2d470fc2008-09-13 05:16:45 +00002230 std::string prettyBufS;
2231 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00002232 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2233 PrintingPolicy(LangOpts));
Steve Naroff00a31762008-03-27 22:29:16 +00002234 Preamble += prettyBuf.str();
2235 Preamble += ",";
Steve Naroffdad80ba2008-03-15 01:36:04 +00002236 // The minus 2 removes the begin/end double quotes.
Steve Naroff00a31762008-03-27 22:29:16 +00002237 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002238
2239 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2240 &Context->Idents.get(S.c_str()), strType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002241 VarDecl::Static);
Ted Kremenek5a201952009-02-07 01:47:29 +00002242 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2243 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002244 Context->getPointerType(DRE->getType()),
Steve Naroffce8e8862008-03-15 00:55:56 +00002245 SourceLocation());
Steve Naroff265a6b92007-11-08 14:30:50 +00002246 // cast to NSConstantString *
Mike Stump11289f42009-09-09 15:08:12 +00002247 CastExpr *cast = new (Context) CStyleCastExpr(Exp->getType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002248 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002249 Unop, Exp->getType(),
2250 SourceLocation(),
Anders Carlssona2615922009-07-31 00:48:10 +00002251 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002252 ReplaceStmt(Exp, cast);
Steve Naroff22216db2008-12-04 23:50:32 +00002253 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff265a6b92007-11-08 14:30:50 +00002254 return cast;
Steve Naroffa397efd2007-11-03 11:27:19 +00002255}
2256
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002257ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002258 // check if we are sending a message to 'super'
Douglas Gregorffca3a22009-01-09 17:18:27 +00002259 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002260
Douglas Gregor8ea1f532008-11-04 14:56:14 +00002261 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
Mike Stump11289f42009-09-09 15:08:12 +00002262 const ObjCObjectPointerType *OPT =
John McCall9dd450b2009-09-21 23:43:11 +00002263 Super->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00002264 assert(OPT);
2265 const ObjCInterfaceType *IT = OPT->getInterfaceType();
Chris Lattnera9b3cae2008-06-21 18:04:54 +00002266 return IT->getDecl();
2267 }
2268 return 0;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002269}
2270
2271// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002272QualType RewriteObjC::getSuperStructType() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002273 if (!SuperStructDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002274 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002275 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002276 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002277 QualType FieldTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002278
Steve Naroff7fa2f042007-11-15 10:28:18 +00002279 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002280 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002281 // struct objc_class *super;
Mike Stump11289f42009-09-09 15:08:12 +00002282 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor91f84212008-12-11 16:49:14 +00002283
Steve Naroff7fa2f042007-11-15 10:28:18 +00002284 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002285 for (unsigned i = 0; i < 2; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002286 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2287 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002288 FieldTypes[i], 0,
2289 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002290 /*Mutable=*/false));
Douglas Gregor91f84212008-12-11 16:49:14 +00002291 }
Mike Stump11289f42009-09-09 15:08:12 +00002292
Douglas Gregor91f84212008-12-11 16:49:14 +00002293 SuperStructDecl->completeDefinition(*Context);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002294 }
2295 return Context->getTagDeclType(SuperStructDecl);
2296}
2297
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002298QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffce8e8862008-03-15 00:55:56 +00002299 if (!ConstantStringDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002300 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002301 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002302 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffce8e8862008-03-15 00:55:56 +00002303 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002304
Steve Naroffce8e8862008-03-15 00:55:56 +00002305 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002306 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffce8e8862008-03-15 00:55:56 +00002307 // int flags;
Mike Stump11289f42009-09-09 15:08:12 +00002308 FieldTypes[1] = Context->IntTy;
Steve Naroffce8e8862008-03-15 00:55:56 +00002309 // char *str;
Mike Stump11289f42009-09-09 15:08:12 +00002310 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffce8e8862008-03-15 00:55:56 +00002311 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002312 FieldTypes[3] = Context->LongTy;
Douglas Gregor91f84212008-12-11 16:49:14 +00002313
Steve Naroffce8e8862008-03-15 00:55:56 +00002314 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002315 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002316 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2317 ConstantStringDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002318 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002319 FieldTypes[i], 0,
Douglas Gregor91f84212008-12-11 16:49:14 +00002320 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002321 /*Mutable=*/true));
Douglas Gregor91f84212008-12-11 16:49:14 +00002322 }
2323
2324 ConstantStringDecl->completeDefinition(*Context);
Steve Naroffce8e8862008-03-15 00:55:56 +00002325 }
2326 return Context->getTagDeclType(ConstantStringDecl);
2327}
2328
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002329Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002330 if (!SelGetUidFunctionDecl)
2331 SynthSelGetUidFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002332 if (!MsgSendFunctionDecl)
2333 SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002334 if (!MsgSendSuperFunctionDecl)
2335 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002336 if (!MsgSendStretFunctionDecl)
2337 SynthMsgSendStretFunctionDecl();
2338 if (!MsgSendSuperStretFunctionDecl)
2339 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002340 if (!MsgSendFpretFunctionDecl)
2341 SynthMsgSendFpretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002342 if (!GetClassFunctionDecl)
2343 SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002344 if (!GetMetaClassFunctionDecl)
2345 SynthGetMetaClassFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002346
Steve Naroff7fa2f042007-11-15 10:28:18 +00002347 // default to objc_msgSend().
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002348 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2349 // May need to use objc_msgSend_stret() as well.
2350 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroffd9803712009-04-29 16:37:50 +00002351 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2352 QualType resultType = mDecl->getResultType();
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002353 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002354 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002355 else if (resultType->isRealFloatingType())
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002356 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002357 }
Mike Stump11289f42009-09-09 15:08:12 +00002358
Steve Naroff574440f2007-10-24 22:48:43 +00002359 // Synthesize a call to objc_msgSend().
2360 llvm::SmallVector<Expr*, 8> MsgExprs;
2361 IdentifierInfo *clsName = Exp->getClassName();
Mike Stump11289f42009-09-09 15:08:12 +00002362
Steve Naroff574440f2007-10-24 22:48:43 +00002363 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2364 if (clsName) { // class message.
Steve Naroff6c79f972008-07-24 19:44:33 +00002365 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2366 // the 'super' idiom within a class method.
Daniel Dunbar07d07852009-10-18 21:17:35 +00002367 if (clsName->getName() == "super") {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002368 MsgSendFlavor = MsgSendSuperFunctionDecl;
2369 if (MsgSendStretFlavor)
2370 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2371 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002372
2373 ObjCInterfaceDecl *SuperDecl =
Steve Naroff677ab3a2008-10-27 17:20:55 +00002374 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002375
2376 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002377
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002378 // set the receiver to self, the first argument to all methods.
Steve Naroffd9803712009-04-29 16:37:50 +00002379 InitExprs.push_back(
Mike Stump11289f42009-09-09 15:08:12 +00002380 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002381 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002382 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroffd9803712009-04-29 16:37:50 +00002383 Context->getObjCIdType(),
2384 SourceLocation()),
2385 Context->getObjCIdType(),
2386 SourceLocation(), SourceLocation())); // set the 'receiver'.
2387
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002388 llvm::SmallVector<Expr*, 8> ClsExprs;
2389 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002390 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002391 SuperDecl->getIdentifier()->getNameStart(),
2392 SuperDecl->getIdentifier()->getLength(),
2393 false, argType, SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002394 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002395 &ClsExprs[0],
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002396 ClsExprs.size());
2397 // To turn off a warning, type-cast to 'id'
Douglas Gregore200adc2008-10-27 19:41:14 +00002398 InitExprs.push_back( // set 'super class', using objc_getClass().
Mike Stump11289f42009-09-09 15:08:12 +00002399 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002400 CastExpr::CK_Unknown,
Douglas Gregore200adc2008-10-27 19:41:14 +00002401 Cls, Context->getObjCIdType(),
Mike Stump11289f42009-09-09 15:08:12 +00002402 SourceLocation(), SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002403 // struct objc_super
2404 QualType superType = getSuperStructType();
Steve Naroff0b844f02008-03-11 18:14:26 +00002405 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002406
Steve Naroff0b844f02008-03-11 18:14:26 +00002407 if (LangOpts.Microsoft) {
2408 SynthSuperContructorFunctionDecl();
2409 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002410 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff0b844f02008-03-11 18:14:26 +00002411 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002412 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002413 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002414 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002415 // The code for super is a little tricky to prevent collision with
2416 // the structure definition in the header. The rewriter has it's own
2417 // internal definition (__rw_objc_super) that is uses. This is why
2418 // we need the cast below. For example:
2419 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2420 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002421 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002422 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002423 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002424 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
2425 CastExpr::CK_Unknown, SuperRep,
Anders Carlssona2615922009-07-31 00:48:10 +00002426 Context->getPointerType(superType),
Mike Stump11289f42009-09-09 15:08:12 +00002427 SourceLocation(), SourceLocation());
2428 } else {
Steve Naroff0b844f02008-03-11 18:14:26 +00002429 // (struct objc_super) { <exprs from above> }
Mike Stump11289f42009-09-09 15:08:12 +00002430 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2431 &InitExprs[0], InitExprs.size(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002432 SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00002433 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE,
Chris Lattner07d754a2008-10-26 23:43:26 +00002434 false);
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002435 // struct objc_super *
Ted Kremenek5a201952009-02-07 01:47:29 +00002436 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002437 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002438 SourceLocation());
Steve Naroff0b844f02008-03-11 18:14:26 +00002439 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002440 MsgExprs.push_back(SuperRep);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002441 } else {
2442 llvm::SmallVector<Expr*, 8> ClsExprs;
2443 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002444 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002445 clsName->getNameStart(),
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002446 clsName->getLength(),
2447 false, argType,
2448 SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002449 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002450 &ClsExprs[0],
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002451 ClsExprs.size());
2452 MsgExprs.push_back(Cls);
2453 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002454 } else { // instance message.
2455 Expr *recExpr = Exp->getReceiver();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002456
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002457 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002458 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002459 if (MsgSendStretFlavor)
2460 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002461 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002462
Steve Naroff7fa2f042007-11-15 10:28:18 +00002463 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002464
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002465 InitExprs.push_back(
Mike Stump11289f42009-09-09 15:08:12 +00002466 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002467 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002468 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff97adf602008-07-16 22:35:27 +00002469 Context->getObjCIdType(),
Douglas Gregore200adc2008-10-27 19:41:14 +00002470 SourceLocation()),
2471 Context->getObjCIdType(),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002472 SourceLocation(), SourceLocation())); // set the 'receiver'.
Mike Stump11289f42009-09-09 15:08:12 +00002473
Steve Naroff7fa2f042007-11-15 10:28:18 +00002474 llvm::SmallVector<Expr*, 8> ClsExprs;
2475 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002476 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002477 SuperDecl->getIdentifier()->getNameStart(),
2478 SuperDecl->getIdentifier()->getLength(),
2479 false, argType, SourceLocation()));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002480 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002481 &ClsExprs[0],
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002482 ClsExprs.size());
Fariborz Jahaniand5db92b2007-12-05 17:29:46 +00002483 // To turn off a warning, type-cast to 'id'
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002484 InitExprs.push_back(
Douglas Gregore200adc2008-10-27 19:41:14 +00002485 // set 'super class', using objc_getClass().
Mike Stump11289f42009-09-09 15:08:12 +00002486 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002487 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002488 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002489 // struct objc_super
2490 QualType superType = getSuperStructType();
Steve Naroff17978c42008-03-11 17:37:02 +00002491 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002492
Steve Naroff17978c42008-03-11 17:37:02 +00002493 if (LangOpts.Microsoft) {
2494 SynthSuperContructorFunctionDecl();
2495 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002496 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff17978c42008-03-11 17:37:02 +00002497 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002498 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002499 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002500 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002501 // The code for super is a little tricky to prevent collision with
2502 // the structure definition in the header. The rewriter has it's own
2503 // internal definition (__rw_objc_super) that is uses. This is why
2504 // we need the cast below. For example:
2505 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2506 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002507 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002508 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002509 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002510 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Anders Carlssona2615922009-07-31 00:48:10 +00002511 CastExpr::CK_Unknown,
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002512 SuperRep, Context->getPointerType(superType),
Mike Stump11289f42009-09-09 15:08:12 +00002513 SourceLocation(), SourceLocation());
Steve Naroff17978c42008-03-11 17:37:02 +00002514 } else {
2515 // (struct objc_super) { <exprs from above> }
Mike Stump11289f42009-09-09 15:08:12 +00002516 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2517 &InitExprs[0], InitExprs.size(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002518 SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00002519 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002520 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002521 MsgExprs.push_back(SuperRep);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002522 } else {
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002523 // Remove all type-casts because it may contain objc-style types; e.g.
2524 // Foo<Proto> *.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002525 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002526 recExpr = CE->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002527 recExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002528 CastExpr::CK_Unknown, recExpr,
Mike Stump11289f42009-09-09 15:08:12 +00002529 Context->getObjCIdType(),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002530 SourceLocation(), SourceLocation());
Steve Naroff7fa2f042007-11-15 10:28:18 +00002531 MsgExprs.push_back(recExpr);
2532 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002533 }
Steve Naroffa397efd2007-11-03 11:27:19 +00002534 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff574440f2007-10-24 22:48:43 +00002535 llvm::SmallVector<Expr*, 8> SelExprs;
2536 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002537 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002538 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002539 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00002540 false, argType, SourceLocation()));
Steve Naroff574440f2007-10-24 22:48:43 +00002541 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2542 &SelExprs[0], SelExprs.size());
2543 MsgExprs.push_back(SelExp);
Mike Stump11289f42009-09-09 15:08:12 +00002544
Steve Naroff574440f2007-10-24 22:48:43 +00002545 // Now push any user supplied arguments.
2546 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroffe7f18192007-11-14 23:54:14 +00002547 Expr *userExpr = Exp->getArg(i);
Steve Narofff60782b2007-11-15 02:58:25 +00002548 // Make all implicit casts explicit...ICE comes in handy:-)
2549 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2550 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregore200adc2008-10-27 19:41:14 +00002551 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002552 ? Context->getObjCIdType()
Douglas Gregore200adc2008-10-27 19:41:14 +00002553 : ICE->getType();
Anders Carlssona2615922009-07-31 00:48:10 +00002554 userExpr = new (Context) CStyleCastExpr(type, CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002555 userExpr, type, SourceLocation(),
Anders Carlssona2615922009-07-31 00:48:10 +00002556 SourceLocation());
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002557 }
2558 // Make id<P...> cast into an 'id' cast.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002559 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002560 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregorf19b2312008-10-28 15:36:24 +00002561 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002562 userExpr = CE->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002563 userExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002564 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002565 userExpr, Context->getObjCIdType(),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002566 SourceLocation(), SourceLocation());
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002567 }
Mike Stump11289f42009-09-09 15:08:12 +00002568 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002569 MsgExprs.push_back(userExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00002570 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2571 // out the argument in the original expression (since we aren't deleting
2572 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2573 //Exp->setArg(i, 0);
Steve Naroff574440f2007-10-24 22:48:43 +00002574 }
Steve Narofff36987c2007-11-04 22:37:50 +00002575 // Generate the funky cast.
2576 CastExpr *cast;
2577 llvm::SmallVector<QualType, 8> ArgTypes;
2578 QualType returnType;
Mike Stump11289f42009-09-09 15:08:12 +00002579
Steve Narofff36987c2007-11-04 22:37:50 +00002580 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff44864e42007-11-15 10:43:57 +00002581 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2582 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2583 else
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002584 ArgTypes.push_back(Context->getObjCIdType());
2585 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattnera4997152009-02-20 18:43:26 +00002586 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Narofff36987c2007-11-04 22:37:50 +00002587 // Push any user argument types.
Chris Lattnera4997152009-02-20 18:43:26 +00002588 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2589 E = OMD->param_end(); PI != E; ++PI) {
2590 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump11289f42009-09-09 15:08:12 +00002591 ? Context->getObjCIdType()
Chris Lattnera4997152009-02-20 18:43:26 +00002592 : (*PI)->getType();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002593 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00002594 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002595 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002596 t = Context->getPointerType(BPT->getPointeeType());
2597 }
Steve Naroff98eb8d12007-11-05 14:36:37 +00002598 ArgTypes.push_back(t);
2599 }
Chris Lattnera4997152009-02-20 18:43:26 +00002600 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2601 ? Context->getObjCIdType() : OMD->getResultType();
Steve Narofff36987c2007-11-04 22:37:50 +00002602 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002603 returnType = Context->getObjCIdType();
Steve Narofff36987c2007-11-04 22:37:50 +00002604 }
2605 // Get the type, we will need to reference it in a couple spots.
Steve Naroff7fa2f042007-11-15 10:28:18 +00002606 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002607
Steve Narofff36987c2007-11-04 22:37:50 +00002608 // Create a reference to the objc_msgSend() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002609 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002610 SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002611
Mike Stump11289f42009-09-09 15:08:12 +00002612 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Narofff36987c2007-11-04 22:37:50 +00002613 // If we don't do this cast, we get the following bizarre warning/note:
2614 // xx.m:13: warning: function called through a non-compatible type
2615 // xx.m:13: note: if this code is reached, the program will abort
Mike Stump11289f42009-09-09 15:08:12 +00002616 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy),
2617 CastExpr::CK_Unknown, DRE,
Douglas Gregore200adc2008-10-27 19:41:14 +00002618 Context->getPointerType(Context->VoidTy),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002619 SourceLocation(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002620
Steve Narofff36987c2007-11-04 22:37:50 +00002621 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002622 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002623 &ArgTypes[0], ArgTypes.size(),
Steve Naroff327f0f42008-03-18 02:02:04 +00002624 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002625 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Narofff36987c2007-11-04 22:37:50 +00002626 castType = Context->getPointerType(castType);
Mike Stump11289f42009-09-09 15:08:12 +00002627 cast = new (Context) CStyleCastExpr(castType, CastExpr::CK_Unknown, cast,
2628 castType, SourceLocation(),
Anders Carlssona2615922009-07-31 00:48:10 +00002629 SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002630
2631 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00002632 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00002633
John McCall9dd450b2009-09-21 23:43:11 +00002634 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002635 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002636 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002637 FT->getResultType(), SourceLocation());
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002638 Stmt *ReplacingStmt = CE;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002639 if (MsgSendStretFlavor) {
2640 // We have the method which returns a struct/union. Must also generate
2641 // call to objc_msgSend_stret and hang both varieties on a conditional
2642 // expression which dictate which one to envoke depending on size of
2643 // method's return type.
Mike Stump11289f42009-09-09 15:08:12 +00002644
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002645 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002646 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002647 SourceLocation());
2648 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Mike Stump11289f42009-09-09 15:08:12 +00002649 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy),
2650 CastExpr::CK_Unknown, STDRE,
Douglas Gregore200adc2008-10-27 19:41:14 +00002651 Context->getPointerType(Context->VoidTy),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002652 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002653 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002654 castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002655 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002656 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002657 castType = Context->getPointerType(castType);
Anders Carlssona2615922009-07-31 00:48:10 +00002658 cast = new (Context) CStyleCastExpr(castType, CastExpr::CK_Unknown,
2659 cast, castType, SourceLocation(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002660
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002661 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00002662 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00002663
John McCall9dd450b2009-09-21 23:43:11 +00002664 FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002665 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002666 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002667 FT->getResultType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002668
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002669 // Build sizeof(returnType)
Mike Stump11289f42009-09-09 15:08:12 +00002670 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCall4c98fd82009-11-04 07:28:41 +00002671 Context->getTrivialDeclaratorInfo(returnType),
Sebastian Redl6f282892008-11-11 17:56:53 +00002672 Context->getSizeType(),
2673 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002674 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2675 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2676 // For X86 it is more complicated and some kind of target specific routine
2677 // is needed to decide what to do.
Mike Stump11289f42009-09-09 15:08:12 +00002678 unsigned IntSize =
Chris Lattner37e05872008-03-05 18:54:05 +00002679 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Mike Stump11289f42009-09-09 15:08:12 +00002680 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002681 Context->IntTy,
2682 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002683 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
2684 BinaryOperator::LE,
2685 Context->IntTy,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002686 SourceLocation());
2687 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump11289f42009-09-09 15:08:12 +00002688 ConditionalOperator *CondExpr =
Douglas Gregor7e112b02009-08-26 14:37:04 +00002689 new (Context) ConditionalOperator(lessThanExpr,
2690 SourceLocation(), CE,
2691 SourceLocation(), STCE, returnType);
Ted Kremenek5a201952009-02-07 01:47:29 +00002692 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002693 }
Mike Stump11289f42009-09-09 15:08:12 +00002694 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002695 return ReplacingStmt;
2696}
2697
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002698Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002699 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Mike Stump11289f42009-09-09 15:08:12 +00002700
Steve Naroff574440f2007-10-24 22:48:43 +00002701 // Now do the actual rewrite.
Chris Lattner2e0d2602008-01-31 19:37:57 +00002702 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00002703
2704 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002705 return ReplacingStmt;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002706}
2707
Steve Naroffd9803712009-04-29 16:37:50 +00002708// typedef struct objc_object Protocol;
2709QualType RewriteObjC::getProtocolType() {
2710 if (!ProtocolTypeDecl) {
John McCall703a3f82009-10-24 08:00:42 +00002711 DeclaratorInfo *DInfo
2712 = Context->getTrivialDeclaratorInfo(Context->getObjCIdType());
Steve Naroffd9803712009-04-29 16:37:50 +00002713 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002714 SourceLocation(),
Steve Naroffd9803712009-04-29 16:37:50 +00002715 &Context->Idents.get("Protocol"),
John McCall703a3f82009-10-24 08:00:42 +00002716 DInfo);
Steve Naroffd9803712009-04-29 16:37:50 +00002717 }
2718 return Context->getTypeDeclType(ProtocolTypeDecl);
2719}
2720
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00002721/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroffd9803712009-04-29 16:37:50 +00002722/// a synthesized/forward data reference (to the protocol's metadata).
2723/// The forward references (and metadata) are generated in
2724/// RewriteObjC::HandleTranslationUnit().
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002725Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroffd9803712009-04-29 16:37:50 +00002726 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
2727 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump11289f42009-09-09 15:08:12 +00002728 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregored6c7442009-11-23 11:41:28 +00002729 ID, getProtocolType(), 0, VarDecl::Extern);
Steve Naroffd9803712009-04-29 16:37:50 +00002730 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
2731 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
2732 Context->getPointerType(DRE->getType()),
2733 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002734 CastExpr *castExpr = new (Context) CStyleCastExpr(DerefExpr->getType(),
2735 CastExpr::CK_Unknown,
2736 DerefExpr, DerefExpr->getType(),
Steve Naroffd9803712009-04-29 16:37:50 +00002737 SourceLocation(), SourceLocation());
2738 ReplaceStmt(Exp, castExpr);
2739 ProtocolExprDecls.insert(Exp->getProtocol());
Mike Stump11289f42009-09-09 15:08:12 +00002740 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00002741 return castExpr;
Mike Stump11289f42009-09-09 15:08:12 +00002742
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00002743}
2744
Mike Stump11289f42009-09-09 15:08:12 +00002745bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002746 const char *endBuf) {
2747 while (startBuf < endBuf) {
2748 if (*startBuf == '#') {
2749 // Skip whitespace.
2750 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2751 ;
2752 if (!strncmp(startBuf, "if", strlen("if")) ||
2753 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2754 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2755 !strncmp(startBuf, "define", strlen("define")) ||
2756 !strncmp(startBuf, "undef", strlen("undef")) ||
2757 !strncmp(startBuf, "else", strlen("else")) ||
2758 !strncmp(startBuf, "elif", strlen("elif")) ||
2759 !strncmp(startBuf, "endif", strlen("endif")) ||
2760 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2761 !strncmp(startBuf, "include", strlen("include")) ||
2762 !strncmp(startBuf, "import", strlen("import")) ||
2763 !strncmp(startBuf, "include_next", strlen("include_next")))
2764 return true;
2765 }
2766 startBuf++;
2767 }
2768 return false;
2769}
2770
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002771/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002772/// an objective-c class with ivars.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002773void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002774 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002775 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Mike Stump11289f42009-09-09 15:08:12 +00002776 assert(CDecl->getNameAsCString() &&
Douglas Gregor77324f32008-11-17 14:58:09 +00002777 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00002778 // Do not synthesize more than once.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002779 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00002780 return;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002781 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattner8d1c04f2008-03-16 21:08:55 +00002782 int NumIvars = CDecl->ivar_size();
Steve Naroffdde78982007-11-14 19:25:57 +00002783 SourceLocation LocStart = CDecl->getLocStart();
2784 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00002785
Steve Naroffdde78982007-11-14 19:25:57 +00002786 const char *startBuf = SM->getCharacterData(LocStart);
2787 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00002788
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002789 // If no ivars and no root or if its root, directly or indirectly,
2790 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattner8d1c04f2008-03-16 21:08:55 +00002791 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2792 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner184e65d2009-04-14 23:22:57 +00002793 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Chris Lattner9cc55f52008-01-31 19:51:04 +00002794 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002795 return;
2796 }
Mike Stump11289f42009-09-09 15:08:12 +00002797
2798 // FIXME: This has potential of causing problem. If
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002799 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002800 Result += "\nstruct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002801 Result += CDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00002802 if (LangOpts.Microsoft)
2803 Result += "_IMPL";
Steve Naroffdc5b6b22008-03-12 00:25:36 +00002804
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002805 if (NumIvars > 0) {
Steve Naroffdde78982007-11-14 19:25:57 +00002806 const char *cursor = strchr(startBuf, '{');
Mike Stump11289f42009-09-09 15:08:12 +00002807 assert((cursor && endBuf)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002808 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002809 // If the buffer contains preprocessor directives, we do more fine-grained
2810 // rewrites. This is intended to fix code that looks like (which occurs in
2811 // NSURL.h, for example):
2812 //
2813 // #ifdef XYZ
2814 // @interface Foo : NSObject
2815 // #else
2816 // @interface FooBar : NSObject
2817 // #endif
2818 // {
2819 // int i;
2820 // }
2821 // @end
2822 //
2823 // This clause is segregated to avoid breaking the common case.
2824 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump11289f42009-09-09 15:08:12 +00002825 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002826 CDecl->getClassLoc();
2827 const char *endHeader = SM->getCharacterData(L);
Chris Lattner184e65d2009-04-14 23:22:57 +00002828 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002829
Chris Lattnerf5b77512009-02-20 18:18:36 +00002830 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002831 // advance to the end of the referenced protocols.
2832 while (endHeader < cursor && *endHeader != '>') endHeader++;
2833 endHeader++;
2834 }
2835 // rewrite the original header
2836 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2837 } else {
2838 // rewrite the original header *without* disturbing the '{'
Steve Naroffb0e33902009-12-04 21:36:32 +00002839 ReplaceText(LocStart, cursor-startBuf, Result.c_str(), Result.size());
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002840 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002841 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroffdde78982007-11-14 19:25:57 +00002842 Result = "\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002843 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00002844 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002845 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00002846 Result += "_IVARS;\n";
Mike Stump11289f42009-09-09 15:08:12 +00002847
Steve Naroffdde78982007-11-14 19:25:57 +00002848 // insert the super class structure definition.
Chris Lattner1780a852008-01-31 19:42:41 +00002849 SourceLocation OnePastCurly =
2850 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2851 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Naroffdde78982007-11-14 19:25:57 +00002852 }
2853 cursor++; // past '{'
Mike Stump11289f42009-09-09 15:08:12 +00002854
Steve Naroffdde78982007-11-14 19:25:57 +00002855 // Now comment out any visibility specifiers.
2856 while (cursor < endBuf) {
2857 if (*cursor == '@') {
2858 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner174a8252007-11-14 22:57:51 +00002859 // Skip whitespace.
2860 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2861 /*scan*/;
2862
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002863 // FIXME: presence of @public, etc. inside comment results in
2864 // this transformation as well, which is still correct c-code.
Steve Naroffdde78982007-11-14 19:25:57 +00002865 if (!strncmp(cursor, "public", strlen("public")) ||
2866 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffaf91b9a2008-04-04 22:34:24 +00002867 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002868 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattner1780a852008-01-31 19:42:41 +00002869 InsertText(atLoc, "// ", 3);
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002870 }
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002871 // FIXME: If there are cases where '<' is used in ivar declaration part
2872 // of user code, then scan the ivar list and use needToScanForQualifiers
2873 // for type checking.
2874 else if (*cursor == '<') {
2875 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner1780a852008-01-31 19:42:41 +00002876 InsertText(atLoc, "/* ", 3);
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002877 cursor = strchr(cursor, '>');
2878 cursor++;
2879 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner1780a852008-01-31 19:42:41 +00002880 InsertText(atLoc, " */", 3);
Steve Naroff295570a2008-10-30 12:09:33 +00002881 } else if (*cursor == '^') { // rewrite block specifier.
2882 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2883 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002884 }
Steve Naroffdde78982007-11-14 19:25:57 +00002885 cursor++;
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002886 }
Steve Naroffdde78982007-11-14 19:25:57 +00002887 // Don't forget to add a ';'!!
Chris Lattner1780a852008-01-31 19:42:41 +00002888 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Naroffdde78982007-11-14 19:25:57 +00002889 } else { // we don't have any instance variables - insert super struct.
Chris Lattner184e65d2009-04-14 23:22:57 +00002890 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroffdde78982007-11-14 19:25:57 +00002891 Result += " {\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002892 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00002893 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002894 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00002895 Result += "_IVARS;\n};\n";
Chris Lattner9cc55f52008-01-31 19:51:04 +00002896 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002897 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002898 // Mark this struct as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002899 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff13e74872008-05-06 18:26:51 +00002900 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002901}
2902
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002903// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002904/// class methods.
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002905template<typename MethodIterator>
2906void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
2907 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +00002908 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002909 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +00002910 const char *ClassName,
2911 std::string &Result) {
Chris Lattner31bc07e2007-12-12 07:46:12 +00002912 if (MethodBegin == MethodEnd) return;
Mike Stump11289f42009-09-09 15:08:12 +00002913
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00002914 static bool objc_impl_method = false;
Chris Lattner31bc07e2007-12-12 07:46:12 +00002915 if (!objc_impl_method) {
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002916 /* struct _objc_method {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00002917 SEL _cmd;
2918 char *method_types;
2919 void *_imp;
2920 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002921 */
Chris Lattner211f8b82007-10-25 17:07:24 +00002922 Result += "\nstruct _objc_method {\n";
2923 Result += "\tSEL _cmd;\n";
2924 Result += "\tchar *method_types;\n";
2925 Result += "\tvoid *_imp;\n";
2926 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002927
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002928 objc_impl_method = true;
Fariborz Jahanian74a1cfa2007-10-19 00:36:46 +00002929 }
Mike Stump11289f42009-09-09 15:08:12 +00002930
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002931 // Build _objc_method_list for class's methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00002932
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002933 /* struct {
2934 struct _objc_method_list *next_method;
2935 int method_count;
2936 struct _objc_method method_list[];
2937 }
2938 */
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002939 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002940 Result += "\nstatic struct {\n";
2941 Result += "\tstruct _objc_method_list *next_method;\n";
2942 Result += "\tint method_count;\n";
2943 Result += "\tstruct _objc_method method_list[";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002944 Result += utostr(NumMethods);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002945 Result += "];\n} _OBJC_";
Chris Lattner31bc07e2007-12-12 07:46:12 +00002946 Result += prefix;
2947 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2948 Result += "_METHODS_";
2949 Result += ClassName;
Steve Naroffb327e492008-03-12 17:18:30 +00002950 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattner31bc07e2007-12-12 07:46:12 +00002951 Result += IsInstanceMethod ? "inst" : "cls";
2952 Result += "_meth\")))= ";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002953 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00002954
Chris Lattner31bc07e2007-12-12 07:46:12 +00002955 Result += "\t,{{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00002956 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattner31bc07e2007-12-12 07:46:12 +00002957 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002958 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattner31bc07e2007-12-12 07:46:12 +00002959 Result += "\", \"";
2960 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002961 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00002962 Result += MethodInternalNames[*MethodBegin];
2963 Result += "}\n";
2964 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2965 Result += "\t ,{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00002966 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00002967 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002968 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +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];
Fariborz Jahanian56338352007-11-13 21:02:00 +00002973 Result += "}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00002974 }
Chris Lattner31bc07e2007-12-12 07:46:12 +00002975 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002976}
2977
Steve Naroffd9803712009-04-29 16:37:50 +00002978/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner390d39a2008-07-21 21:32:27 +00002979void RewriteObjC::
Steve Naroffd9803712009-04-29 16:37:50 +00002980RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
2981 const char *ClassName, std::string &Result) {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00002982 static bool objc_protocol_methods = false;
Steve Naroffd9803712009-04-29 16:37:50 +00002983
2984 // Output struct protocol_methods holder of method selector and type.
2985 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2986 /* struct protocol_methods {
2987 SEL _cmd;
2988 char *method_types;
2989 }
2990 */
2991 Result += "\nstruct _protocol_methods {\n";
2992 Result += "\tstruct objc_selector *_cmd;\n";
2993 Result += "\tchar *method_types;\n";
2994 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002995
Steve Naroffd9803712009-04-29 16:37:50 +00002996 objc_protocol_methods = true;
2997 }
2998 // Do not synthesize the protocol more than once.
2999 if (ObjCSynthesizedProtocols.count(PDecl))
3000 return;
Mike Stump11289f42009-09-09 15:08:12 +00003001
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003002 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3003 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3004 PDecl->instmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003005 /* struct _objc_protocol_method_list {
3006 int protocol_method_count;
3007 struct protocol_methods protocols[];
3008 }
Steve Naroff251084d2008-03-12 01:06:30 +00003009 */
Steve Naroffd9803712009-04-29 16:37:50 +00003010 Result += "\nstatic struct {\n";
3011 Result += "\tint protocol_method_count;\n";
3012 Result += "\tstruct _protocol_methods protocol_methods[";
3013 Result += utostr(NumMethods);
3014 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3015 Result += PDecl->getNameAsString();
3016 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3017 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003018
Steve Naroffd9803712009-04-29 16:37:50 +00003019 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003020 for (ObjCProtocolDecl::instmeth_iterator
3021 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003022 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003023 if (I == PDecl->instmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003024 Result += "\t ,{{(struct objc_selector *)\"";
3025 else
3026 Result += "\t ,{(struct objc_selector *)\"";
3027 Result += (*I)->getSelector().getAsString().c_str();
3028 std::string MethodTypeString;
3029 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3030 Result += "\", \"";
3031 Result += MethodTypeString;
3032 Result += "\"}\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003033 }
Steve Naroffd9803712009-04-29 16:37:50 +00003034 Result += "\t }\n};\n";
3035 }
Mike Stump11289f42009-09-09 15:08:12 +00003036
Steve Naroffd9803712009-04-29 16:37:50 +00003037 // Output class methods declared in this protocol.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003038 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3039 PDecl->classmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003040 if (NumMethods > 0) {
3041 /* struct _objc_protocol_method_list {
3042 int protocol_method_count;
3043 struct protocol_methods protocols[];
3044 }
3045 */
3046 Result += "\nstatic struct {\n";
3047 Result += "\tint protocol_method_count;\n";
3048 Result += "\tstruct _protocol_methods protocol_methods[";
3049 Result += utostr(NumMethods);
3050 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3051 Result += PDecl->getNameAsString();
3052 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3053 "{\n\t";
3054 Result += utostr(NumMethods);
3055 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003056
Steve Naroffd9803712009-04-29 16:37:50 +00003057 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003058 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003059 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003060 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003061 if (I == PDecl->classmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003062 Result += "\t ,{{(struct objc_selector *)\"";
3063 else
3064 Result += "\t ,{(struct objc_selector *)\"";
3065 Result += (*I)->getSelector().getAsString().c_str();
3066 std::string MethodTypeString;
3067 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3068 Result += "\", \"";
3069 Result += MethodTypeString;
3070 Result += "\"}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003071 }
Steve Naroffd9803712009-04-29 16:37:50 +00003072 Result += "\t }\n};\n";
3073 }
3074
3075 // Output:
3076 /* struct _objc_protocol {
3077 // Objective-C 1.0 extensions
3078 struct _objc_protocol_extension *isa;
3079 char *protocol_name;
3080 struct _objc_protocol **protocol_list;
3081 struct _objc_protocol_method_list *instance_methods;
3082 struct _objc_protocol_method_list *class_methods;
Mike Stump11289f42009-09-09 15:08:12 +00003083 };
Steve Naroffd9803712009-04-29 16:37:50 +00003084 */
3085 static bool objc_protocol = false;
3086 if (!objc_protocol) {
3087 Result += "\nstruct _objc_protocol {\n";
3088 Result += "\tstruct _objc_protocol_extension *isa;\n";
3089 Result += "\tchar *protocol_name;\n";
3090 Result += "\tstruct _objc_protocol **protocol_list;\n";
3091 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3092 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003093 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003094
Steve Naroffd9803712009-04-29 16:37:50 +00003095 objc_protocol = true;
Chris Lattner388f6e92008-07-21 21:33:21 +00003096 }
Mike Stump11289f42009-09-09 15:08:12 +00003097
Steve Naroffd9803712009-04-29 16:37:50 +00003098 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3099 Result += PDecl->getNameAsString();
3100 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3101 "{\n\t0, \"";
3102 Result += PDecl->getNameAsString();
3103 Result += "\", 0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003104 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003105 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3106 Result += PDecl->getNameAsString();
3107 Result += ", ";
3108 }
3109 else
3110 Result += "0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003111 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003112 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3113 Result += PDecl->getNameAsString();
3114 Result += "\n";
3115 }
3116 else
3117 Result += "0\n";
3118 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003119
Steve Naroffd9803712009-04-29 16:37:50 +00003120 // Mark this protocol as having been generated.
3121 if (!ObjCSynthesizedProtocols.insert(PDecl))
3122 assert(false && "protocol already synthesized");
3123
3124}
3125
3126void RewriteObjC::
3127RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3128 const char *prefix, const char *ClassName,
3129 std::string &Result) {
3130 if (Protocols.empty()) return;
Mike Stump11289f42009-09-09 15:08:12 +00003131
Steve Naroffd9803712009-04-29 16:37:50 +00003132 for (unsigned i = 0; i != Protocols.size(); i++)
3133 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3134
Chris Lattner388f6e92008-07-21 21:33:21 +00003135 // Output the top lovel protocol meta-data for the class.
3136 /* struct _objc_protocol_list {
3137 struct _objc_protocol_list *next;
3138 int protocol_count;
3139 struct _objc_protocol *class_protocols[];
3140 }
3141 */
3142 Result += "\nstatic struct {\n";
3143 Result += "\tstruct _objc_protocol_list *next;\n";
3144 Result += "\tint protocol_count;\n";
3145 Result += "\tstruct _objc_protocol *class_protocols[";
3146 Result += utostr(Protocols.size());
3147 Result += "];\n} _OBJC_";
3148 Result += prefix;
3149 Result += "_PROTOCOLS_";
3150 Result += ClassName;
3151 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3152 "{\n\t0, ";
3153 Result += utostr(Protocols.size());
3154 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003155
Chris Lattner388f6e92008-07-21 21:33:21 +00003156 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003157 Result += Protocols[0]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003158 Result += " \n";
Mike Stump11289f42009-09-09 15:08:12 +00003159
Chris Lattner388f6e92008-07-21 21:33:21 +00003160 for (unsigned i = 1; i != Protocols.size(); i++) {
3161 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003162 Result += Protocols[i]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003163 Result += "\n";
3164 }
3165 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003166}
3167
Steve Naroffd9803712009-04-29 16:37:50 +00003168
Mike Stump11289f42009-09-09 15:08:12 +00003169/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003170/// implementation.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003171void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003172 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003173 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003174 // Find category declaration for this implementation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003175 ObjCCategoryDecl *CDecl;
Mike Stump11289f42009-09-09 15:08:12 +00003176 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003177 CDecl = CDecl->getNextClassCategory())
3178 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3179 break;
Mike Stump11289f42009-09-09 15:08:12 +00003180
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003181 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003182 FullCategoryName += '_';
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003183 FullCategoryName += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003184
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003185 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003186 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003187 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003188
3189 // If any of our property implementations have associated getters or
3190 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003191 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3192 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003193 Prop != PropEnd; ++Prop) {
3194 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3195 continue;
3196 if (!(*Prop)->getPropertyIvarDecl())
3197 continue;
3198 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3199 if (!PD)
3200 continue;
3201 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3202 InstanceMethods.push_back(Getter);
3203 if (PD->isReadOnly())
3204 continue;
3205 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3206 InstanceMethods.push_back(Setter);
3207 }
3208 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003209 true, "CATEGORY_", FullCategoryName.c_str(),
3210 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003211
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003212 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003213 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003214 false, "CATEGORY_", FullCategoryName.c_str(),
3215 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003216
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003217 // Protocols referenced in class declaration?
Fariborz Jahanian989e0392007-11-13 22:09:49 +00003218 // Null CDecl is case of a category implementation with no category interface
3219 if (CDecl)
Steve Naroffd9803712009-04-29 16:37:50 +00003220 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3221 FullCategoryName.c_str(), Result);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003222 /* struct _objc_category {
3223 char *category_name;
3224 char *class_name;
3225 struct _objc_method_list *instance_methods;
3226 struct _objc_method_list *class_methods;
3227 struct _objc_protocol_list *protocols;
3228 // Objective-C 1.0 extensions
3229 uint32_t size; // sizeof (struct _objc_category)
Mike Stump11289f42009-09-09 15:08:12 +00003230 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003231 // @property decl.
Mike Stump11289f42009-09-09 15:08:12 +00003232 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003233 */
Mike Stump11289f42009-09-09 15:08:12 +00003234
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003235 static bool objc_category = false;
3236 if (!objc_category) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003237 Result += "\nstruct _objc_category {\n";
3238 Result += "\tchar *category_name;\n";
3239 Result += "\tchar *class_name;\n";
3240 Result += "\tstruct _objc_method_list *instance_methods;\n";
3241 Result += "\tstruct _objc_method_list *class_methods;\n";
3242 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003243 Result += "\tunsigned int size;\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003244 Result += "\tstruct _objc_property_list *instance_properties;\n";
3245 Result += "};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003246 objc_category = true;
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003247 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003248 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3249 Result += FullCategoryName;
Steve Naroffb327e492008-03-12 17:18:30 +00003250 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003251 Result += IDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003252 Result += "\"\n\t, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003253 Result += ClassDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003254 Result += "\"\n";
Mike Stump11289f42009-09-09 15:08:12 +00003255
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003256 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003257 Result += "\t, (struct _objc_method_list *)"
3258 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3259 Result += FullCategoryName;
3260 Result += "\n";
3261 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003262 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003263 Result += "\t, 0\n";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003264 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003265 Result += "\t, (struct _objc_method_list *)"
3266 "&_OBJC_CATEGORY_CLASS_METHODS_";
3267 Result += FullCategoryName;
3268 Result += "\n";
3269 }
3270 else
3271 Result += "\t, 0\n";
Mike Stump11289f42009-09-09 15:08:12 +00003272
Chris Lattnerf5b77512009-02-20 18:18:36 +00003273 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump11289f42009-09-09 15:08:12 +00003274 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003275 Result += FullCategoryName;
3276 Result += "\n";
3277 }
3278 else
3279 Result += "\t, 0\n";
3280 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003281}
3282
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003283/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3284/// ivar offset.
Mike Stump11289f42009-09-09 15:08:12 +00003285void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
3286 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003287 std::string &Result) {
Steve Naroffde7d0f62008-07-16 18:22:22 +00003288 if (ivar->isBitField()) {
3289 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3290 // place all bitfields at offset 0.
3291 Result += "0";
3292 } else {
3293 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003294 Result += IDecl->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003295 if (LangOpts.Microsoft)
3296 Result += "_IMPL";
3297 Result += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003298 Result += ivar->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003299 Result += ")";
3300 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003301}
3302
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003303//===----------------------------------------------------------------------===//
3304// Meta Data Emission
3305//===----------------------------------------------------------------------===//
3306
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003307void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003308 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003309 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00003310
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003311 // Explictly declared @interface's are already synthesized.
Steve Naroffaac654a2009-04-20 20:09:33 +00003312 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump11289f42009-09-09 15:08:12 +00003313 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003314 // produce correct synthesis as yet.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003315 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003316 }
Mike Stump11289f42009-09-09 15:08:12 +00003317
Chris Lattner30d23e82007-12-12 07:56:42 +00003318 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003319 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump11289f42009-09-09 15:08:12 +00003320 ? IDecl->ivar_size()
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003321 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003322 if (NumIvars > 0) {
3323 static bool objc_ivar = false;
3324 if (!objc_ivar) {
3325 /* struct _objc_ivar {
3326 char *ivar_name;
3327 char *ivar_type;
3328 int ivar_offset;
Mike Stump11289f42009-09-09 15:08:12 +00003329 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003330 */
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003331 Result += "\nstruct _objc_ivar {\n";
3332 Result += "\tchar *ivar_name;\n";
3333 Result += "\tchar *ivar_type;\n";
3334 Result += "\tint ivar_offset;\n";
3335 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003336
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003337 objc_ivar = true;
3338 }
3339
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003340 /* struct {
3341 int ivar_count;
3342 struct _objc_ivar ivar_list[nIvars];
Mike Stump11289f42009-09-09 15:08:12 +00003343 };
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003344 */
Mike Stump11289f42009-09-09 15:08:12 +00003345 Result += "\nstatic struct {\n";
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003346 Result += "\tint ivar_count;\n";
3347 Result += "\tstruct _objc_ivar ivar_list[";
3348 Result += utostr(NumIvars);
3349 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003350 Result += IDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003351 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003352 "{\n\t";
3353 Result += utostr(NumIvars);
3354 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003355
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003356 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor5f662052009-04-23 03:23:08 +00003357 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003358 if (!IDecl->ivar_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00003359 for (ObjCImplementationDecl::ivar_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003360 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor5f662052009-04-23 03:23:08 +00003361 IV != IVEnd; ++IV)
3362 IVars.push_back(*IV);
3363 IVI = IVars.begin();
3364 IVE = IVars.end();
Chris Lattner30d23e82007-12-12 07:56:42 +00003365 } else {
3366 IVI = CDecl->ivar_begin();
3367 IVE = CDecl->ivar_end();
3368 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003369 Result += "\t,{{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003370 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003371 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003372 std::string TmpString, StrEncoding;
3373 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3374 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003375 Result += StrEncoding;
3376 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003377 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003378 Result += "}\n";
Chris Lattner30d23e82007-12-12 07:56:42 +00003379 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003380 Result += "\t ,{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003381 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003382 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003383 std::string TmpString, StrEncoding;
3384 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3385 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003386 Result += StrEncoding;
3387 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003388 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003389 Result += "}\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003390 }
Mike Stump11289f42009-09-09 15:08:12 +00003391
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003392 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003393 }
Mike Stump11289f42009-09-09 15:08:12 +00003394
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003395 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003396 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003397 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003398
3399 // If any of our property implementations have associated getters or
3400 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003401 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3402 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003403 Prop != PropEnd; ++Prop) {
3404 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3405 continue;
3406 if (!(*Prop)->getPropertyIvarDecl())
3407 continue;
3408 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3409 if (!PD)
3410 continue;
3411 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3412 InstanceMethods.push_back(Getter);
3413 if (PD->isReadOnly())
3414 continue;
3415 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3416 InstanceMethods.push_back(Setter);
3417 }
3418 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003419 true, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003420
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003421 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003422 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003423 false, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003424
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003425 // Protocols referenced in class declaration?
Steve Naroffd9803712009-04-29 16:37:50 +00003426 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3427 "CLASS", CDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003428
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003429 // Declaration of class/meta-class metadata
3430 /* struct _objc_class {
3431 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003432 const char *super_class_name;
3433 char *name;
3434 long version;
3435 long info;
3436 long instance_size;
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003437 struct _objc_ivar_list *ivars;
3438 struct _objc_method_list *methods;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003439 struct objc_cache *cache;
3440 struct objc_protocol_list *protocols;
3441 const char *ivar_layout;
3442 struct _objc_class_ext *ext;
Mike Stump11289f42009-09-09 15:08:12 +00003443 };
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003444 */
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003445 static bool objc_class = false;
3446 if (!objc_class) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003447 Result += "\nstruct _objc_class {\n";
3448 Result += "\tstruct _objc_class *isa;\n";
3449 Result += "\tconst char *super_class_name;\n";
3450 Result += "\tchar *name;\n";
3451 Result += "\tlong version;\n";
3452 Result += "\tlong info;\n";
3453 Result += "\tlong instance_size;\n";
3454 Result += "\tstruct _objc_ivar_list *ivars;\n";
3455 Result += "\tstruct _objc_method_list *methods;\n";
3456 Result += "\tstruct objc_cache *cache;\n";
3457 Result += "\tstruct _objc_protocol_list *protocols;\n";
3458 Result += "\tconst char *ivar_layout;\n";
3459 Result += "\tstruct _objc_class_ext *ext;\n";
3460 Result += "};\n";
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003461 objc_class = true;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003462 }
Mike Stump11289f42009-09-09 15:08:12 +00003463
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003464 // Meta-class metadata generation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003465 ObjCInterfaceDecl *RootClass = 0;
3466 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003467 while (SuperClass) {
3468 RootClass = SuperClass;
3469 SuperClass = SuperClass->getSuperClass();
3470 }
3471 SuperClass = CDecl->getSuperClass();
Mike Stump11289f42009-09-09 15:08:12 +00003472
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003473 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003474 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003475 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003476 "{\n\t(struct _objc_class *)\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003477 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003478 Result += "\"";
3479
3480 if (SuperClass) {
3481 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003482 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003483 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003484 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003485 Result += "\"";
3486 }
3487 else {
3488 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003489 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003490 Result += "\"";
3491 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003492 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003493 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003494 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003495 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff0b844f02008-03-11 18:14:26 +00003496 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003497 Result += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003498 Result += "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003499 }
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003500 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003501 Result += ", 0\n";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003502 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003503 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003504 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003505 Result += ",0,0\n";
3506 }
Fariborz Jahanian486f7182007-10-24 20:54:23 +00003507 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003508 Result += "\t,0,0,0,0\n";
3509 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003510
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003511 // class metadata generation.
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003512 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003513 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003514 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003515 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003516 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003517 if (SuperClass) {
3518 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003519 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003520 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003521 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003522 Result += "\"";
3523 }
3524 else {
3525 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003526 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003527 Result += "\"";
3528 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003529 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003530 Result += ", 0,1";
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003531 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003532 Result += ",0";
3533 else {
3534 // class has size. Must synthesize its size.
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00003535 Result += ",sizeof(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003536 Result += CDecl->getNameAsString();
Steve Naroff14a07462008-03-10 23:33:22 +00003537 if (LangOpts.Microsoft)
3538 Result += "_IMPL";
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003539 Result += ")";
3540 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003541 if (NumIvars > 0) {
Steve Naroff17978c42008-03-11 17:37:02 +00003542 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003543 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003544 Result += "\n\t";
3545 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003546 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003547 Result += ",0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003548 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003549 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003550 Result += CDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003551 Result += ", 0\n\t";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003552 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003553 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003554 Result += ",0,0";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003555 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003556 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003557 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003558 Result += ", 0,0\n";
3559 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003560 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003561 Result += ",0,0,0\n";
3562 Result += "};\n";
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003563}
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003564
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003565/// RewriteImplementations - This routine rewrites all method implementations
3566/// and emits meta-data.
3567
Steve Narofff8cfd162008-11-13 20:07:04 +00003568void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003569 int ClsDefCount = ClassImplementation.size();
3570 int CatDefCount = CategoryImplementation.size();
Mike Stump11289f42009-09-09 15:08:12 +00003571
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003572 // Rewrite implemented methods
3573 for (int i = 0; i < ClsDefCount; i++)
3574 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003575
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00003576 for (int i = 0; i < CatDefCount; i++)
3577 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofff8cfd162008-11-13 20:07:04 +00003578}
Mike Stump11289f42009-09-09 15:08:12 +00003579
Steve Narofff8cfd162008-11-13 20:07:04 +00003580void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3581 int ClsDefCount = ClassImplementation.size();
3582 int CatDefCount = CategoryImplementation.size();
3583
Steve Naroff30ac2222008-05-07 21:23:49 +00003584 // This is needed for determining instance variable offsets.
Mike Stump11289f42009-09-09 15:08:12 +00003585 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003586 // For each implemented class, write out all its meta data.
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003587 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003588 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump11289f42009-09-09 15:08:12 +00003589
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003590 // For each implemented category, write out all its meta data.
3591 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003592 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroffd9803712009-04-29 16:37:50 +00003593
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003594 // Write objc_symtab metadata
3595 /*
3596 struct _objc_symtab
3597 {
3598 long sel_ref_cnt;
3599 SEL *refs;
3600 short cls_def_cnt;
3601 short cat_def_cnt;
3602 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump11289f42009-09-09 15:08:12 +00003603 };
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003604 */
Mike Stump11289f42009-09-09 15:08:12 +00003605
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003606 Result += "\nstruct _objc_symtab {\n";
3607 Result += "\tlong sel_ref_cnt;\n";
3608 Result += "\tSEL *refs;\n";
3609 Result += "\tshort cls_def_cnt;\n";
3610 Result += "\tshort cat_def_cnt;\n";
3611 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3612 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003613
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003614 Result += "static struct _objc_symtab "
Steve Naroffb327e492008-03-12 17:18:30 +00003615 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003616 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003617 + ", " + utostr(CatDefCount) + "\n";
3618 for (int i = 0; i < ClsDefCount; i++) {
3619 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003620 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003621 Result += "\n";
3622 }
Mike Stump11289f42009-09-09 15:08:12 +00003623
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003624 for (int i = 0; i < CatDefCount; i++) {
3625 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003626 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003627 Result += "_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003628 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003629 Result += "\n";
3630 }
Mike Stump11289f42009-09-09 15:08:12 +00003631
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003632 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003633
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003634 // Write objc_module metadata
Mike Stump11289f42009-09-09 15:08:12 +00003635
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003636 /*
3637 struct _objc_module {
3638 long version;
3639 long size;
3640 const char *name;
3641 struct _objc_symtab *symtab;
3642 }
3643 */
Mike Stump11289f42009-09-09 15:08:12 +00003644
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003645 Result += "\nstruct _objc_module {\n";
3646 Result += "\tlong version;\n";
3647 Result += "\tlong size;\n";
3648 Result += "\tconst char *name;\n";
3649 Result += "\tstruct _objc_symtab *symtab;\n";
3650 Result += "};\n\n";
3651 Result += "static struct _objc_module "
Steve Naroffb327e492008-03-12 17:18:30 +00003652 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003653 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003654 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003655 Result += "};\n\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003656
3657 if (LangOpts.Microsoft) {
Steve Naroffd9803712009-04-29 16:37:50 +00003658 if (ProtocolExprDecls.size()) {
3659 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
3660 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump11289f42009-09-09 15:08:12 +00003661 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00003662 E = ProtocolExprDecls.end(); I != E; ++I) {
3663 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
3664 Result += (*I)->getNameAsString();
3665 Result += " = &_OBJC_PROTOCOL_";
3666 Result += (*I)->getNameAsString();
3667 Result += ";\n";
3668 }
3669 Result += "#pragma data_seg(pop)\n\n";
3670 }
Steve Naroff945a3b12008-03-10 20:43:59 +00003671 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffcab93d52008-05-07 00:06:16 +00003672 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003673 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3674 Result += "&_OBJC_MODULES;\n";
3675 Result += "#pragma data_seg(pop)\n\n";
3676 }
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003677}
Chris Lattnera7c19fe2007-10-16 22:36:42 +00003678
Steve Naroff677ab3a2008-10-27 17:20:55 +00003679std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3680 const char *funcName,
3681 std::string Tag) {
3682 const FunctionType *AFT = CE->getFunctionType();
3683 QualType RT = AFT->getResultType();
3684 std::string StructRef = "struct " + Tag;
3685 std::string S = "static " + RT.getAsString() + " __" +
3686 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00003687
Steve Naroff677ab3a2008-10-27 17:20:55 +00003688 BlockDecl *BD = CE->getBlockDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003689
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003690 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump11289f42009-09-09 15:08:12 +00003691 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Narofff26a1d42009-02-02 17:19:26 +00003692 // block (to reference imported block decl refs).
3693 S += "(" + StructRef + " *__cself)";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003694 } else if (BD->param_empty()) {
3695 S += "(" + StructRef + " *__cself)";
3696 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003697 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003698 assert(FT && "SynthesizeBlockFunc: No function proto");
3699 S += '(';
3700 // first add the implicit argument.
3701 S += StructRef + " *__cself, ";
3702 std::string ParamStr;
3703 for (BlockDecl::param_iterator AI = BD->param_begin(),
3704 E = BD->param_end(); AI != E; ++AI) {
3705 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003706 ParamStr = (*AI)->getNameAsString();
Douglas Gregor7de59662009-05-29 20:38:28 +00003707 (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003708 S += ParamStr;
3709 }
3710 if (FT->isVariadic()) {
3711 if (!BD->param_empty()) S += ", ";
3712 S += "...";
3713 }
3714 S += ')';
3715 }
3716 S += " {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003717
Steve Naroff677ab3a2008-10-27 17:20:55 +00003718 // Create local declarations to avoid rewriting all closure decl ref exprs.
3719 // First, emit a declaration for all "by ref" decls.
Mike Stump11289f42009-09-09 15:08:12 +00003720 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003721 E = BlockByRefDecls.end(); I != E; ++I) {
3722 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003723 std::string Name = (*I)->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003724 Context->getPointerType((*I)->getType()).getAsStringInternal(Name,
Douglas Gregor7de59662009-05-29 20:38:28 +00003725 Context->PrintingPolicy);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003726 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump11289f42009-09-09 15:08:12 +00003727 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003728 // Next, emit a declaration for all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003729 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003730 E = BlockByCopyDecls.end(); I != E; ++I) {
3731 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003732 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003733 // Handle nested closure invocation. For example:
3734 //
3735 // void (^myImportedClosure)(void);
3736 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003737 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003738 // void (^anotherClosure)(void);
3739 // anotherClosure = ^(void) {
3740 // myImportedClosure(); // import and invoke the closure
3741 // };
3742 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003743 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003744 S += "struct __block_impl *";
3745 else
Douglas Gregor7de59662009-05-29 20:38:28 +00003746 (*I)->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003747 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003748 }
3749 std::string RewrittenStr = RewrittenBlockExprs[CE];
3750 const char *cstr = RewrittenStr.c_str();
3751 while (*cstr++ != '{') ;
3752 S += cstr;
3753 S += "\n";
3754 return S;
3755}
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00003756
Steve Naroff677ab3a2008-10-27 17:20:55 +00003757std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3758 const char *funcName,
3759 std::string Tag) {
3760 std::string StructRef = "struct " + Tag;
3761 std::string S = "static void __";
Mike Stump11289f42009-09-09 15:08:12 +00003762
Steve Naroff677ab3a2008-10-27 17:20:55 +00003763 S += funcName;
3764 S += "_block_copy_" + utostr(i);
3765 S += "(" + StructRef;
3766 S += "*dst, " + StructRef;
3767 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003768 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003769 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003770 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003771 S += (*I)->getNameAsString();
Steve Naroff5ac4eac2008-12-11 20:51:38 +00003772 S += ", (void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003773 S += (*I)->getNameAsString();
Steve Naroff61d879e2008-12-16 15:50:30 +00003774 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);}";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003775 }
3776 S += "\nstatic void __";
3777 S += funcName;
3778 S += "_block_dispose_" + utostr(i);
3779 S += "(" + StructRef;
3780 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003781 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003782 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003783 S += "_Block_object_dispose((void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003784 S += (*I)->getNameAsString();
Steve Naroff61d879e2008-12-16 15:50:30 +00003785 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003786 }
Mike Stump11289f42009-09-09 15:08:12 +00003787 S += "}\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003788 return S;
3789}
3790
3791std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3792 bool hasCopyDisposeHelpers) {
Steve Naroff295570a2008-10-30 12:09:33 +00003793 std::string S = "\nstruct " + Tag;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003794 std::string Constructor = " " + Tag;
Mike Stump11289f42009-09-09 15:08:12 +00003795
Steve Naroff677ab3a2008-10-27 17:20:55 +00003796 S += " {\n struct __block_impl impl;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003797
Steve Naroff677ab3a2008-10-27 17:20:55 +00003798 if (hasCopyDisposeHelpers)
3799 S += " void *copy;\n void *dispose;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003800
Steve Naroff677ab3a2008-10-27 17:20:55 +00003801 Constructor += "(void *fp";
Mike Stump11289f42009-09-09 15:08:12 +00003802
Steve Naroff677ab3a2008-10-27 17:20:55 +00003803 if (hasCopyDisposeHelpers)
3804 Constructor += ", void *copyHelp, void *disposeHelp";
Mike Stump11289f42009-09-09 15:08:12 +00003805
Steve Naroff677ab3a2008-10-27 17:20:55 +00003806 if (BlockDeclRefs.size()) {
3807 // Output all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003808 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003809 E = BlockByCopyDecls.end(); I != E; ++I) {
3810 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003811 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003812 std::string ArgName = "_" + FieldName;
3813 // Handle nested closure invocation. For example:
3814 //
3815 // void (^myImportedBlock)(void);
3816 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003817 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003818 // void (^anotherBlock)(void);
3819 // anotherBlock = ^(void) {
3820 // myImportedBlock(); // import and invoke the closure
3821 // };
3822 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003823 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003824 S += "struct __block_impl *";
3825 Constructor += ", void *" + ArgName;
3826 } else {
Douglas Gregor7de59662009-05-29 20:38:28 +00003827 (*I)->getType().getAsStringInternal(FieldName, Context->PrintingPolicy);
3828 (*I)->getType().getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003829 Constructor += ", " + ArgName;
3830 }
3831 S += FieldName + ";\n";
3832 }
3833 // Output all "by ref" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003834 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003835 E = BlockByRefDecls.end(); I != E; ++I) {
3836 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003837 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003838 std::string ArgName = "_" + FieldName;
3839 // Handle nested closure invocation. For example:
3840 //
3841 // void (^myImportedBlock)(void);
3842 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003843 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003844 // void (^anotherBlock)(void);
3845 // anotherBlock = ^(void) {
3846 // myImportedBlock(); // import and invoke the closure
3847 // };
3848 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003849 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003850 S += "struct __block_impl *";
3851 Constructor += ", void *" + ArgName;
3852 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003853 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName,
Douglas Gregor7de59662009-05-29 20:38:28 +00003854 Context->PrintingPolicy);
Mike Stump11289f42009-09-09 15:08:12 +00003855 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName,
Douglas Gregor7de59662009-05-29 20:38:28 +00003856 Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003857 Constructor += ", " + ArgName;
3858 }
3859 S += FieldName + "; // by ref\n";
3860 }
3861 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00003862 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00003863 if (GlobalVarDecl)
3864 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3865 else
3866 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3867 Constructor += " impl.Size = sizeof(";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003868 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003869
Steve Naroff677ab3a2008-10-27 17:20:55 +00003870 if (hasCopyDisposeHelpers)
3871 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003872
Steve Naroff677ab3a2008-10-27 17:20:55 +00003873 // Initialize all "by copy" arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003874 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003875 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003876 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003877 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00003878 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003879 Constructor += Name + " = (struct __block_impl *)_";
3880 else
3881 Constructor += Name + " = _";
3882 Constructor += Name + ";\n";
3883 }
3884 // Initialize all "by ref" arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003885 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003886 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003887 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003888 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00003889 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003890 Constructor += Name + " = (struct __block_impl *)_";
3891 else
3892 Constructor += Name + " = _";
3893 Constructor += Name + ";\n";
3894 }
3895 } else {
3896 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00003897 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00003898 if (GlobalVarDecl)
3899 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3900 else
3901 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3902 Constructor += " impl.Size = sizeof(";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003903 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3904 if (hasCopyDisposeHelpers)
3905 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3906 }
3907 Constructor += " ";
3908 Constructor += "}\n";
3909 S += Constructor;
3910 S += "};\n";
3911 return S;
3912}
3913
3914void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3915 const char *FunName) {
3916 // Insert closures that were part of the function.
3917 for (unsigned i = 0; i < Blocks.size(); i++) {
3918
3919 CollectBlockDeclRefInfo(Blocks[i]);
3920
3921 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
Mike Stump11289f42009-09-09 15:08:12 +00003922
3923 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
Steve Naroff677ab3a2008-10-27 17:20:55 +00003924 ImportedBlockDecls.size() > 0);
3925
3926 InsertText(FunLocStart, CI.c_str(), CI.size());
3927
3928 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
Mike Stump11289f42009-09-09 15:08:12 +00003929
Steve Naroff677ab3a2008-10-27 17:20:55 +00003930 InsertText(FunLocStart, CF.c_str(), CF.size());
3931
3932 if (ImportedBlockDecls.size()) {
3933 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3934 InsertText(FunLocStart, HF.c_str(), HF.size());
3935 }
Mike Stump11289f42009-09-09 15:08:12 +00003936
Steve Naroff677ab3a2008-10-27 17:20:55 +00003937 BlockDeclRefs.clear();
3938 BlockByRefDecls.clear();
3939 BlockByCopyDecls.clear();
3940 BlockCallExprs.clear();
3941 ImportedBlockDecls.clear();
3942 }
3943 Blocks.clear();
3944 RewrittenBlockExprs.clear();
3945}
3946
3947void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3948 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner86d7d912008-11-24 03:54:41 +00003949 const char *FuncName = FD->getNameAsCString();
Mike Stump11289f42009-09-09 15:08:12 +00003950
Steve Naroff677ab3a2008-10-27 17:20:55 +00003951 SynthesizeBlockLiterals(FunLocStart, FuncName);
3952}
3953
3954void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff295570a2008-10-30 12:09:33 +00003955 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3956 //SourceLocation FunLocStart = MD->getLocStart();
3957 // FIXME: This hack works around a bug in Rewrite.InsertText().
3958 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattnere4b95692008-11-24 03:33:13 +00003959 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003960 // Convert colons to underscores.
3961 std::string::size_type loc = 0;
3962 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3963 FuncName.replace(loc, 1, "_");
Mike Stump11289f42009-09-09 15:08:12 +00003964
Steve Naroff677ab3a2008-10-27 17:20:55 +00003965 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3966}
3967
3968void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3969 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3970 CI != E; ++CI)
3971 if (*CI) {
3972 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3973 GetBlockDeclRefExprs(CBE->getBody());
3974 else
3975 GetBlockDeclRefExprs(*CI);
3976 }
3977 // Handle specific things.
3978 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3979 // FIXME: Handle enums.
3980 if (!isa<FunctionDecl>(CDRE->getDecl()))
3981 BlockDeclRefs.push_back(CDRE);
3982 return;
3983}
3984
3985void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3986 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3987 CI != E; ++CI)
3988 if (*CI) {
3989 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3990 GetBlockCallExprs(CBE->getBody());
3991 else
3992 GetBlockCallExprs(*CI);
3993 }
Mike Stump11289f42009-09-09 15:08:12 +00003994
Steve Naroff677ab3a2008-10-27 17:20:55 +00003995 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
3996 if (CE->getCallee()->getType()->isBlockPointerType()) {
3997 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
3998 }
3999 }
4000 return;
4001}
4002
Steve Naroff350b6652008-10-30 10:07:53 +00004003Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004004 // Navigate to relevant type information.
4005 const char *closureName = 0;
4006 const BlockPointerType *CPT = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004007
Steve Naroff677ab3a2008-10-27 17:20:55 +00004008 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004009 closureName = DRE->getDecl()->getNameAsCString();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004010 CPT = DRE->getType()->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004011 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004012 closureName = CDRE->getDecl()->getNameAsCString();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004013 CPT = CDRE->getType()->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004014 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004015 closureName = MExpr->getMemberDecl()->getNameAsCString();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004016 CPT = MExpr->getType()->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004017 } else {
4018 assert(1 && "RewriteBlockClass: Bad type");
4019 }
4020 assert(CPT && "RewriteBlockClass: Bad type");
John McCall9dd450b2009-09-21 23:43:11 +00004021 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004022 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004023 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004024 // FTP will be null for closures that don't take arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004025
Steve Naroff350b6652008-10-30 10:07:53 +00004026 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
4027 SourceLocation(),
4028 &Context->Idents.get("__block_impl"));
4029 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff677ab3a2008-10-27 17:20:55 +00004030
Steve Naroff350b6652008-10-30 10:07:53 +00004031 // Generate a funky cast.
4032 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00004033
Steve Naroff350b6652008-10-30 10:07:53 +00004034 // Push the block argument type.
4035 ArgTypes.push_back(PtrBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004036 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004037 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff350b6652008-10-30 10:07:53 +00004038 E = FTP->arg_type_end(); I && (I != E); ++I) {
4039 QualType t = *I;
4040 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00004041 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004042 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff350b6652008-10-30 10:07:53 +00004043 t = Context->getPointerType(BPT->getPointeeType());
4044 }
4045 ArgTypes.push_back(t);
4046 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004047 }
Steve Naroff350b6652008-10-30 10:07:53 +00004048 // Now do the pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00004049 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Steve Naroff350b6652008-10-30 10:07:53 +00004050 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004051
Steve Naroff350b6652008-10-30 10:07:53 +00004052 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump11289f42009-09-09 15:08:12 +00004053
4054 CastExpr *BlkCast = new (Context) CStyleCastExpr(PtrBlock,
Anders Carlssona2615922009-07-31 00:48:10 +00004055 CastExpr::CK_Unknown,
4056 Exp->getCallee(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004057 PtrBlock, SourceLocation(),
4058 SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004059 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00004060 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4061 BlkCast);
Steve Naroff350b6652008-10-30 10:07:53 +00004062 //PE->dump();
Mike Stump11289f42009-09-09 15:08:12 +00004063
Douglas Gregor91f84212008-12-11 16:49:14 +00004064 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00004065 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004066 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek5a201952009-02-07 01:47:29 +00004067 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4068 FD->getType());
Mike Stump11289f42009-09-09 15:08:12 +00004069
Anders Carlssona2615922009-07-31 00:48:10 +00004070 CastExpr *FunkCast = new (Context) CStyleCastExpr(PtrToFuncCastType,
4071 CastExpr::CK_Unknown, ME,
Ted Kremenek5a201952009-02-07 01:47:29 +00004072 PtrToFuncCastType,
4073 SourceLocation(),
4074 SourceLocation());
4075 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump11289f42009-09-09 15:08:12 +00004076
Steve Naroff350b6652008-10-30 10:07:53 +00004077 llvm::SmallVector<Expr*, 8> BlkExprs;
4078 // Add the implicit argument.
4079 BlkExprs.push_back(BlkCast);
4080 // Add the user arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004081 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004082 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00004083 BlkExprs.push_back(*I);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004084 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004085 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4086 BlkExprs.size(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004087 Exp->getType(), SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004088 return CE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004089}
4090
4091void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Steve Naroff350b6652008-10-30 10:07:53 +00004092 Stmt *BlockCall = SynthesizeBlockCall(Exp);
4093 ReplaceStmt(Exp, BlockCall);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004094}
4095
Steve Naroffd9803712009-04-29 16:37:50 +00004096// We need to return the rewritten expression to handle cases where the
4097// BlockDeclRefExpr is embedded in another expression being rewritten.
4098// For example:
4099//
4100// int main() {
4101// __block Foo *f;
4102// __block int i;
Mike Stump11289f42009-09-09 15:08:12 +00004103//
Steve Naroffd9803712009-04-29 16:37:50 +00004104// void (^myblock)() = ^() {
4105// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4106// i = 77;
4107// };
4108//}
4109Stmt *RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004110 // FIXME: Add more elaborate code generation required by the ABI.
Ted Kremenek5a201952009-02-07 01:47:29 +00004111 Expr *DerefExpr = new (Context) UnaryOperator(BDRE, UnaryOperator::Deref,
Steve Narofff26a1d42009-02-02 17:19:26 +00004112 Context->getPointerType(BDRE->getType()),
4113 SourceLocation());
4114 // Need parens to enforce precedence.
Ted Kremenek5a201952009-02-07 01:47:29 +00004115 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), DerefExpr);
Steve Narofff26a1d42009-02-02 17:19:26 +00004116 ReplaceStmt(BDRE, PE);
Steve Naroffd9803712009-04-29 16:37:50 +00004117 return PE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004118}
4119
Steve Naroffc989a7b2008-11-03 23:29:32 +00004120void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4121 SourceLocation LocStart = CE->getLParenLoc();
4122 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofff4b992a2008-10-28 20:29:00 +00004123
4124 // Need to avoid trying to rewrite synthesized casts.
4125 if (LocStart.isInvalid())
4126 return;
Steve Naroff3e7ced12008-11-03 11:20:24 +00004127 // Need to avoid trying to rewrite casts contained in macros.
4128 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4129 return;
Mike Stump11289f42009-09-09 15:08:12 +00004130
Steve Naroff677ab3a2008-10-27 17:20:55 +00004131 const char *startBuf = SM->getCharacterData(LocStart);
4132 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00004133
Steve Naroff677ab3a2008-10-27 17:20:55 +00004134 // advance the location to startArgList.
4135 const char *argPtr = startBuf;
Mike Stump11289f42009-09-09 15:08:12 +00004136
Steve Naroff677ab3a2008-10-27 17:20:55 +00004137 while (*argPtr++ && (argPtr < endBuf)) {
4138 switch (*argPtr) {
Mike Stump11289f42009-09-09 15:08:12 +00004139 case '^':
Steve Naroff677ab3a2008-10-27 17:20:55 +00004140 // Replace the '^' with '*'.
4141 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
4142 ReplaceText(LocStart, 1, "*", 1);
4143 break;
4144 }
4145 }
4146 return;
4147}
4148
4149void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4150 SourceLocation DeclLoc = FD->getLocation();
4151 unsigned parenCount = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004152
Steve Naroff677ab3a2008-10-27 17:20:55 +00004153 // We have 1 or more arguments that have closure pointers.
4154 const char *startBuf = SM->getCharacterData(DeclLoc);
4155 const char *startArgList = strchr(startBuf, '(');
Mike Stump11289f42009-09-09 15:08:12 +00004156
Steve Naroff677ab3a2008-10-27 17:20:55 +00004157 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004158
Steve Naroff677ab3a2008-10-27 17:20:55 +00004159 parenCount++;
4160 // advance the location to startArgList.
4161 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4162 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump11289f42009-09-09 15:08:12 +00004163
Steve Naroff677ab3a2008-10-27 17:20:55 +00004164 const char *argPtr = startArgList;
Mike Stump11289f42009-09-09 15:08:12 +00004165
Steve Naroff677ab3a2008-10-27 17:20:55 +00004166 while (*argPtr++ && parenCount) {
4167 switch (*argPtr) {
Mike Stump11289f42009-09-09 15:08:12 +00004168 case '^':
Steve Naroff677ab3a2008-10-27 17:20:55 +00004169 // Replace the '^' with '*'.
4170 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
4171 ReplaceText(DeclLoc, 1, "*", 1);
4172 break;
Mike Stump11289f42009-09-09 15:08:12 +00004173 case '(':
4174 parenCount++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004175 break;
Mike Stump11289f42009-09-09 15:08:12 +00004176 case ')':
Steve Naroff677ab3a2008-10-27 17:20:55 +00004177 parenCount--;
4178 break;
4179 }
4180 }
4181 return;
4182}
4183
4184bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004185 const FunctionProtoType *FTP;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004186 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004187 if (PT) {
John McCall9dd450b2009-09-21 23:43:11 +00004188 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004189 } else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004190 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004191 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall9dd450b2009-09-21 23:43:11 +00004192 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004193 }
4194 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004195 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004196 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +00004197 if (isTopLevelBlockPointerType(*I))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004198 return true;
4199 }
4200 return false;
4201}
4202
Ted Kremenek5a201952009-02-07 01:47:29 +00004203void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4204 const char *&RParen) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004205 const char *argPtr = strchr(Name, '(');
4206 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004207
Steve Naroff677ab3a2008-10-27 17:20:55 +00004208 LParen = argPtr; // output the start.
4209 argPtr++; // skip past the left paren.
4210 unsigned parenCount = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004211
Steve Naroff677ab3a2008-10-27 17:20:55 +00004212 while (*argPtr && parenCount) {
4213 switch (*argPtr) {
4214 case '(': parenCount++; break;
4215 case ')': parenCount--; break;
4216 default: break;
4217 }
4218 if (parenCount) argPtr++;
4219 }
4220 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4221 RParen = argPtr; // output the end
4222}
4223
4224void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4225 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4226 RewriteBlockPointerFunctionArgs(FD);
4227 return;
Mike Stump11289f42009-09-09 15:08:12 +00004228 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004229 // Handle Variables and Typedefs.
4230 SourceLocation DeclLoc = ND->getLocation();
4231 QualType DeclT;
4232 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4233 DeclT = VD->getType();
4234 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4235 DeclT = TDD->getUnderlyingType();
4236 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4237 DeclT = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004238 else
Steve Naroff677ab3a2008-10-27 17:20:55 +00004239 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump11289f42009-09-09 15:08:12 +00004240
Steve Naroff677ab3a2008-10-27 17:20:55 +00004241 const char *startBuf = SM->getCharacterData(DeclLoc);
4242 const char *endBuf = startBuf;
4243 // scan backward (from the decl location) for the end of the previous decl.
4244 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4245 startBuf--;
Mike Stump11289f42009-09-09 15:08:12 +00004246
Steve Naroff677ab3a2008-10-27 17:20:55 +00004247 // *startBuf != '^' if we are dealing with a pointer to function that
4248 // may take block argument types (which will be handled below).
4249 if (*startBuf == '^') {
4250 // Replace the '^' with '*', computing a negative offset.
4251 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4252 ReplaceText(DeclLoc, 1, "*", 1);
4253 }
4254 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4255 // Replace the '^' with '*' for arguments.
4256 DeclLoc = ND->getLocation();
4257 startBuf = SM->getCharacterData(DeclLoc);
4258 const char *argListBegin, *argListEnd;
4259 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4260 while (argListBegin < argListEnd) {
4261 if (*argListBegin == '^') {
4262 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
4263 ReplaceText(CaretLoc, 1, "*", 1);
4264 }
4265 argListBegin++;
4266 }
4267 }
4268 return;
4269}
4270
Mike Stump11289f42009-09-09 15:08:12 +00004271void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004272 // Add initializers for any closure decl refs.
4273 GetBlockDeclRefExprs(Exp->getBody());
4274 if (BlockDeclRefs.size()) {
4275 // Unique all "by copy" declarations.
4276 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4277 if (!BlockDeclRefs[i]->isByRef())
4278 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
4279 // Unique all "by ref" declarations.
4280 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4281 if (BlockDeclRefs[i]->isByRef()) {
4282 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
4283 }
4284 // Find any imported blocks...they will need special attention.
4285 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Steve Naroff5ac4eac2008-12-11 20:51:38 +00004286 if (BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroff832d8902008-11-13 17:40:07 +00004287 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004288 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4289 }
4290 }
4291}
4292
Steve Narofff4b992a2008-10-28 20:29:00 +00004293FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4294 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004295 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump11289f42009-09-09 15:08:12 +00004296 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004297 ID, FType, 0, FunctionDecl::Extern, false,
Douglas Gregor739ef0c2009-02-25 16:33:18 +00004298 false);
Steve Narofff4b992a2008-10-28 20:29:00 +00004299}
4300
Steve Naroffd8907b72008-10-29 18:15:37 +00004301Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004302 Blocks.push_back(Exp);
4303
4304 CollectBlockDeclRefInfo(Exp);
4305 std::string FuncName;
Mike Stump11289f42009-09-09 15:08:12 +00004306
Steve Narofff4b992a2008-10-28 20:29:00 +00004307 if (CurFunctionDef)
Chris Lattnere4b95692008-11-24 03:33:13 +00004308 FuncName = CurFunctionDef->getNameAsString();
Steve Narofff4b992a2008-10-28 20:29:00 +00004309 else if (CurMethodDef) {
Chris Lattnere4b95692008-11-24 03:33:13 +00004310 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofff4b992a2008-10-28 20:29:00 +00004311 // Convert colons to underscores.
4312 std::string::size_type loc = 0;
4313 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4314 FuncName.replace(loc, 1, "_");
Steve Naroffd8907b72008-10-29 18:15:37 +00004315 } else if (GlobalVarDecl)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004316 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump11289f42009-09-09 15:08:12 +00004317
Steve Narofff4b992a2008-10-28 20:29:00 +00004318 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump11289f42009-09-09 15:08:12 +00004319
Steve Narofff4b992a2008-10-28 20:29:00 +00004320 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4321 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump11289f42009-09-09 15:08:12 +00004322
Steve Narofff4b992a2008-10-28 20:29:00 +00004323 // Get a pointer to the function type so we can cast appropriately.
4324 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4325
4326 FunctionDecl *FD;
4327 Expr *NewRep;
Mike Stump11289f42009-09-09 15:08:12 +00004328
Steve Narofff4b992a2008-10-28 20:29:00 +00004329 // Simulate a contructor call...
4330 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004331 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004332
Steve Narofff4b992a2008-10-28 20:29:00 +00004333 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00004334
Steve Naroffe2514232008-10-29 21:23:59 +00004335 // Initialize the block function.
Steve Narofff4b992a2008-10-28 20:29:00 +00004336 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004337 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4338 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004339 CastExpr *castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4340 CastExpr::CK_Unknown, Arg,
Ted Kremenek5a201952009-02-07 01:47:29 +00004341 Context->VoidPtrTy, SourceLocation(),
4342 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004343 InitExprs.push_back(castExpr);
4344
Steve Narofff4b992a2008-10-28 20:29:00 +00004345 if (ImportedBlockDecls.size()) {
4346 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
Steve Naroffe2514232008-10-29 21:23:59 +00004347 FD = SynthBlockInitFunctionDecl(Buf.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004348 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004349 castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4350 CastExpr::CK_Unknown, Arg,
Ted Kremenek5a201952009-02-07 01:47:29 +00004351 Context->VoidPtrTy, SourceLocation(),
4352 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004353 InitExprs.push_back(castExpr);
4354
Steve Narofff4b992a2008-10-28 20:29:00 +00004355 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
Steve Naroffe2514232008-10-29 21:23:59 +00004356 FD = SynthBlockInitFunctionDecl(Buf.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004357 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004358 castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4359 CastExpr::CK_Unknown, Arg,
Ted Kremenek5a201952009-02-07 01:47:29 +00004360 Context->VoidPtrTy, SourceLocation(),
4361 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004362 InitExprs.push_back(castExpr);
Steve Narofff4b992a2008-10-28 20:29:00 +00004363 }
4364 // Add initializers for any closure decl refs.
4365 if (BlockDeclRefs.size()) {
Steve Naroffe2514232008-10-29 21:23:59 +00004366 Expr *Exp;
Steve Narofff4b992a2008-10-28 20:29:00 +00004367 // Output all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004368 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004369 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004370 if (isObjCType((*I)->getType())) {
Steve Naroffe2514232008-10-29 21:23:59 +00004371 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner86d7d912008-11-24 03:54:41 +00004372 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004373 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroffa5c0db82008-12-11 21:05:33 +00004374 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004375 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004376 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004377 Exp = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4378 CastExpr::CK_Unknown, Arg,
4379 Context->VoidPtrTy,
Anders Carlssona2615922009-07-31 00:48:10 +00004380 SourceLocation(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004381 SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004382 } else {
Chris Lattner86d7d912008-11-24 03:54:41 +00004383 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004384 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004385 }
Mike Stump11289f42009-09-09 15:08:12 +00004386 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004387 }
4388 // Output all "by ref" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004389 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004390 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004391 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004392 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4393 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004394 Context->getPointerType(Exp->getType()),
Steve Naroffe2514232008-10-29 21:23:59 +00004395 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004396 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004397 }
4398 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004399 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4400 FType, SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00004401 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004402 Context->getPointerType(NewRep->getType()),
Steve Narofff4b992a2008-10-28 20:29:00 +00004403 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004404 NewRep = new (Context) CStyleCastExpr(FType, CastExpr::CK_Unknown, NewRep,
Anders Carlssona2615922009-07-31 00:48:10 +00004405 FType, SourceLocation(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004406 SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004407 BlockDeclRefs.clear();
4408 BlockByRefDecls.clear();
4409 BlockByCopyDecls.clear();
4410 ImportedBlockDecls.clear();
4411 return NewRep;
4412}
4413
4414//===----------------------------------------------------------------------===//
4415// Function Body / Expression rewriting
4416//===----------------------------------------------------------------------===//
4417
Steve Naroff4588d0f2008-12-04 16:24:46 +00004418// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4419// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4420// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4421// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4422// Since the rewriter isn't capable of rewriting rewritten code, it's important
4423// we get this right.
4424void RewriteObjC::CollectPropertySetters(Stmt *S) {
4425 // Perform a bottom up traversal of all children.
4426 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4427 CI != E; ++CI)
4428 if (*CI)
4429 CollectPropertySetters(*CI);
4430
4431 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4432 if (BinOp->isAssignmentOp()) {
4433 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4434 PropSetters[PRE] = BinOp;
4435 }
4436 }
4437}
4438
Steve Narofff4b992a2008-10-28 20:29:00 +00004439Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump11289f42009-09-09 15:08:12 +00004440 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004441 isa<DoStmt>(S) || isa<ForStmt>(S))
4442 Stmts.push_back(S);
4443 else if (isa<ObjCForCollectionStmt>(S)) {
4444 Stmts.push_back(S);
4445 ObjCBcLabelNo.push_back(++BcLabelCount);
4446 }
Mike Stump11289f42009-09-09 15:08:12 +00004447
Steve Narofff4b992a2008-10-28 20:29:00 +00004448 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004449
Steve Narofff4b992a2008-10-28 20:29:00 +00004450 // Perform a bottom up rewrite of all children.
4451 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4452 CI != E; ++CI)
4453 if (*CI) {
4454 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Mike Stump11289f42009-09-09 15:08:12 +00004455 if (newStmt)
Steve Narofff4b992a2008-10-28 20:29:00 +00004456 *CI = newStmt;
4457 }
Mike Stump11289f42009-09-09 15:08:12 +00004458
Steve Narofff4b992a2008-10-28 20:29:00 +00004459 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4460 // Rewrite the block body in place.
4461 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Mike Stump11289f42009-09-09 15:08:12 +00004462
Steve Narofff4b992a2008-10-28 20:29:00 +00004463 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroffd8907b72008-10-29 18:15:37 +00004464 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
4465 RewrittenBlockExprs[BE] = Str;
Mike Stump11289f42009-09-09 15:08:12 +00004466
Steve Narofff4b992a2008-10-28 20:29:00 +00004467 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4468 //blockTranscribed->dump();
Steve Naroffd8907b72008-10-29 18:15:37 +00004469 ReplaceStmt(S, blockTranscribed);
Steve Narofff4b992a2008-10-28 20:29:00 +00004470 return blockTranscribed;
4471 }
4472 // Handle specific things.
4473 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4474 return RewriteAtEncode(AtEncode);
Mike Stump11289f42009-09-09 15:08:12 +00004475
Steve Narofff4b992a2008-10-28 20:29:00 +00004476 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4477 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4478
Steve Naroff4588d0f2008-12-04 16:24:46 +00004479 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4480 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4481 if (BinOp) {
4482 // Because the rewriter doesn't allow us to rewrite rewritten code,
4483 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroff08628db2008-12-09 12:56:34 +00004484 DisableReplaceStmt = true;
4485 // Save the source range. Even if we disable the replacement, the
4486 // rewritten node will have been inserted into the tree. If the synthesized
4487 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump11289f42009-09-09 15:08:12 +00004488 // self.errorHandler = handler ? handler :
Steve Naroff08628db2008-12-09 12:56:34 +00004489 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4490 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroff4588d0f2008-12-04 16:24:46 +00004491 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroff08628db2008-12-09 12:56:34 +00004492 DisableReplaceStmt = false;
Steve Naroff22216db2008-12-04 23:50:32 +00004493 //
4494 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4495 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4496 // to see the original expression). Consider this example:
4497 //
4498 // Foo *obj1, *obj2;
4499 //
4500 // obj1.i = [obj2 rrrr];
4501 //
4502 // 'BinOp' for the previous expression looks like:
4503 //
4504 // (BinaryOperator 0x231ccf0 'int' '='
4505 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4506 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4507 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4508 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4509 //
4510 // 'newStmt' represents the rewritten message expression. For example:
4511 //
4512 // (CallExpr 0x231d300 'id':'struct objc_object *'
4513 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4514 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4515 // (CStyleCastExpr 0x231d220 'void *'
4516 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4517 //
4518 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4519 // can be used as the setter argument. ReplaceStmt() will still 'see'
4520 // the original RHS (since we haven't altered BinOp).
4521 //
Mike Stump11289f42009-09-09 15:08:12 +00004522 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff22216db2008-12-04 23:50:32 +00004523 // node. As a result, we now leak the original AST nodes.
4524 //
Steve Naroff08628db2008-12-09 12:56:34 +00004525 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroff4588d0f2008-12-04 16:24:46 +00004526 } else {
4527 return RewritePropertyGetter(PropRefExpr);
Steve Narofff326f402008-12-03 00:56:33 +00004528 }
4529 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004530 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4531 return RewriteAtSelector(AtSelector);
Mike Stump11289f42009-09-09 15:08:12 +00004532
Steve Narofff4b992a2008-10-28 20:29:00 +00004533 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4534 return RewriteObjCStringLiteral(AtString);
Mike Stump11289f42009-09-09 15:08:12 +00004535
Steve Narofff4b992a2008-10-28 20:29:00 +00004536 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00004537#if 0
Steve Narofff4b992a2008-10-28 20:29:00 +00004538 // Before we rewrite it, put the original message expression in a comment.
4539 SourceLocation startLoc = MessExpr->getLocStart();
4540 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00004541
Steve Narofff4b992a2008-10-28 20:29:00 +00004542 const char *startBuf = SM->getCharacterData(startLoc);
4543 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004544
Steve Narofff4b992a2008-10-28 20:29:00 +00004545 std::string messString;
4546 messString += "// ";
4547 messString.append(startBuf, endBuf-startBuf+1);
4548 messString += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00004549
4550 // FIXME: Missing definition of
Steve Narofff4b992a2008-10-28 20:29:00 +00004551 // InsertText(clang::SourceLocation, char const*, unsigned int).
4552 // InsertText(startLoc, messString.c_str(), messString.size());
4553 // Tried this, but it didn't work either...
4554 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff4588d0f2008-12-04 16:24:46 +00004555#endif
Steve Narofff4b992a2008-10-28 20:29:00 +00004556 return RewriteMessageExpr(MessExpr);
4557 }
Mike Stump11289f42009-09-09 15:08:12 +00004558
Steve Narofff4b992a2008-10-28 20:29:00 +00004559 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4560 return RewriteObjCTryStmt(StmtTry);
4561
4562 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4563 return RewriteObjCSynchronizedStmt(StmtTry);
4564
4565 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4566 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump11289f42009-09-09 15:08:12 +00004567
Steve Narofff4b992a2008-10-28 20:29:00 +00004568 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4569 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump11289f42009-09-09 15:08:12 +00004570
4571 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofff4b992a2008-10-28 20:29:00 +00004572 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump11289f42009-09-09 15:08:12 +00004573 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofff4b992a2008-10-28 20:29:00 +00004574 OrigStmtRange.getEnd());
4575 if (BreakStmt *StmtBreakStmt =
4576 dyn_cast<BreakStmt>(S))
4577 return RewriteBreakStmt(StmtBreakStmt);
4578 if (ContinueStmt *StmtContinueStmt =
4579 dyn_cast<ContinueStmt>(S))
4580 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump11289f42009-09-09 15:08:12 +00004581
4582 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofff4b992a2008-10-28 20:29:00 +00004583 // and cast exprs.
4584 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4585 // FIXME: What we're doing here is modifying the type-specifier that
4586 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump11289f42009-09-09 15:08:12 +00004587 // a separate type-specifier that we can rewrite.
Steve Naroffe70a52a2009-12-05 15:55:59 +00004588 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4589 // the context of an ObjCForCollectionStmt. For example:
4590 // NSArray *someArray;
4591 // for (id <FooProtocol> index in someArray) ;
4592 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4593 // and it depends on the original text locations/positions.
Benjamin Krameracc5fa12009-12-05 22:16:51 +00004594 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroffe70a52a2009-12-05 15:55:59 +00004595 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump11289f42009-09-09 15:08:12 +00004596
Steve Narofff4b992a2008-10-28 20:29:00 +00004597 // Blocks rewrite rules.
4598 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4599 DI != DE; ++DI) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004600 Decl *SD = *DI;
Steve Narofff4b992a2008-10-28 20:29:00 +00004601 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004602 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004603 RewriteBlockPointerDecl(ND);
Mike Stump11289f42009-09-09 15:08:12 +00004604 else if (ND->getType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004605 CheckFunctionPointerDecl(ND->getType(), ND);
4606 }
4607 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004608 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004609 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00004610 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004611 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4612 }
4613 }
4614 }
Mike Stump11289f42009-09-09 15:08:12 +00004615
Steve Narofff4b992a2008-10-28 20:29:00 +00004616 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4617 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump11289f42009-09-09 15:08:12 +00004618
4619 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004620 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4621 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump11289f42009-09-09 15:08:12 +00004622 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4623 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004624 && "Statement stack mismatch");
4625 Stmts.pop_back();
4626 }
4627 // Handle blocks rewriting.
4628 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4629 if (BDRE->isByRef())
Steve Naroffd9803712009-04-29 16:37:50 +00004630 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofff4b992a2008-10-28 20:29:00 +00004631 }
4632 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff350b6652008-10-30 10:07:53 +00004633 if (CE->getCallee()->getType()->isBlockPointerType()) {
4634 Stmt *BlockCall = SynthesizeBlockCall(CE);
4635 ReplaceStmt(S, BlockCall);
4636 return BlockCall;
4637 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004638 }
Steve Naroffc989a7b2008-11-03 23:29:32 +00004639 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004640 RewriteCastExpr(CE);
4641 }
4642#if 0
4643 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek5a201952009-02-07 01:47:29 +00004644 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004645 // Get the new text.
4646 std::string SStr;
4647 llvm::raw_string_ostream Buf(SStr);
Eli Friedman0905f142009-05-30 05:19:26 +00004648 Replacement->printPretty(Buf, *Context);
Steve Narofff4b992a2008-10-28 20:29:00 +00004649 const std::string &Str = Buf.str();
4650
4651 printf("CAST = %s\n", &Str[0]);
4652 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4653 delete S;
4654 return Replacement;
4655 }
4656#endif
4657 // Return this stmt unmodified.
4658 return S;
4659}
4660
Steve Naroffe70a52a2009-12-05 15:55:59 +00004661void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
4662 for (RecordDecl::field_iterator i = RD->field_begin(),
4663 e = RD->field_end(); i != e; ++i) {
4664 FieldDecl *FD = *i;
4665 if (isTopLevelBlockPointerType(FD->getType()))
4666 RewriteBlockPointerDecl(FD);
4667 if (FD->getType()->isObjCQualifiedIdType() ||
4668 FD->getType()->isObjCQualifiedInterfaceType())
4669 RewriteObjCQualifiedInterfaceTypes(FD);
4670 }
4671}
4672
Steve Narofff4b992a2008-10-28 20:29:00 +00004673/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4674/// main file of the input.
4675void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4676 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffb1368882008-12-17 00:20:22 +00004677 if (FD->isOverloadedOperator())
4678 return;
Mike Stump11289f42009-09-09 15:08:12 +00004679
Steve Narofff4b992a2008-10-28 20:29:00 +00004680 // Since function prototypes don't have ParmDecl's, we check the function
4681 // prototype. This enables us to rewrite function declarations and
4682 // definitions using the same code.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004683 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofff4b992a2008-10-28 20:29:00 +00004684
Sebastian Redla7b98a72009-04-26 20:35:05 +00004685 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00004686 if (CompoundStmt *Body = FD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004687 CurFunctionDef = FD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00004688 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00004689 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00004690 Body =
4691 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4692 FD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00004693 CurrentBody = 0;
4694 if (PropParentMap) {
4695 delete PropParentMap;
4696 PropParentMap = 0;
4697 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004698 // This synthesizes and inserts the block "impl" struct, invoke function,
4699 // and any copy/dispose helper functions.
4700 InsertBlockLiteralsWithinFunction(FD);
4701 CurFunctionDef = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004702 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004703 return;
4704 }
4705 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00004706 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004707 CurMethodDef = MD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00004708 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00004709 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00004710 Body =
4711 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4712 MD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00004713 CurrentBody = 0;
4714 if (PropParentMap) {
4715 delete PropParentMap;
4716 PropParentMap = 0;
4717 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004718 InsertBlockLiteralsWithinMethod(MD);
4719 CurMethodDef = 0;
4720 }
4721 }
4722 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
4723 ClassImplementation.push_back(CI);
4724 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4725 CategoryImplementation.push_back(CI);
4726 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4727 RewriteForwardClassDecl(CD);
4728 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4729 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroffa5c0db82008-12-11 21:05:33 +00004730 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004731 RewriteBlockPointerDecl(VD);
Steve Naroffd8907b72008-10-29 18:15:37 +00004732 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004733 CheckFunctionPointerDecl(VD->getType(), VD);
4734 if (VD->getInit()) {
Steve Naroffc989a7b2008-11-03 23:29:32 +00004735 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004736 RewriteCastExpr(CE);
4737 }
4738 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00004739 } else if (VD->getType()->isRecordType()) {
4740 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4741 if (RD->isDefinition())
4742 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00004743 }
Steve Naroffd8907b72008-10-29 18:15:37 +00004744 if (VD->getInit()) {
4745 GlobalVarDecl = VD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00004746 CollectPropertySetters(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00004747 CurrentBody = VD->getInit();
Steve Naroffd8907b72008-10-29 18:15:37 +00004748 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00004749 CurrentBody = 0;
4750 if (PropParentMap) {
4751 delete PropParentMap;
4752 PropParentMap = 0;
4753 }
Mike Stump11289f42009-09-09 15:08:12 +00004754 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner86d7d912008-11-24 03:54:41 +00004755 VD->getNameAsCString());
Steve Naroffd8907b72008-10-29 18:15:37 +00004756 GlobalVarDecl = 0;
4757
4758 // This is needed for blocks.
Steve Naroffc989a7b2008-11-03 23:29:32 +00004759 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroffd8907b72008-10-29 18:15:37 +00004760 RewriteCastExpr(CE);
4761 }
4762 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004763 return;
4764 }
4765 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004766 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004767 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00004768 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004769 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Steve Naroffe70a52a2009-12-05 15:55:59 +00004770 else if (TD->getUnderlyingType()->isRecordType()) {
4771 RecordDecl *RD = TD->getUnderlyingType()->getAs<RecordType>()->getDecl();
4772 if (RD->isDefinition())
4773 RewriteRecordBody(RD);
4774 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004775 return;
4776 }
4777 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroffe70a52a2009-12-05 15:55:59 +00004778 if (RD->isDefinition())
4779 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00004780 return;
4781 }
4782 // Nothing yet.
4783}
4784
Chris Lattnercf169832009-03-28 04:11:33 +00004785void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004786 // Get the top-level buffer that this corresponds to.
Mike Stump11289f42009-09-09 15:08:12 +00004787
Steve Narofff4b992a2008-10-28 20:29:00 +00004788 // Rewrite tabs if we care.
4789 //RewriteTabs();
Mike Stump11289f42009-09-09 15:08:12 +00004790
Steve Narofff4b992a2008-10-28 20:29:00 +00004791 if (Diags.hasErrorOccurred())
4792 return;
Mike Stump11289f42009-09-09 15:08:12 +00004793
Steve Narofff4b992a2008-10-28 20:29:00 +00004794 RewriteInclude();
Mike Stump11289f42009-09-09 15:08:12 +00004795
Steve Naroffd9803712009-04-29 16:37:50 +00004796 // Here's a great place to add any extra declarations that may be needed.
4797 // Write out meta data for each @protocol(<expr>).
Mike Stump11289f42009-09-09 15:08:12 +00004798 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00004799 E = ProtocolExprDecls.end(); I != E; ++I)
4800 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
4801
Mike Stump11289f42009-09-09 15:08:12 +00004802 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Narofff4b992a2008-10-28 20:29:00 +00004803 Preamble.c_str(), Preamble.size(), false);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00004804 if (ClassImplementation.size() || CategoryImplementation.size())
4805 RewriteImplementations();
Steve Naroffd9803712009-04-29 16:37:50 +00004806
Steve Narofff4b992a2008-10-28 20:29:00 +00004807 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4808 // we are done.
Mike Stump11289f42009-09-09 15:08:12 +00004809 if (const RewriteBuffer *RewriteBuf =
Steve Narofff4b992a2008-10-28 20:29:00 +00004810 Rewrite.getRewriteBufferFor(MainFileID)) {
4811 //printf("Changed:\n");
4812 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4813 } else {
4814 fprintf(stderr, "No changes\n");
4815 }
Steve Narofff8cfd162008-11-13 20:07:04 +00004816
Steve Naroffd9803712009-04-29 16:37:50 +00004817 if (ClassImplementation.size() || CategoryImplementation.size() ||
4818 ProtocolExprDecls.size()) {
Steve Naroff2a2a41f2008-11-14 14:10:01 +00004819 // Rewrite Objective-c meta data*
4820 std::string ResultStr;
4821 SynthesizeMetaDataIntoBuffer(ResultStr);
4822 // Emit metadata.
4823 *OutFile << ResultStr;
4824 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004825 OutFile->flush();
4826}
4827