blob: 2f2f005db9b37a5133479f7af4742b20b4e0beb9 [file] [log] [blame]
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Ted Kremenek305c6132012-09-01 05:09:24 +000014#include "clang/Rewrite/Frontend/ASTConsumers.h"
15#include "clang/Rewrite/Core/Rewriter.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ParentMap.h"
19#include "clang/Basic/SourceManager.h"
20#include "clang/Basic/IdentifierTable.h"
21#include "clang/Basic/Diagnostic.h"
22#include "clang/Lex/Lexer.h"
23#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
25#include "llvm/ADT/StringExtras.h"
26#include "llvm/ADT/SmallPtrSet.h"
27#include "llvm/ADT/OwningPtr.h"
28#include "llvm/ADT/DenseSet.h"
29
30using namespace clang;
31using llvm::utostr;
32
33namespace {
34 class RewriteModernObjC : public ASTConsumer {
35 protected:
36
37 enum {
38 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
39 block, ... */
40 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
41 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
42 __block variable */
43 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
44 helpers */
45 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
46 support routines */
47 BLOCK_BYREF_CURRENT_MAX = 256
48 };
49
50 enum {
51 BLOCK_NEEDS_FREE = (1 << 24),
52 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
53 BLOCK_HAS_CXX_OBJ = (1 << 26),
54 BLOCK_IS_GC = (1 << 27),
55 BLOCK_IS_GLOBAL = (1 << 28),
56 BLOCK_HAS_DESCRIPTOR = (1 << 29)
57 };
58 static const int OBJC_ABI_VERSION = 7;
59
60 Rewriter Rewrite;
61 DiagnosticsEngine &Diags;
62 const LangOptions &LangOpts;
63 ASTContext *Context;
64 SourceManager *SM;
65 TranslationUnitDecl *TUDecl;
66 FileID MainFileID;
67 const char *MainFileStart, *MainFileEnd;
68 Stmt *CurrentBody;
69 ParentMap *PropParentMap; // created lazily.
70 std::string InFileName;
71 raw_ostream* OutFile;
72 std::string Preamble;
73
74 TypeDecl *ProtocolTypeDecl;
75 VarDecl *GlobalVarDecl;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +000076 Expr *GlobalConstructionExp;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000077 unsigned RewriteFailedDiag;
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +000078 unsigned GlobalBlockRewriteFailedDiag;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000079 // ObjC string constant support.
80 unsigned NumObjCStringLiterals;
81 VarDecl *ConstantStringClassReference;
82 RecordDecl *NSStringRecord;
83
84 // ObjC foreach break/continue generation support.
85 int BcLabelCount;
86
87 unsigned TryFinallyContainsReturnDiag;
88 // Needed for super.
89 ObjCMethodDecl *CurMethodDef;
90 RecordDecl *SuperStructDecl;
91 RecordDecl *ConstantStringDecl;
92
93 FunctionDecl *MsgSendFunctionDecl;
94 FunctionDecl *MsgSendSuperFunctionDecl;
95 FunctionDecl *MsgSendStretFunctionDecl;
96 FunctionDecl *MsgSendSuperStretFunctionDecl;
97 FunctionDecl *MsgSendFpretFunctionDecl;
98 FunctionDecl *GetClassFunctionDecl;
99 FunctionDecl *GetMetaClassFunctionDecl;
100 FunctionDecl *GetSuperClassFunctionDecl;
101 FunctionDecl *SelGetUidFunctionDecl;
102 FunctionDecl *CFStringFunctionDecl;
103 FunctionDecl *SuperContructorFunctionDecl;
104 FunctionDecl *CurFunctionDef;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000105
106 /* Misc. containers needed for meta-data rewrite. */
107 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
108 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
109 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
110 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000111 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +0000112 llvm::SmallPtrSet<TagDecl*, 32> GlobalDefinedTags;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000113 SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000114 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
115 SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
116
117 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
118 llvm::SmallVector<ObjCCategoryDecl*, 8> DefinedNonLazyCategories;
119
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000120 SmallVector<Stmt *, 32> Stmts;
121 SmallVector<int, 8> ObjCBcLabelNo;
122 // Remember all the @protocol(<expr>) expressions.
123 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
124
125 llvm::DenseSet<uint64_t> CopyDestroyCache;
126
127 // Block expressions.
128 SmallVector<BlockExpr *, 32> Blocks;
129 SmallVector<int, 32> InnerDeclRefsCount;
John McCallf4b88a42012-03-10 09:33:50 +0000130 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000131
John McCallf4b88a42012-03-10 09:33:50 +0000132 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000133
134 // Block related declarations.
135 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
136 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
137 SmallVector<ValueDecl *, 8> BlockByRefDecls;
138 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
139 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
140 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
141 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
142
143 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000144 llvm::DenseMap<ObjCInterfaceDecl *,
145 llvm::SmallPtrSet<ObjCIvarDecl *, 8> > ReferencedIvars;
146
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000147 // This maps an original source AST to it's rewritten form. This allows
148 // us to avoid rewriting the same node twice (which is very uncommon).
149 // This is needed to support some of the exotic property rewriting.
150 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
151
152 // Needed for header files being rewritten
153 bool IsHeader;
154 bool SilenceRewriteMacroWarning;
155 bool objc_impl_method;
156
157 bool DisableReplaceStmt;
158 class DisableReplaceStmtScope {
159 RewriteModernObjC &R;
160 bool SavedValue;
161
162 public:
163 DisableReplaceStmtScope(RewriteModernObjC &R)
164 : R(R), SavedValue(R.DisableReplaceStmt) {
165 R.DisableReplaceStmt = true;
166 }
167 ~DisableReplaceStmtScope() {
168 R.DisableReplaceStmt = SavedValue;
169 }
170 };
171 void InitializeCommon(ASTContext &context);
172
173 public:
Fariborz Jahanian90af4e22012-02-14 17:19:02 +0000174 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000175 // Top Level Driver code.
176 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
177 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
178 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
179 if (!Class->isThisDeclarationADefinition()) {
180 RewriteForwardClassDecl(D);
181 break;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000182 } else {
183 // Keep track of all interface declarations seen.
Fariborz Jahanianf3295272012-02-24 21:42:38 +0000184 ObjCInterfacesSeen.push_back(Class);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000185 break;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000186 }
187 }
188
189 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
190 if (!Proto->isThisDeclarationADefinition()) {
191 RewriteForwardProtocolDecl(D);
192 break;
193 }
194 }
195
196 HandleTopLevelSingleDecl(*I);
197 }
198 return true;
199 }
200 void HandleTopLevelSingleDecl(Decl *D);
201 void HandleDeclInMainFile(Decl *D);
202 RewriteModernObjC(std::string inFile, raw_ostream *OS,
203 DiagnosticsEngine &D, const LangOptions &LOpts,
204 bool silenceMacroWarn);
205
206 ~RewriteModernObjC() {}
207
208 virtual void HandleTranslationUnit(ASTContext &C);
209
210 void ReplaceStmt(Stmt *Old, Stmt *New) {
211 Stmt *ReplacingStmt = ReplacedNodes[Old];
212
213 if (ReplacingStmt)
214 return; // We can't rewrite the same node twice.
215
216 if (DisableReplaceStmt)
217 return;
218
219 // If replacement succeeded or warning disabled return with no warning.
220 if (!Rewrite.ReplaceStmt(Old, New)) {
221 ReplacedNodes[Old] = New;
222 return;
223 }
224 if (SilenceRewriteMacroWarning)
225 return;
226 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
227 << Old->getSourceRange();
228 }
229
230 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
231 if (DisableReplaceStmt)
232 return;
233
234 // Measure the old text.
235 int Size = Rewrite.getRangeSize(SrcRange);
236 if (Size == -1) {
237 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
238 << Old->getSourceRange();
239 return;
240 }
241 // Get the new text.
242 std::string SStr;
243 llvm::raw_string_ostream S(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +0000244 New->printPretty(S, 0, PrintingPolicy(LangOpts));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000245 const std::string &Str = S.str();
246
247 // If replacement succeeded or warning disabled return with no warning.
248 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
249 ReplacedNodes[Old] = New;
250 return;
251 }
252 if (SilenceRewriteMacroWarning)
253 return;
254 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
255 << Old->getSourceRange();
256 }
257
258 void InsertText(SourceLocation Loc, StringRef Str,
259 bool InsertAfter = true) {
260 // If insertion succeeded or warning disabled return with no warning.
261 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
262 SilenceRewriteMacroWarning)
263 return;
264
265 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
266 }
267
268 void ReplaceText(SourceLocation Start, unsigned OrigLength,
269 StringRef Str) {
270 // If removal succeeded or warning disabled return with no warning.
271 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
272 SilenceRewriteMacroWarning)
273 return;
274
275 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
276 }
277
278 // Syntactic Rewriting.
279 void RewriteRecordBody(RecordDecl *RD);
280 void RewriteInclude();
Fariborz Jahanian96205962012-11-06 17:30:23 +0000281 void RewriteLineDirective(const Decl *D);
Fariborz Jahanianf616ae22012-11-06 23:25:49 +0000282 void ConvertSourceLocationToLineDirective(SourceLocation Loc,
283 std::string &LineString);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000284 void RewriteForwardClassDecl(DeclGroupRef D);
285 void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG);
286 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
287 const std::string &typedefString);
288 void RewriteImplementations();
289 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
290 ObjCImplementationDecl *IMD,
291 ObjCCategoryImplDecl *CID);
292 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
293 void RewriteImplementationDecl(Decl *Dcl);
294 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
295 ObjCMethodDecl *MDecl, std::string &ResultStr);
296 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
297 const FunctionType *&FPRetType);
298 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
299 ValueDecl *VD, bool def=false);
300 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
301 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
302 void RewriteForwardProtocolDecl(DeclGroupRef D);
303 void RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG);
304 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
305 void RewriteProperty(ObjCPropertyDecl *prop);
306 void RewriteFunctionDecl(FunctionDecl *FD);
307 void RewriteBlockPointerType(std::string& Str, QualType Type);
308 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +0000309 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000310 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
311 void RewriteTypeOfDecl(VarDecl *VD);
312 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000313
314 std::string getIvarAccessString(ObjCIvarDecl *D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000315
316 // Expression Rewriting.
317 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
318 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
319 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
320 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
321 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
322 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
323 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian55947042012-03-27 20:17:30 +0000324 Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
Patrick Beardeb382ec2012-04-19 00:25:12 +0000325 Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
Fariborz Jahanian86cff602012-03-30 23:35:47 +0000326 Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000327 Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000328 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000329 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian042b91d2012-05-23 23:47:20 +0000330 Stmt *RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000331 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
332 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
333 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
334 SourceLocation OrigEnd);
335 Stmt *RewriteBreakStmt(BreakStmt *S);
336 Stmt *RewriteContinueStmt(ContinueStmt *S);
337 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +0000338 void RewriteImplicitCastObjCExpr(CastExpr *IE);
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000339 void RewriteLinkageSpec(LinkageSpecDecl *LSD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000340
341 // Block rewriting.
342 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
343
344 // Block specific rewrite rules.
345 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +0000346 void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
John McCallf4b88a42012-03-10 09:33:50 +0000347 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000348 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
349 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
350
351 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
352 std::string &Result);
353
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000354 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
Fariborz Jahanianb68258f2012-05-01 17:46:45 +0000355 bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
Fariborz Jahanian8fba8942012-04-30 23:20:30 +0000356 bool &IsNamedDefinition);
357 void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
358 std::string &Result);
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000359
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +0000360 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
361
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000362 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
363 std::string &Result);
364
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000365 virtual void Initialize(ASTContext &context);
366
Benjamin Kramer48d798c2012-06-02 10:20:41 +0000367 // Misc. AST transformation routines. Sometimes they end up calling
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000368 // rewriting routines on the new ASTs.
369 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
370 Expr **args, unsigned nargs,
371 SourceLocation StartLoc=SourceLocation(),
372 SourceLocation EndLoc=SourceLocation());
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +0000373
374 Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
375 QualType msgSendType,
376 QualType returnType,
377 SmallVectorImpl<QualType> &ArgTypes,
378 SmallVectorImpl<Expr*> &MsgExprs,
379 ObjCMethodDecl *Method);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000380
381 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
382 SourceLocation StartLoc=SourceLocation(),
383 SourceLocation EndLoc=SourceLocation());
384
385 void SynthCountByEnumWithState(std::string &buf);
386 void SynthMsgSendFunctionDecl();
387 void SynthMsgSendSuperFunctionDecl();
388 void SynthMsgSendStretFunctionDecl();
389 void SynthMsgSendFpretFunctionDecl();
390 void SynthMsgSendSuperStretFunctionDecl();
391 void SynthGetClassFunctionDecl();
392 void SynthGetMetaClassFunctionDecl();
393 void SynthGetSuperClassFunctionDecl();
394 void SynthSelGetUidFunctionDecl();
395 void SynthSuperContructorFunctionDecl();
396
397 // Rewriting metadata
398 template<typename MethodIterator>
399 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
400 MethodIterator MethodEnd,
401 bool IsInstanceMethod,
402 StringRef prefix,
403 StringRef ClassName,
404 std::string &Result);
Fariborz Jahanianda9624a2012-02-08 19:53:58 +0000405 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
406 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000407 void RewriteObjCProtocolListMetaData(
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000408 const ObjCList<ObjCProtocolDecl> &Prots,
409 StringRef prefix, StringRef ClassName, std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000410 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000411 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000412 void RewriteClassSetupInitHook(std::string &Result);
Fariborz Jahaniane0335782012-03-27 18:41:05 +0000413
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000414 void RewriteMetaDataIntoBuffer(std::string &Result);
415 void WriteImageInfo(std::string &Result);
416 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000417 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000418 void RewriteCategorySetupInitHook(std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000419
420 // Rewriting ivar
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000421 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000422 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000423 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000424
425
426 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
427 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
428 StringRef funcName, std::string Tag);
429 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
430 StringRef funcName, std::string Tag);
431 std::string SynthesizeBlockImpl(BlockExpr *CE,
432 std::string Tag, std::string Desc);
433 std::string SynthesizeBlockDescriptor(std::string DescTag,
434 std::string ImplTag,
435 int i, StringRef funcName,
436 unsigned hasCopy);
437 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
438 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
439 StringRef FunName);
440 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
441 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +0000442 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000443
444 // Misc. helper routines.
445 QualType getProtocolType();
446 void WarnAboutReturnGotoStmts(Stmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000447 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
448 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
449 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
450
451 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
452 void CollectBlockDeclRefInfo(BlockExpr *Exp);
453 void GetBlockDeclRefExprs(Stmt *S);
454 void GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +0000455 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000456 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
457
458 // We avoid calling Type::isBlockPointerType(), since it operates on the
459 // canonical type. We only care if the top-level type is a closure pointer.
460 bool isTopLevelBlockPointerType(QualType T) {
461 return isa<BlockPointerType>(T);
462 }
463
464 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
465 /// to a function pointer type and upon success, returns true; false
466 /// otherwise.
467 bool convertBlockPointerToFunctionPointer(QualType &T) {
468 if (isTopLevelBlockPointerType(T)) {
469 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
470 T = Context->getPointerType(BPT->getPointeeType());
471 return true;
472 }
473 return false;
474 }
475
Fariborz Jahanian164d6f82012-02-13 18:57:49 +0000476 bool convertObjCTypeToCStyleType(QualType &T);
477
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000478 bool needToScanForQualifiers(QualType T);
479 QualType getSuperStructType();
480 QualType getConstantStringStructType();
481 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
482 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
483
484 void convertToUnqualifiedObjCType(QualType &T) {
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000485 if (T->isObjCQualifiedIdType()) {
486 bool isConst = T.isConstQualified();
487 T = isConst ? Context->getObjCIdType().withConst()
488 : Context->getObjCIdType();
489 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000490 else if (T->isObjCQualifiedClassType())
491 T = Context->getObjCClassType();
492 else if (T->isObjCObjectPointerType() &&
493 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
494 if (const ObjCObjectPointerType * OBJPT =
495 T->getAsObjCInterfacePointerType()) {
496 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
497 T = QualType(IFaceT, 0);
498 T = Context->getPointerType(T);
499 }
500 }
501 }
502
503 // FIXME: This predicate seems like it would be useful to add to ASTContext.
504 bool isObjCType(QualType T) {
505 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
506 return false;
507
508 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
509
510 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
511 OCT == Context->getCanonicalType(Context->getObjCClassType()))
512 return true;
513
514 if (const PointerType *PT = OCT->getAs<PointerType>()) {
515 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
516 PT->getPointeeType()->isObjCQualifiedIdType())
517 return true;
518 }
519 return false;
520 }
521 bool PointerTypeTakesAnyBlockArguments(QualType QT);
522 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
523 void GetExtentOfArgList(const char *Name, const char *&LParen,
524 const char *&RParen);
525
526 void QuoteDoublequotes(std::string &From, std::string &To) {
527 for (unsigned i = 0; i < From.length(); i++) {
528 if (From[i] == '"')
529 To += "\\\"";
530 else
531 To += From[i];
532 }
533 }
534
535 QualType getSimpleFunctionType(QualType result,
536 const QualType *args,
537 unsigned numArgs,
538 bool variadic = false) {
539 if (result == Context->getObjCInstanceType())
540 result = Context->getObjCIdType();
541 FunctionProtoType::ExtProtoInfo fpi;
542 fpi.Variadic = variadic;
543 return Context->getFunctionType(result, args, numArgs, fpi);
544 }
545
546 // Helper function: create a CStyleCastExpr with trivial type source info.
547 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
548 CastKind Kind, Expr *E) {
549 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
550 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
551 SourceLocation(), SourceLocation());
552 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000553
554 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
555 IdentifierInfo* II = &Context->Idents.get("load");
556 Selector LoadSel = Context->Selectors.getSelector(0, &II);
557 return OD->getClassMethod(LoadSel) != 0;
558 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000559 };
560
561}
562
563void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
564 NamedDecl *D) {
565 if (const FunctionProtoType *fproto
566 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
567 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
568 E = fproto->arg_type_end(); I && (I != E); ++I)
569 if (isTopLevelBlockPointerType(*I)) {
570 // All the args are checked/rewritten. Don't call twice!
571 RewriteBlockPointerDecl(D);
572 break;
573 }
574 }
575}
576
577void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
578 const PointerType *PT = funcType->getAs<PointerType>();
579 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
580 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
581}
582
583static bool IsHeaderFile(const std::string &Filename) {
584 std::string::size_type DotPos = Filename.rfind('.');
585
586 if (DotPos == std::string::npos) {
587 // no file extension
588 return false;
589 }
590
591 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
592 // C header: .h
593 // C++ header: .hh or .H;
594 return Ext == "h" || Ext == "hh" || Ext == "H";
595}
596
597RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
598 DiagnosticsEngine &D, const LangOptions &LOpts,
599 bool silenceMacroWarn)
600 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
601 SilenceRewriteMacroWarning(silenceMacroWarn) {
602 IsHeader = IsHeaderFile(inFile);
603 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
604 "rewriting sub-expression within a macro (may not be correct)");
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +0000605 // FIXME. This should be an error. But if block is not called, it is OK. And it
606 // may break including some headers.
607 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
608 "rewriting block literal declared in global scope is not implemented");
609
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000610 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
611 DiagnosticsEngine::Warning,
612 "rewriter doesn't support user-specified control flow semantics "
613 "for @try/@finally (code may not execute properly)");
614}
615
616ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
617 raw_ostream* OS,
618 DiagnosticsEngine &Diags,
619 const LangOptions &LOpts,
620 bool SilenceRewriteMacroWarning) {
621 return new RewriteModernObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
622}
623
624void RewriteModernObjC::InitializeCommon(ASTContext &context) {
625 Context = &context;
626 SM = &Context->getSourceManager();
627 TUDecl = Context->getTranslationUnitDecl();
628 MsgSendFunctionDecl = 0;
629 MsgSendSuperFunctionDecl = 0;
630 MsgSendStretFunctionDecl = 0;
631 MsgSendSuperStretFunctionDecl = 0;
632 MsgSendFpretFunctionDecl = 0;
633 GetClassFunctionDecl = 0;
634 GetMetaClassFunctionDecl = 0;
635 GetSuperClassFunctionDecl = 0;
636 SelGetUidFunctionDecl = 0;
637 CFStringFunctionDecl = 0;
638 ConstantStringClassReference = 0;
639 NSStringRecord = 0;
640 CurMethodDef = 0;
641 CurFunctionDef = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000642 GlobalVarDecl = 0;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +0000643 GlobalConstructionExp = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000644 SuperStructDecl = 0;
645 ProtocolTypeDecl = 0;
646 ConstantStringDecl = 0;
647 BcLabelCount = 0;
648 SuperContructorFunctionDecl = 0;
649 NumObjCStringLiterals = 0;
650 PropParentMap = 0;
651 CurrentBody = 0;
652 DisableReplaceStmt = false;
653 objc_impl_method = false;
654
655 // Get the ID and start/end of the main file.
656 MainFileID = SM->getMainFileID();
657 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
658 MainFileStart = MainBuf->getBufferStart();
659 MainFileEnd = MainBuf->getBufferEnd();
660
David Blaikie4e4d0842012-03-11 07:00:24 +0000661 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000662}
663
664//===----------------------------------------------------------------------===//
665// Top Level Driver Code
666//===----------------------------------------------------------------------===//
667
668void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
669 if (Diags.hasErrorOccurred())
670 return;
671
672 // Two cases: either the decl could be in the main file, or it could be in a
673 // #included file. If the former, rewrite it now. If the later, check to see
674 // if we rewrote the #include/#import.
675 SourceLocation Loc = D->getLocation();
676 Loc = SM->getExpansionLoc(Loc);
677
678 // If this is for a builtin, ignore it.
679 if (Loc.isInvalid()) return;
680
681 // Look for built-in declarations that we need to refer during the rewrite.
682 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
683 RewriteFunctionDecl(FD);
684 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
685 // declared in <Foundation/NSString.h>
686 if (FVD->getName() == "_NSConstantStringClassReference") {
687 ConstantStringClassReference = FVD;
688 return;
689 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000690 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
691 RewriteCategoryDecl(CD);
692 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
693 if (PD->isThisDeclarationADefinition())
694 RewriteProtocolDecl(PD);
695 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
Fariborz Jahanian8e86b2d2012-04-04 17:16:15 +0000696 // FIXME. This will not work in all situations and leaving it out
697 // is harmless.
698 // RewriteLinkageSpec(LSD);
699
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000700 // Recurse into linkage specifications
701 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
702 DIEnd = LSD->decls_end();
703 DI != DIEnd; ) {
704 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
705 if (!IFace->isThisDeclarationADefinition()) {
706 SmallVector<Decl *, 8> DG;
707 SourceLocation StartLoc = IFace->getLocStart();
708 do {
709 if (isa<ObjCInterfaceDecl>(*DI) &&
710 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
711 StartLoc == (*DI)->getLocStart())
712 DG.push_back(*DI);
713 else
714 break;
715
716 ++DI;
717 } while (DI != DIEnd);
718 RewriteForwardClassDecl(DG);
719 continue;
720 }
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000721 else {
722 // Keep track of all interface declarations seen.
723 ObjCInterfacesSeen.push_back(IFace);
724 ++DI;
725 continue;
726 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000727 }
728
729 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
730 if (!Proto->isThisDeclarationADefinition()) {
731 SmallVector<Decl *, 8> DG;
732 SourceLocation StartLoc = Proto->getLocStart();
733 do {
734 if (isa<ObjCProtocolDecl>(*DI) &&
735 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
736 StartLoc == (*DI)->getLocStart())
737 DG.push_back(*DI);
738 else
739 break;
740
741 ++DI;
742 } while (DI != DIEnd);
743 RewriteForwardProtocolDecl(DG);
744 continue;
745 }
746 }
747
748 HandleTopLevelSingleDecl(*DI);
749 ++DI;
750 }
751 }
752 // If we have a decl in the main file, see if we should rewrite it.
753 if (SM->isFromMainFile(Loc))
754 return HandleDeclInMainFile(D);
755}
756
757//===----------------------------------------------------------------------===//
758// Syntactic (non-AST) Rewriting Code
759//===----------------------------------------------------------------------===//
760
761void RewriteModernObjC::RewriteInclude() {
762 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
763 StringRef MainBuf = SM->getBufferData(MainFileID);
764 const char *MainBufStart = MainBuf.begin();
765 const char *MainBufEnd = MainBuf.end();
766 size_t ImportLen = strlen("import");
767
768 // Loop over the whole file, looking for includes.
769 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
770 if (*BufPtr == '#') {
771 if (++BufPtr == MainBufEnd)
772 return;
773 while (*BufPtr == ' ' || *BufPtr == '\t')
774 if (++BufPtr == MainBufEnd)
775 return;
776 if (!strncmp(BufPtr, "import", ImportLen)) {
777 // replace import with include
778 SourceLocation ImportLoc =
779 LocStart.getLocWithOffset(BufPtr-MainBufStart);
780 ReplaceText(ImportLoc, ImportLen, "include");
781 BufPtr += ImportLen;
782 }
783 }
784 }
785}
786
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000787static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
788 ObjCIvarDecl *IvarDecl, std::string &Result) {
789 Result += "OBJC_IVAR_$_";
790 Result += IDecl->getName();
791 Result += "$";
792 Result += IvarDecl->getName();
793}
794
795std::string
796RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
797 const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
798
799 // Build name of symbol holding ivar offset.
800 std::string IvarOffsetName;
801 WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
802
803
804 std::string S = "(*(";
805 QualType IvarT = D->getType();
806
807 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
808 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
809 RD = RD->getDefinition();
810 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
811 // decltype(((Foo_IMPL*)0)->bar) *
812 ObjCContainerDecl *CDecl =
813 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
814 // ivar in class extensions requires special treatment.
815 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
816 CDecl = CatDecl->getClassInterface();
817 std::string RecName = CDecl->getName();
818 RecName += "_IMPL";
819 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
820 SourceLocation(), SourceLocation(),
821 &Context->Idents.get(RecName.c_str()));
822 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
823 unsigned UnsignedIntSize =
824 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
825 Expr *Zero = IntegerLiteral::Create(*Context,
826 llvm::APInt(UnsignedIntSize, 0),
827 Context->UnsignedIntTy, SourceLocation());
828 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
829 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
830 Zero);
831 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
832 SourceLocation(),
833 &Context->Idents.get(D->getNameAsString()),
834 IvarT, 0,
835 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +0000836 ICIS_NoInit);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000837 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
838 FD->getType(), VK_LValue,
839 OK_Ordinary);
840 IvarT = Context->getDecltypeType(ME, ME->getType());
841 }
842 }
843 convertObjCTypeToCStyleType(IvarT);
844 QualType castT = Context->getPointerType(IvarT);
845 std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
846 S += TypeString;
847 S += ")";
848
849 // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
850 S += "((char *)self + ";
851 S += IvarOffsetName;
852 S += "))";
853 ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000854 return S;
855}
856
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000857/// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
858/// been found in the class implementation. In this case, it must be synthesized.
859static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
860 ObjCPropertyDecl *PD,
861 bool getter) {
862 return getter ? !IMP->getInstanceMethod(PD->getGetterName())
863 : !IMP->getInstanceMethod(PD->getSetterName());
864
865}
866
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000867void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
868 ObjCImplementationDecl *IMD,
869 ObjCCategoryImplDecl *CID) {
870 static bool objcGetPropertyDefined = false;
871 static bool objcSetPropertyDefined = false;
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000872 SourceLocation startGetterSetterLoc;
873
874 if (PID->getLocStart().isValid()) {
875 SourceLocation startLoc = PID->getLocStart();
876 InsertText(startLoc, "// ");
877 const char *startBuf = SM->getCharacterData(startLoc);
878 assert((*startBuf == '@') && "bogus @synthesize location");
879 const char *semiBuf = strchr(startBuf, ';');
880 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
881 startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
882 }
883 else
884 startGetterSetterLoc = IMD ? IMD->getLocEnd() : CID->getLocEnd();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000885
886 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
887 return; // FIXME: is this correct?
888
889 // Generate the 'getter' function.
890 ObjCPropertyDecl *PD = PID->getPropertyDecl();
891 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
892
893 if (!OID)
894 return;
895 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000896 if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000897 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
898 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
899 ObjCPropertyDecl::OBJC_PR_copy));
900 std::string Getr;
901 if (GenGetProperty && !objcGetPropertyDefined) {
902 objcGetPropertyDefined = true;
903 // FIXME. Is this attribute correct in all cases?
904 Getr = "\nextern \"C\" __declspec(dllimport) "
905 "id objc_getProperty(id, SEL, long, bool);\n";
906 }
907 RewriteObjCMethodDecl(OID->getContainingInterface(),
908 PD->getGetterMethodDecl(), Getr);
909 Getr += "{ ";
910 // Synthesize an explicit cast to gain access to the ivar.
911 // See objc-act.c:objc_synthesize_new_getter() for details.
912 if (GenGetProperty) {
913 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
914 Getr += "typedef ";
915 const FunctionType *FPRetType = 0;
916 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
917 FPRetType);
918 Getr += " _TYPE";
919 if (FPRetType) {
920 Getr += ")"; // close the precedence "scope" for "*".
921
922 // Now, emit the argument types (if any).
923 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
924 Getr += "(";
925 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
926 if (i) Getr += ", ";
927 std::string ParamStr = FT->getArgType(i).getAsString(
928 Context->getPrintingPolicy());
929 Getr += ParamStr;
930 }
931 if (FT->isVariadic()) {
932 if (FT->getNumArgs()) Getr += ", ";
933 Getr += "...";
934 }
935 Getr += ")";
936 } else
937 Getr += "()";
938 }
939 Getr += ";\n";
940 Getr += "return (_TYPE)";
941 Getr += "objc_getProperty(self, _cmd, ";
942 RewriteIvarOffsetComputation(OID, Getr);
943 Getr += ", 1)";
944 }
945 else
946 Getr += "return " + getIvarAccessString(OID);
947 Getr += "; }";
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000948 InsertText(startGetterSetterLoc, Getr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000949 }
950
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000951 if (PD->isReadOnly() ||
952 !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000953 return;
954
955 // Generate the 'setter' function.
956 std::string Setr;
957 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
958 ObjCPropertyDecl::OBJC_PR_copy);
959 if (GenSetProperty && !objcSetPropertyDefined) {
960 objcSetPropertyDefined = true;
961 // FIXME. Is this attribute correct in all cases?
962 Setr = "\nextern \"C\" __declspec(dllimport) "
963 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
964 }
965
966 RewriteObjCMethodDecl(OID->getContainingInterface(),
967 PD->getSetterMethodDecl(), Setr);
968 Setr += "{ ";
969 // Synthesize an explicit cast to initialize the ivar.
970 // See objc-act.c:objc_synthesize_new_setter() for details.
971 if (GenSetProperty) {
972 Setr += "objc_setProperty (self, _cmd, ";
973 RewriteIvarOffsetComputation(OID, Setr);
974 Setr += ", (id)";
975 Setr += PD->getName();
976 Setr += ", ";
977 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
978 Setr += "0, ";
979 else
980 Setr += "1, ";
981 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
982 Setr += "1)";
983 else
984 Setr += "0)";
985 }
986 else {
987 Setr += getIvarAccessString(OID) + " = ";
988 Setr += PD->getName();
989 }
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000990 Setr += "; }\n";
991 InsertText(startGetterSetterLoc, Setr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000992}
993
994static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
995 std::string &typedefString) {
996 typedefString += "#ifndef _REWRITER_typedef_";
997 typedefString += ForwardDecl->getNameAsString();
998 typedefString += "\n";
999 typedefString += "#define _REWRITER_typedef_";
1000 typedefString += ForwardDecl->getNameAsString();
1001 typedefString += "\n";
1002 typedefString += "typedef struct objc_object ";
1003 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001004 // typedef struct { } _objc_exc_Classname;
1005 typedefString += ";\ntypedef struct {} _objc_exc_";
1006 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001007 typedefString += ";\n#endif\n";
1008}
1009
1010void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
1011 const std::string &typedefString) {
1012 SourceLocation startLoc = ClassDecl->getLocStart();
1013 const char *startBuf = SM->getCharacterData(startLoc);
1014 const char *semiPtr = strchr(startBuf, ';');
1015 // Replace the @class with typedefs corresponding to the classes.
1016 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
1017}
1018
1019void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
1020 std::string typedefString;
1021 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
1022 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
1023 if (I == D.begin()) {
1024 // Translate to typedef's that forward reference structs with the same name
1025 // as the class. As a convenience, we include the original declaration
1026 // as a comment.
1027 typedefString += "// @class ";
1028 typedefString += ForwardDecl->getNameAsString();
1029 typedefString += ";\n";
1030 }
1031 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1032 }
1033 DeclGroupRef::iterator I = D.begin();
1034 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
1035}
1036
1037void RewriteModernObjC::RewriteForwardClassDecl(
1038 const llvm::SmallVector<Decl*, 8> &D) {
1039 std::string typedefString;
1040 for (unsigned i = 0; i < D.size(); i++) {
1041 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
1042 if (i == 0) {
1043 typedefString += "// @class ";
1044 typedefString += ForwardDecl->getNameAsString();
1045 typedefString += ";\n";
1046 }
1047 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1048 }
1049 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
1050}
1051
1052void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
1053 // When method is a synthesized one, such as a getter/setter there is
1054 // nothing to rewrite.
1055 if (Method->isImplicit())
1056 return;
1057 SourceLocation LocStart = Method->getLocStart();
1058 SourceLocation LocEnd = Method->getLocEnd();
1059
1060 if (SM->getExpansionLineNumber(LocEnd) >
1061 SM->getExpansionLineNumber(LocStart)) {
1062 InsertText(LocStart, "#if 0\n");
1063 ReplaceText(LocEnd, 1, ";\n#endif\n");
1064 } else {
1065 InsertText(LocStart, "// ");
1066 }
1067}
1068
1069void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
1070 SourceLocation Loc = prop->getAtLoc();
1071
1072 ReplaceText(Loc, 0, "// ");
1073 // FIXME: handle properties that are declared across multiple lines.
1074}
1075
1076void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
1077 SourceLocation LocStart = CatDecl->getLocStart();
1078
1079 // FIXME: handle category headers that are declared across multiple lines.
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001080 if (CatDecl->getIvarRBraceLoc().isValid()) {
1081 ReplaceText(LocStart, 1, "/** ");
1082 ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1083 }
1084 else {
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001085 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001086 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001087
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001088 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
1089 E = CatDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001090 RewriteProperty(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001091
1092 for (ObjCCategoryDecl::instmeth_iterator
1093 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
1094 I != E; ++I)
1095 RewriteMethodDeclaration(*I);
1096 for (ObjCCategoryDecl::classmeth_iterator
1097 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
1098 I != E; ++I)
1099 RewriteMethodDeclaration(*I);
1100
1101 // Lastly, comment out the @end.
1102 ReplaceText(CatDecl->getAtEndRange().getBegin(),
1103 strlen("@end"), "/* @end */");
1104}
1105
1106void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1107 SourceLocation LocStart = PDecl->getLocStart();
1108 assert(PDecl->isThisDeclarationADefinition());
1109
1110 // FIXME: handle protocol headers that are declared across multiple lines.
1111 ReplaceText(LocStart, 0, "// ");
1112
1113 for (ObjCProtocolDecl::instmeth_iterator
1114 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
1115 I != E; ++I)
1116 RewriteMethodDeclaration(*I);
1117 for (ObjCProtocolDecl::classmeth_iterator
1118 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1119 I != E; ++I)
1120 RewriteMethodDeclaration(*I);
1121
1122 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1123 E = PDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001124 RewriteProperty(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001125
1126 // Lastly, comment out the @end.
1127 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1128 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
1129
1130 // Must comment out @optional/@required
1131 const char *startBuf = SM->getCharacterData(LocStart);
1132 const char *endBuf = SM->getCharacterData(LocEnd);
1133 for (const char *p = startBuf; p < endBuf; p++) {
1134 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1135 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1136 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1137
1138 }
1139 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1140 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1141 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1142
1143 }
1144 }
1145}
1146
1147void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1148 SourceLocation LocStart = (*D.begin())->getLocStart();
1149 if (LocStart.isInvalid())
1150 llvm_unreachable("Invalid SourceLocation");
1151 // FIXME: handle forward protocol that are declared across multiple lines.
1152 ReplaceText(LocStart, 0, "// ");
1153}
1154
1155void
1156RewriteModernObjC::RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG) {
1157 SourceLocation LocStart = DG[0]->getLocStart();
1158 if (LocStart.isInvalid())
1159 llvm_unreachable("Invalid SourceLocation");
1160 // FIXME: handle forward protocol that are declared across multiple lines.
1161 ReplaceText(LocStart, 0, "// ");
1162}
1163
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +00001164void
1165RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
1166 SourceLocation LocStart = LSD->getExternLoc();
1167 if (LocStart.isInvalid())
1168 llvm_unreachable("Invalid extern SourceLocation");
1169
1170 ReplaceText(LocStart, 0, "// ");
1171 if (!LSD->hasBraces())
1172 return;
1173 // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
1174 SourceLocation LocRBrace = LSD->getRBraceLoc();
1175 if (LocRBrace.isInvalid())
1176 llvm_unreachable("Invalid rbrace SourceLocation");
1177 ReplaceText(LocRBrace, 0, "// ");
1178}
1179
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001180void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1181 const FunctionType *&FPRetType) {
1182 if (T->isObjCQualifiedIdType())
1183 ResultStr += "id";
1184 else if (T->isFunctionPointerType() ||
1185 T->isBlockPointerType()) {
1186 // needs special handling, since pointer-to-functions have special
1187 // syntax (where a decaration models use).
1188 QualType retType = T;
1189 QualType PointeeTy;
1190 if (const PointerType* PT = retType->getAs<PointerType>())
1191 PointeeTy = PT->getPointeeType();
1192 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1193 PointeeTy = BPT->getPointeeType();
1194 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1195 ResultStr += FPRetType->getResultType().getAsString(
1196 Context->getPrintingPolicy());
1197 ResultStr += "(*";
1198 }
1199 } else
1200 ResultStr += T.getAsString(Context->getPrintingPolicy());
1201}
1202
1203void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1204 ObjCMethodDecl *OMD,
1205 std::string &ResultStr) {
1206 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1207 const FunctionType *FPRetType = 0;
1208 ResultStr += "\nstatic ";
1209 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1210 ResultStr += " ";
1211
1212 // Unique method name
1213 std::string NameStr;
1214
1215 if (OMD->isInstanceMethod())
1216 NameStr += "_I_";
1217 else
1218 NameStr += "_C_";
1219
1220 NameStr += IDecl->getNameAsString();
1221 NameStr += "_";
1222
1223 if (ObjCCategoryImplDecl *CID =
1224 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1225 NameStr += CID->getNameAsString();
1226 NameStr += "_";
1227 }
1228 // Append selector names, replacing ':' with '_'
1229 {
1230 std::string selString = OMD->getSelector().getAsString();
1231 int len = selString.size();
1232 for (int i = 0; i < len; i++)
1233 if (selString[i] == ':')
1234 selString[i] = '_';
1235 NameStr += selString;
1236 }
1237 // Remember this name for metadata emission
1238 MethodInternalNames[OMD] = NameStr;
1239 ResultStr += NameStr;
1240
1241 // Rewrite arguments
1242 ResultStr += "(";
1243
1244 // invisible arguments
1245 if (OMD->isInstanceMethod()) {
1246 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1247 selfTy = Context->getPointerType(selfTy);
1248 if (!LangOpts.MicrosoftExt) {
1249 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1250 ResultStr += "struct ";
1251 }
1252 // When rewriting for Microsoft, explicitly omit the structure name.
1253 ResultStr += IDecl->getNameAsString();
1254 ResultStr += " *";
1255 }
1256 else
1257 ResultStr += Context->getObjCClassType().getAsString(
1258 Context->getPrintingPolicy());
1259
1260 ResultStr += " self, ";
1261 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1262 ResultStr += " _cmd";
1263
1264 // Method arguments.
1265 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1266 E = OMD->param_end(); PI != E; ++PI) {
1267 ParmVarDecl *PDecl = *PI;
1268 ResultStr += ", ";
1269 if (PDecl->getType()->isObjCQualifiedIdType()) {
1270 ResultStr += "id ";
1271 ResultStr += PDecl->getNameAsString();
1272 } else {
1273 std::string Name = PDecl->getNameAsString();
1274 QualType QT = PDecl->getType();
1275 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian2610f902012-03-27 16:42:20 +00001276 (void)convertBlockPointerToFunctionPointer(QT);
1277 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001278 ResultStr += Name;
1279 }
1280 }
1281 if (OMD->isVariadic())
1282 ResultStr += ", ...";
1283 ResultStr += ") ";
1284
1285 if (FPRetType) {
1286 ResultStr += ")"; // close the precedence "scope" for "*".
1287
1288 // Now, emit the argument types (if any).
1289 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1290 ResultStr += "(";
1291 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1292 if (i) ResultStr += ", ";
1293 std::string ParamStr = FT->getArgType(i).getAsString(
1294 Context->getPrintingPolicy());
1295 ResultStr += ParamStr;
1296 }
1297 if (FT->isVariadic()) {
1298 if (FT->getNumArgs()) ResultStr += ", ";
1299 ResultStr += "...";
1300 }
1301 ResultStr += ")";
1302 } else {
1303 ResultStr += "()";
1304 }
1305 }
1306}
1307void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1308 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1309 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1310
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001311 if (IMD) {
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001312 if (IMD->getIvarRBraceLoc().isValid()) {
1313 ReplaceText(IMD->getLocStart(), 1, "/** ");
1314 ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001315 }
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001316 else {
1317 InsertText(IMD->getLocStart(), "// ");
1318 }
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001319 }
1320 else
1321 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001322
1323 for (ObjCCategoryImplDecl::instmeth_iterator
1324 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1325 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1326 I != E; ++I) {
1327 std::string ResultStr;
1328 ObjCMethodDecl *OMD = *I;
1329 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1330 SourceLocation LocStart = OMD->getLocStart();
1331 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1332
1333 const char *startBuf = SM->getCharacterData(LocStart);
1334 const char *endBuf = SM->getCharacterData(LocEnd);
1335 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1336 }
1337
1338 for (ObjCCategoryImplDecl::classmeth_iterator
1339 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1340 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1341 I != E; ++I) {
1342 std::string ResultStr;
1343 ObjCMethodDecl *OMD = *I;
1344 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1345 SourceLocation LocStart = OMD->getLocStart();
1346 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1347
1348 const char *startBuf = SM->getCharacterData(LocStart);
1349 const char *endBuf = SM->getCharacterData(LocEnd);
1350 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1351 }
1352 for (ObjCCategoryImplDecl::propimpl_iterator
1353 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1354 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1355 I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001356 RewritePropertyImplDecl(*I, IMD, CID);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001357 }
1358
1359 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1360}
1361
1362void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00001363 // Do not synthesize more than once.
1364 if (ObjCSynthesizedStructs.count(ClassDecl))
1365 return;
1366 // Make sure super class's are written before current class is written.
1367 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1368 while (SuperClass) {
1369 RewriteInterfaceDecl(SuperClass);
1370 SuperClass = SuperClass->getSuperClass();
1371 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001372 std::string ResultStr;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001373 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001374 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001375 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00001376 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1377
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001378 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001379 // Mark this typedef as having been written into its c++ equivalent.
1380 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001381
1382 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001383 E = ClassDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001384 RewriteProperty(*I);
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001385 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001386 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001387 I != E; ++I)
1388 RewriteMethodDeclaration(*I);
1389 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001390 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001391 I != E; ++I)
1392 RewriteMethodDeclaration(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001393
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001394 // Lastly, comment out the @end.
1395 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1396 "/* @end */");
1397 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001398}
1399
1400Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1401 SourceRange OldRange = PseudoOp->getSourceRange();
1402
1403 // We just magically know some things about the structure of this
1404 // expression.
1405 ObjCMessageExpr *OldMsg =
1406 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1407 PseudoOp->getNumSemanticExprs() - 1));
1408
1409 // Because the rewriter doesn't allow us to rewrite rewritten code,
1410 // we need to suppress rewriting the sub-statements.
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001411 Expr *Base;
1412 SmallVector<Expr*, 2> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001413 {
1414 DisableReplaceStmtScope S(*this);
1415
1416 // Rebuild the base expression if we have one.
1417 Base = 0;
1418 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1419 Base = OldMsg->getInstanceReceiver();
1420 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1421 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1422 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001423
1424 unsigned numArgs = OldMsg->getNumArgs();
1425 for (unsigned i = 0; i < numArgs; i++) {
1426 Expr *Arg = OldMsg->getArg(i);
1427 if (isa<OpaqueValueExpr>(Arg))
1428 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1429 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1430 Args.push_back(Arg);
1431 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001432 }
1433
1434 // TODO: avoid this copy.
1435 SmallVector<SourceLocation, 1> SelLocs;
1436 OldMsg->getSelectorLocs(SelLocs);
1437
1438 ObjCMessageExpr *NewMsg = 0;
1439 switch (OldMsg->getReceiverKind()) {
1440 case ObjCMessageExpr::Class:
1441 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1442 OldMsg->getValueKind(),
1443 OldMsg->getLeftLoc(),
1444 OldMsg->getClassReceiverTypeInfo(),
1445 OldMsg->getSelector(),
1446 SelLocs,
1447 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001448 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001449 OldMsg->getRightLoc(),
1450 OldMsg->isImplicit());
1451 break;
1452
1453 case ObjCMessageExpr::Instance:
1454 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1455 OldMsg->getValueKind(),
1456 OldMsg->getLeftLoc(),
1457 Base,
1458 OldMsg->getSelector(),
1459 SelLocs,
1460 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001461 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001462 OldMsg->getRightLoc(),
1463 OldMsg->isImplicit());
1464 break;
1465
1466 case ObjCMessageExpr::SuperClass:
1467 case ObjCMessageExpr::SuperInstance:
1468 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1469 OldMsg->getValueKind(),
1470 OldMsg->getLeftLoc(),
1471 OldMsg->getSuperLoc(),
1472 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1473 OldMsg->getSuperType(),
1474 OldMsg->getSelector(),
1475 SelLocs,
1476 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001477 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001478 OldMsg->getRightLoc(),
1479 OldMsg->isImplicit());
1480 break;
1481 }
1482
1483 Stmt *Replacement = SynthMessageExpr(NewMsg);
1484 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1485 return Replacement;
1486}
1487
1488Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1489 SourceRange OldRange = PseudoOp->getSourceRange();
1490
1491 // We just magically know some things about the structure of this
1492 // expression.
1493 ObjCMessageExpr *OldMsg =
1494 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1495
1496 // Because the rewriter doesn't allow us to rewrite rewritten code,
1497 // we need to suppress rewriting the sub-statements.
1498 Expr *Base = 0;
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001499 SmallVector<Expr*, 1> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001500 {
1501 DisableReplaceStmtScope S(*this);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001502 // Rebuild the base expression if we have one.
1503 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1504 Base = OldMsg->getInstanceReceiver();
1505 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1506 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1507 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001508 unsigned numArgs = OldMsg->getNumArgs();
1509 for (unsigned i = 0; i < numArgs; i++) {
1510 Expr *Arg = OldMsg->getArg(i);
1511 if (isa<OpaqueValueExpr>(Arg))
1512 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1513 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1514 Args.push_back(Arg);
1515 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001516 }
1517
1518 // Intentionally empty.
1519 SmallVector<SourceLocation, 1> SelLocs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001520
1521 ObjCMessageExpr *NewMsg = 0;
1522 switch (OldMsg->getReceiverKind()) {
1523 case ObjCMessageExpr::Class:
1524 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1525 OldMsg->getValueKind(),
1526 OldMsg->getLeftLoc(),
1527 OldMsg->getClassReceiverTypeInfo(),
1528 OldMsg->getSelector(),
1529 SelLocs,
1530 OldMsg->getMethodDecl(),
1531 Args,
1532 OldMsg->getRightLoc(),
1533 OldMsg->isImplicit());
1534 break;
1535
1536 case ObjCMessageExpr::Instance:
1537 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1538 OldMsg->getValueKind(),
1539 OldMsg->getLeftLoc(),
1540 Base,
1541 OldMsg->getSelector(),
1542 SelLocs,
1543 OldMsg->getMethodDecl(),
1544 Args,
1545 OldMsg->getRightLoc(),
1546 OldMsg->isImplicit());
1547 break;
1548
1549 case ObjCMessageExpr::SuperClass:
1550 case ObjCMessageExpr::SuperInstance:
1551 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1552 OldMsg->getValueKind(),
1553 OldMsg->getLeftLoc(),
1554 OldMsg->getSuperLoc(),
1555 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1556 OldMsg->getSuperType(),
1557 OldMsg->getSelector(),
1558 SelLocs,
1559 OldMsg->getMethodDecl(),
1560 Args,
1561 OldMsg->getRightLoc(),
1562 OldMsg->isImplicit());
1563 break;
1564 }
1565
1566 Stmt *Replacement = SynthMessageExpr(NewMsg);
1567 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1568 return Replacement;
1569}
1570
1571/// SynthCountByEnumWithState - To print:
1572/// ((unsigned int (*)
1573/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1574/// (void *)objc_msgSend)((id)l_collection,
1575/// sel_registerName(
1576/// "countByEnumeratingWithState:objects:count:"),
1577/// &enumState,
1578/// (id *)__rw_items, (unsigned int)16)
1579///
1580void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1581 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1582 "id *, unsigned int))(void *)objc_msgSend)";
1583 buf += "\n\t\t";
1584 buf += "((id)l_collection,\n\t\t";
1585 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1586 buf += "\n\t\t";
1587 buf += "&enumState, "
1588 "(id *)__rw_items, (unsigned int)16)";
1589}
1590
1591/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1592/// statement to exit to its outer synthesized loop.
1593///
1594Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1595 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1596 return S;
1597 // replace break with goto __break_label
1598 std::string buf;
1599
1600 SourceLocation startLoc = S->getLocStart();
1601 buf = "goto __break_label_";
1602 buf += utostr(ObjCBcLabelNo.back());
1603 ReplaceText(startLoc, strlen("break"), buf);
1604
1605 return 0;
1606}
1607
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001608void RewriteModernObjC::ConvertSourceLocationToLineDirective(
1609 SourceLocation Loc,
1610 std::string &LineString) {
1611 if (Loc.isFileID()) {
1612 LineString += "\n#line ";
1613 PresumedLoc PLoc = SM->getPresumedLoc(Loc);
1614 LineString += utostr(PLoc.getLine());
1615 LineString += " \"";
1616 LineString += Lexer::Stringify(PLoc.getFilename());
1617 LineString += "\"\n";
1618 }
1619}
1620
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001621/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1622/// statement to continue with its inner synthesized loop.
1623///
1624Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1625 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1626 return S;
1627 // replace continue with goto __continue_label
1628 std::string buf;
1629
1630 SourceLocation startLoc = S->getLocStart();
1631 buf = "goto __continue_label_";
1632 buf += utostr(ObjCBcLabelNo.back());
1633 ReplaceText(startLoc, strlen("continue"), buf);
1634
1635 return 0;
1636}
1637
1638/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1639/// It rewrites:
1640/// for ( type elem in collection) { stmts; }
1641
1642/// Into:
1643/// {
1644/// type elem;
1645/// struct __objcFastEnumerationState enumState = { 0 };
1646/// id __rw_items[16];
1647/// id l_collection = (id)collection;
1648/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1649/// objects:__rw_items count:16];
1650/// if (limit) {
1651/// unsigned long startMutations = *enumState.mutationsPtr;
1652/// do {
1653/// unsigned long counter = 0;
1654/// do {
1655/// if (startMutations != *enumState.mutationsPtr)
1656/// objc_enumerationMutation(l_collection);
1657/// elem = (type)enumState.itemsPtr[counter++];
1658/// stmts;
1659/// __continue_label: ;
1660/// } while (counter < limit);
1661/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1662/// objects:__rw_items count:16]);
1663/// elem = nil;
1664/// __break_label: ;
1665/// }
1666/// else
1667/// elem = nil;
1668/// }
1669///
1670Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1671 SourceLocation OrigEnd) {
1672 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1673 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1674 "ObjCForCollectionStmt Statement stack mismatch");
1675 assert(!ObjCBcLabelNo.empty() &&
1676 "ObjCForCollectionStmt - Label No stack empty");
1677
1678 SourceLocation startLoc = S->getLocStart();
1679 const char *startBuf = SM->getCharacterData(startLoc);
1680 StringRef elementName;
1681 std::string elementTypeAsString;
1682 std::string buf;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001683 // line directive first.
1684 SourceLocation ForEachLoc = S->getForLoc();
1685 ConvertSourceLocationToLineDirective(ForEachLoc, buf);
1686 buf += "{\n\t";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001687 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1688 // type elem;
1689 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1690 QualType ElementType = cast<ValueDecl>(D)->getType();
1691 if (ElementType->isObjCQualifiedIdType() ||
1692 ElementType->isObjCQualifiedInterfaceType())
1693 // Simply use 'id' for all qualified types.
1694 elementTypeAsString = "id";
1695 else
1696 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1697 buf += elementTypeAsString;
1698 buf += " ";
1699 elementName = D->getName();
1700 buf += elementName;
1701 buf += ";\n\t";
1702 }
1703 else {
1704 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1705 elementName = DR->getDecl()->getName();
1706 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1707 if (VD->getType()->isObjCQualifiedIdType() ||
1708 VD->getType()->isObjCQualifiedInterfaceType())
1709 // Simply use 'id' for all qualified types.
1710 elementTypeAsString = "id";
1711 else
1712 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1713 }
1714
1715 // struct __objcFastEnumerationState enumState = { 0 };
1716 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1717 // id __rw_items[16];
1718 buf += "id __rw_items[16];\n\t";
1719 // id l_collection = (id)
1720 buf += "id l_collection = (id)";
1721 // Find start location of 'collection' the hard way!
1722 const char *startCollectionBuf = startBuf;
1723 startCollectionBuf += 3; // skip 'for'
1724 startCollectionBuf = strchr(startCollectionBuf, '(');
1725 startCollectionBuf++; // skip '('
1726 // find 'in' and skip it.
1727 while (*startCollectionBuf != ' ' ||
1728 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1729 (*(startCollectionBuf+3) != ' ' &&
1730 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1731 startCollectionBuf++;
1732 startCollectionBuf += 3;
1733
1734 // Replace: "for (type element in" with string constructed thus far.
1735 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1736 // Replace ')' in for '(' type elem in collection ')' with ';'
1737 SourceLocation rightParenLoc = S->getRParenLoc();
1738 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1739 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1740 buf = ";\n\t";
1741
1742 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1743 // objects:__rw_items count:16];
1744 // which is synthesized into:
1745 // unsigned int limit =
1746 // ((unsigned int (*)
1747 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1748 // (void *)objc_msgSend)((id)l_collection,
1749 // sel_registerName(
1750 // "countByEnumeratingWithState:objects:count:"),
1751 // (struct __objcFastEnumerationState *)&state,
1752 // (id *)__rw_items, (unsigned int)16);
1753 buf += "unsigned long limit =\n\t\t";
1754 SynthCountByEnumWithState(buf);
1755 buf += ";\n\t";
1756 /// if (limit) {
1757 /// unsigned long startMutations = *enumState.mutationsPtr;
1758 /// do {
1759 /// unsigned long counter = 0;
1760 /// do {
1761 /// if (startMutations != *enumState.mutationsPtr)
1762 /// objc_enumerationMutation(l_collection);
1763 /// elem = (type)enumState.itemsPtr[counter++];
1764 buf += "if (limit) {\n\t";
1765 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1766 buf += "do {\n\t\t";
1767 buf += "unsigned long counter = 0;\n\t\t";
1768 buf += "do {\n\t\t\t";
1769 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1770 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1771 buf += elementName;
1772 buf += " = (";
1773 buf += elementTypeAsString;
1774 buf += ")enumState.itemsPtr[counter++];";
1775 // Replace ')' in for '(' type elem in collection ')' with all of these.
1776 ReplaceText(lparenLoc, 1, buf);
1777
1778 /// __continue_label: ;
1779 /// } while (counter < limit);
1780 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1781 /// objects:__rw_items count:16]);
1782 /// elem = nil;
1783 /// __break_label: ;
1784 /// }
1785 /// else
1786 /// elem = nil;
1787 /// }
1788 ///
1789 buf = ";\n\t";
1790 buf += "__continue_label_";
1791 buf += utostr(ObjCBcLabelNo.back());
1792 buf += ": ;";
1793 buf += "\n\t\t";
1794 buf += "} while (counter < limit);\n\t";
1795 buf += "} while (limit = ";
1796 SynthCountByEnumWithState(buf);
1797 buf += ");\n\t";
1798 buf += elementName;
1799 buf += " = ((";
1800 buf += elementTypeAsString;
1801 buf += ")0);\n\t";
1802 buf += "__break_label_";
1803 buf += utostr(ObjCBcLabelNo.back());
1804 buf += ": ;\n\t";
1805 buf += "}\n\t";
1806 buf += "else\n\t\t";
1807 buf += elementName;
1808 buf += " = ((";
1809 buf += elementTypeAsString;
1810 buf += ")0);\n\t";
1811 buf += "}\n";
1812
1813 // Insert all these *after* the statement body.
1814 // FIXME: If this should support Obj-C++, support CXXTryStmt
1815 if (isa<CompoundStmt>(S->getBody())) {
1816 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1817 InsertText(endBodyLoc, buf);
1818 } else {
1819 /* Need to treat single statements specially. For example:
1820 *
1821 * for (A *a in b) if (stuff()) break;
1822 * for (A *a in b) xxxyy;
1823 *
1824 * The following code simply scans ahead to the semi to find the actual end.
1825 */
1826 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1827 const char *semiBuf = strchr(stmtBuf, ';');
1828 assert(semiBuf && "Can't find ';'");
1829 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1830 InsertText(endBodyLoc, buf);
1831 }
1832 Stmts.pop_back();
1833 ObjCBcLabelNo.pop_back();
1834 return 0;
1835}
1836
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001837static void Write_RethrowObject(std::string &buf) {
1838 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1839 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1840 buf += "\tid rethrow;\n";
1841 buf += "\t} _fin_force_rethow(_rethrow);";
1842}
1843
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001844/// RewriteObjCSynchronizedStmt -
1845/// This routine rewrites @synchronized(expr) stmt;
1846/// into:
1847/// objc_sync_enter(expr);
1848/// @try stmt @finally { objc_sync_exit(expr); }
1849///
1850Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1851 // Get the start location and compute the semi location.
1852 SourceLocation startLoc = S->getLocStart();
1853 const char *startBuf = SM->getCharacterData(startLoc);
1854
1855 assert((*startBuf == '@') && "bogus @synchronized location");
1856
1857 std::string buf;
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001858 buf = "{ id _rethrow = 0; id _sync_obj = ";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001859
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001860 const char *lparenBuf = startBuf;
1861 while (*lparenBuf != '(') lparenBuf++;
1862 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001863
1864 buf = "; objc_sync_enter(_sync_obj);\n";
1865 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1866 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1867 buf += "\n\tid sync_exit;";
1868 buf += "\n\t} _sync_exit(_sync_obj);\n";
1869
1870 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1871 // the sync expression is typically a message expression that's already
1872 // been rewritten! (which implies the SourceLocation's are invalid).
1873 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1874 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1875 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1876 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1877
1878 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1879 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1880 assert (*LBraceLocBuf == '{');
1881 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001882
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001883 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay9ab511c2012-03-16 22:20:39 +00001884 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1885 "bogus @synchronized block");
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001886
1887 buf = "} catch (id e) {_rethrow = e;}\n";
1888 Write_RethrowObject(buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001889 buf += "}\n";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001890 buf += "}\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001891
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001892 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001893
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001894 return 0;
1895}
1896
1897void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1898{
1899 // Perform a bottom up traversal of all children.
1900 for (Stmt::child_range CI = S->children(); CI; ++CI)
1901 if (*CI)
1902 WarnAboutReturnGotoStmts(*CI);
1903
1904 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1905 Diags.Report(Context->getFullLoc(S->getLocStart()),
1906 TryFinallyContainsReturnDiag);
1907 }
1908 return;
1909}
1910
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00001911Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
1912 SourceLocation startLoc = S->getAtLoc();
1913 ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
Fariborz Jahanianc9b72b62012-05-24 22:59:56 +00001914 ReplaceText(S->getSubStmt()->getLocStart(), 1,
1915 "{ __AtAutoreleasePool __autoreleasepool; ");
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00001916
1917 return 0;
1918}
1919
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001920Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001921 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001922 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001923 std::string buf;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001924 SourceLocation TryLocation = S->getAtTryLoc();
1925 ConvertSourceLocationToLineDirective(TryLocation, buf);
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001926
1927 if (finalStmt) {
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001928 if (noCatch)
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001929 buf += "{ id volatile _rethrow = 0;\n";
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001930 else {
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001931 buf += "{ id volatile _rethrow = 0;\ntry {\n";
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001932 }
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001933 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001934 // Get the start location and compute the semi location.
1935 SourceLocation startLoc = S->getLocStart();
1936 const char *startBuf = SM->getCharacterData(startLoc);
1937
1938 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001939 if (finalStmt)
1940 ReplaceText(startLoc, 1, buf);
1941 else
1942 // @try -> try
1943 ReplaceText(startLoc, 1, "");
1944
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001945 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1946 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001947 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001948
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001949 startLoc = Catch->getLocStart();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001950 bool AtRemoved = false;
1951 if (catchDecl) {
1952 QualType t = catchDecl->getType();
1953 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1954 // Should be a pointer to a class.
1955 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1956 if (IDecl) {
1957 std::string Result;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001958 ConvertSourceLocationToLineDirective(Catch->getLocStart(), Result);
1959
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001960 startBuf = SM->getCharacterData(startLoc);
1961 assert((*startBuf == '@') && "bogus @catch location");
1962 SourceLocation rParenLoc = Catch->getRParenLoc();
1963 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1964
1965 // _objc_exc_Foo *_e as argument to catch.
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001966 Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001967 Result += " *_"; Result += catchDecl->getNameAsString();
1968 Result += ")";
1969 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1970 // Foo *e = (Foo *)_e;
1971 Result.clear();
1972 Result = "{ ";
1973 Result += IDecl->getNameAsString();
1974 Result += " *"; Result += catchDecl->getNameAsString();
1975 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1976 Result += "_"; Result += catchDecl->getNameAsString();
1977
1978 Result += "; ";
1979 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
1980 ReplaceText(lBraceLoc, 1, Result);
1981 AtRemoved = true;
1982 }
1983 }
1984 }
1985 if (!AtRemoved)
1986 // @catch -> catch
1987 ReplaceText(startLoc, 1, "");
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001988
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001989 }
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001990 if (finalStmt) {
1991 buf.clear();
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001992 SourceLocation FinallyLoc = finalStmt->getLocStart();
1993
1994 if (noCatch) {
1995 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
1996 buf += "catch (id e) {_rethrow = e;}\n";
1997 }
1998 else {
1999 buf += "}\n";
2000 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2001 buf += "catch (id e) {_rethrow = e;}\n";
2002 }
2003
Fariborz Jahanian220419a2012-03-15 23:50:33 +00002004 SourceLocation startFinalLoc = finalStmt->getLocStart();
2005 ReplaceText(startFinalLoc, 8, buf);
2006 Stmt *body = finalStmt->getFinallyBody();
2007 SourceLocation startFinalBodyLoc = body->getLocStart();
2008 buf.clear();
Fariborz Jahanian542125f2012-03-16 21:33:16 +00002009 Write_RethrowObject(buf);
Fariborz Jahanian220419a2012-03-15 23:50:33 +00002010 ReplaceText(startFinalBodyLoc, 1, buf);
2011
2012 SourceLocation endFinalBodyLoc = body->getLocEnd();
2013 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00002014 // Now check for any return/continue/go statements within the @try.
2015 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanian220419a2012-03-15 23:50:33 +00002016 }
2017
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002018 return 0;
2019}
2020
2021// This can't be done with ReplaceStmt(S, ThrowExpr), since
2022// the throw expression is typically a message expression that's already
2023// been rewritten! (which implies the SourceLocation's are invalid).
2024Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
2025 // Get the start location and compute the semi location.
2026 SourceLocation startLoc = S->getLocStart();
2027 const char *startBuf = SM->getCharacterData(startLoc);
2028
2029 assert((*startBuf == '@') && "bogus @throw location");
2030
2031 std::string buf;
2032 /* void objc_exception_throw(id) __attribute__((noreturn)); */
2033 if (S->getThrowExpr())
2034 buf = "objc_exception_throw(";
Fariborz Jahanian40539462012-03-16 16:52:06 +00002035 else
2036 buf = "throw";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002037
2038 // handle "@ throw" correctly.
2039 const char *wBuf = strchr(startBuf, 'w');
2040 assert((*wBuf == 'w') && "@throw: can't find 'w'");
2041 ReplaceText(startLoc, wBuf-startBuf+1, buf);
2042
2043 const char *semiBuf = strchr(startBuf, ';');
2044 assert((*semiBuf == ';') && "@throw: can't find ';'");
2045 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian40539462012-03-16 16:52:06 +00002046 if (S->getThrowExpr())
2047 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002048 return 0;
2049}
2050
2051Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2052 // Create a new string expression.
2053 QualType StrType = Context->getPointerType(Context->CharTy);
2054 std::string StrEncoding;
2055 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
2056 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
2057 StringLiteral::Ascii, false,
2058 StrType, SourceLocation());
2059 ReplaceStmt(Exp, Replacement);
2060
2061 // Replace this subexpr in the parent.
2062 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2063 return Replacement;
2064}
2065
2066Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2067 if (!SelGetUidFunctionDecl)
2068 SynthSelGetUidFunctionDecl();
2069 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2070 // Create a call to sel_registerName("selName").
2071 SmallVector<Expr*, 8> SelExprs;
2072 QualType argType = Context->getPointerType(Context->CharTy);
2073 SelExprs.push_back(StringLiteral::Create(*Context,
2074 Exp->getSelector().getAsString(),
2075 StringLiteral::Ascii, false,
2076 argType, SourceLocation()));
2077 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2078 &SelExprs[0], SelExprs.size());
2079 ReplaceStmt(Exp, SelExp);
2080 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2081 return SelExp;
2082}
2083
2084CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
2085 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2086 SourceLocation EndLoc) {
2087 // Get the type, we will need to reference it in a couple spots.
2088 QualType msgSendType = FD->getType();
2089
2090 // Create a reference to the objc_msgSend() declaration.
2091 DeclRefExpr *DRE =
John McCallf4b88a42012-03-10 09:33:50 +00002092 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002093
2094 // Now, we cast the reference to a pointer to the objc_msgSend type.
2095 QualType pToFunc = Context->getPointerType(msgSendType);
2096 ImplicitCastExpr *ICE =
2097 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2098 DRE, 0, VK_RValue);
2099
2100 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2101
2102 CallExpr *Exp =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002103 new (Context) CallExpr(*Context, ICE, llvm::makeArrayRef(args, nargs),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002104 FT->getCallResultType(*Context),
2105 VK_RValue, EndLoc);
2106 return Exp;
2107}
2108
2109static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2110 const char *&startRef, const char *&endRef) {
2111 while (startBuf < endBuf) {
2112 if (*startBuf == '<')
2113 startRef = startBuf; // mark the start.
2114 if (*startBuf == '>') {
2115 if (startRef && *startRef == '<') {
2116 endRef = startBuf; // mark the end.
2117 return true;
2118 }
2119 return false;
2120 }
2121 startBuf++;
2122 }
2123 return false;
2124}
2125
2126static void scanToNextArgument(const char *&argRef) {
2127 int angle = 0;
2128 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2129 if (*argRef == '<')
2130 angle++;
2131 else if (*argRef == '>')
2132 angle--;
2133 argRef++;
2134 }
2135 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2136}
2137
2138bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2139 if (T->isObjCQualifiedIdType())
2140 return true;
2141 if (const PointerType *PT = T->getAs<PointerType>()) {
2142 if (PT->getPointeeType()->isObjCQualifiedIdType())
2143 return true;
2144 }
2145 if (T->isObjCObjectPointerType()) {
2146 T = T->getPointeeType();
2147 return T->isObjCQualifiedInterfaceType();
2148 }
2149 if (T->isArrayType()) {
2150 QualType ElemTy = Context->getBaseElementType(T);
2151 return needToScanForQualifiers(ElemTy);
2152 }
2153 return false;
2154}
2155
2156void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2157 QualType Type = E->getType();
2158 if (needToScanForQualifiers(Type)) {
2159 SourceLocation Loc, EndLoc;
2160
2161 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2162 Loc = ECE->getLParenLoc();
2163 EndLoc = ECE->getRParenLoc();
2164 } else {
2165 Loc = E->getLocStart();
2166 EndLoc = E->getLocEnd();
2167 }
2168 // This will defend against trying to rewrite synthesized expressions.
2169 if (Loc.isInvalid() || EndLoc.isInvalid())
2170 return;
2171
2172 const char *startBuf = SM->getCharacterData(Loc);
2173 const char *endBuf = SM->getCharacterData(EndLoc);
2174 const char *startRef = 0, *endRef = 0;
2175 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2176 // Get the locations of the startRef, endRef.
2177 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2178 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2179 // Comment out the protocol references.
2180 InsertText(LessLoc, "/*");
2181 InsertText(GreaterLoc, "*/");
2182 }
2183 }
2184}
2185
2186void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2187 SourceLocation Loc;
2188 QualType Type;
2189 const FunctionProtoType *proto = 0;
2190 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2191 Loc = VD->getLocation();
2192 Type = VD->getType();
2193 }
2194 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2195 Loc = FD->getLocation();
2196 // Check for ObjC 'id' and class types that have been adorned with protocol
2197 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2198 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2199 assert(funcType && "missing function type");
2200 proto = dyn_cast<FunctionProtoType>(funcType);
2201 if (!proto)
2202 return;
2203 Type = proto->getResultType();
2204 }
2205 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2206 Loc = FD->getLocation();
2207 Type = FD->getType();
2208 }
2209 else
2210 return;
2211
2212 if (needToScanForQualifiers(Type)) {
2213 // Since types are unique, we need to scan the buffer.
2214
2215 const char *endBuf = SM->getCharacterData(Loc);
2216 const char *startBuf = endBuf;
2217 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2218 startBuf--; // scan backward (from the decl location) for return type.
2219 const char *startRef = 0, *endRef = 0;
2220 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2221 // Get the locations of the startRef, endRef.
2222 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2223 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2224 // Comment out the protocol references.
2225 InsertText(LessLoc, "/*");
2226 InsertText(GreaterLoc, "*/");
2227 }
2228 }
2229 if (!proto)
2230 return; // most likely, was a variable
2231 // Now check arguments.
2232 const char *startBuf = SM->getCharacterData(Loc);
2233 const char *startFuncBuf = startBuf;
2234 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2235 if (needToScanForQualifiers(proto->getArgType(i))) {
2236 // Since types are unique, we need to scan the buffer.
2237
2238 const char *endBuf = startBuf;
2239 // scan forward (from the decl location) for argument types.
2240 scanToNextArgument(endBuf);
2241 const char *startRef = 0, *endRef = 0;
2242 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2243 // Get the locations of the startRef, endRef.
2244 SourceLocation LessLoc =
2245 Loc.getLocWithOffset(startRef-startFuncBuf);
2246 SourceLocation GreaterLoc =
2247 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2248 // Comment out the protocol references.
2249 InsertText(LessLoc, "/*");
2250 InsertText(GreaterLoc, "*/");
2251 }
2252 startBuf = ++endBuf;
2253 }
2254 else {
2255 // If the function name is derived from a macro expansion, then the
2256 // argument buffer will not follow the name. Need to speak with Chris.
2257 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2258 startBuf++; // scan forward (from the decl location) for argument types.
2259 startBuf++;
2260 }
2261 }
2262}
2263
2264void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2265 QualType QT = ND->getType();
2266 const Type* TypePtr = QT->getAs<Type>();
2267 if (!isa<TypeOfExprType>(TypePtr))
2268 return;
2269 while (isa<TypeOfExprType>(TypePtr)) {
2270 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2271 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2272 TypePtr = QT->getAs<Type>();
2273 }
2274 // FIXME. This will not work for multiple declarators; as in:
2275 // __typeof__(a) b,c,d;
2276 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2277 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2278 const char *startBuf = SM->getCharacterData(DeclLoc);
2279 if (ND->getInit()) {
2280 std::string Name(ND->getNameAsString());
2281 TypeAsString += " " + Name + " = ";
2282 Expr *E = ND->getInit();
2283 SourceLocation startLoc;
2284 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2285 startLoc = ECE->getLParenLoc();
2286 else
2287 startLoc = E->getLocStart();
2288 startLoc = SM->getExpansionLoc(startLoc);
2289 const char *endBuf = SM->getCharacterData(startLoc);
2290 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2291 }
2292 else {
2293 SourceLocation X = ND->getLocEnd();
2294 X = SM->getExpansionLoc(X);
2295 const char *endBuf = SM->getCharacterData(X);
2296 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2297 }
2298}
2299
2300// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2301void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2302 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2303 SmallVector<QualType, 16> ArgTys;
2304 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2305 QualType getFuncType =
2306 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
2307 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2308 SourceLocation(),
2309 SourceLocation(),
2310 SelGetUidIdent, getFuncType, 0,
2311 SC_Extern,
2312 SC_None, false);
2313}
2314
2315void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2316 // declared in <objc/objc.h>
2317 if (FD->getIdentifier() &&
2318 FD->getName() == "sel_registerName") {
2319 SelGetUidFunctionDecl = FD;
2320 return;
2321 }
2322 RewriteObjCQualifiedInterfaceTypes(FD);
2323}
2324
2325void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2326 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2327 const char *argPtr = TypeString.c_str();
2328 if (!strchr(argPtr, '^')) {
2329 Str += TypeString;
2330 return;
2331 }
2332 while (*argPtr) {
2333 Str += (*argPtr == '^' ? '*' : *argPtr);
2334 argPtr++;
2335 }
2336}
2337
2338// FIXME. Consolidate this routine with RewriteBlockPointerType.
2339void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2340 ValueDecl *VD) {
2341 QualType Type = VD->getType();
2342 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2343 const char *argPtr = TypeString.c_str();
2344 int paren = 0;
2345 while (*argPtr) {
2346 switch (*argPtr) {
2347 case '(':
2348 Str += *argPtr;
2349 paren++;
2350 break;
2351 case ')':
2352 Str += *argPtr;
2353 paren--;
2354 break;
2355 case '^':
2356 Str += '*';
2357 if (paren == 1)
2358 Str += VD->getNameAsString();
2359 break;
2360 default:
2361 Str += *argPtr;
2362 break;
2363 }
2364 argPtr++;
2365 }
2366}
2367
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002368void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2369 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2370 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2371 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2372 if (!proto)
2373 return;
2374 QualType Type = proto->getResultType();
2375 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2376 FdStr += " ";
2377 FdStr += FD->getName();
2378 FdStr += "(";
2379 unsigned numArgs = proto->getNumArgs();
2380 for (unsigned i = 0; i < numArgs; i++) {
2381 QualType ArgType = proto->getArgType(i);
2382 RewriteBlockPointerType(FdStr, ArgType);
2383 if (i+1 < numArgs)
2384 FdStr += ", ";
2385 }
Fariborz Jahanianb5863da2012-04-19 16:30:28 +00002386 if (FD->isVariadic()) {
2387 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2388 }
2389 else
2390 FdStr += ");\n";
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002391 InsertText(FunLocStart, FdStr);
2392}
2393
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002394// SynthSuperContructorFunctionDecl - id __rw_objc_super(id obj, id super);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002395void RewriteModernObjC::SynthSuperContructorFunctionDecl() {
2396 if (SuperContructorFunctionDecl)
2397 return;
2398 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2399 SmallVector<QualType, 16> ArgTys;
2400 QualType argT = Context->getObjCIdType();
2401 assert(!argT.isNull() && "Can't find 'id' type");
2402 ArgTys.push_back(argT);
2403 ArgTys.push_back(argT);
2404 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2405 &ArgTys[0], ArgTys.size());
2406 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2407 SourceLocation(),
2408 SourceLocation(),
2409 msgSendIdent, msgSendType, 0,
2410 SC_Extern,
2411 SC_None, false);
2412}
2413
2414// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2415void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2416 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2417 SmallVector<QualType, 16> ArgTys;
2418 QualType argT = Context->getObjCIdType();
2419 assert(!argT.isNull() && "Can't find 'id' type");
2420 ArgTys.push_back(argT);
2421 argT = Context->getObjCSelType();
2422 assert(!argT.isNull() && "Can't find 'SEL' type");
2423 ArgTys.push_back(argT);
2424 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2425 &ArgTys[0], ArgTys.size(),
2426 true /*isVariadic*/);
2427 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2428 SourceLocation(),
2429 SourceLocation(),
2430 msgSendIdent, msgSendType, 0,
2431 SC_Extern,
2432 SC_None, false);
2433}
2434
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002435// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002436void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2437 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002438 SmallVector<QualType, 2> ArgTys;
2439 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002440 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002441 &ArgTys[0], 1,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002442 true /*isVariadic*/);
2443 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2444 SourceLocation(),
2445 SourceLocation(),
2446 msgSendIdent, msgSendType, 0,
2447 SC_Extern,
2448 SC_None, false);
2449}
2450
2451// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2452void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2453 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2454 SmallVector<QualType, 16> ArgTys;
2455 QualType argT = Context->getObjCIdType();
2456 assert(!argT.isNull() && "Can't find 'id' type");
2457 ArgTys.push_back(argT);
2458 argT = Context->getObjCSelType();
2459 assert(!argT.isNull() && "Can't find 'SEL' type");
2460 ArgTys.push_back(argT);
2461 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2462 &ArgTys[0], ArgTys.size(),
2463 true /*isVariadic*/);
2464 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2465 SourceLocation(),
2466 SourceLocation(),
2467 msgSendIdent, msgSendType, 0,
2468 SC_Extern,
2469 SC_None, false);
2470}
2471
2472// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002473// id objc_msgSendSuper_stret(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002474void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2475 IdentifierInfo *msgSendIdent =
2476 &Context->Idents.get("objc_msgSendSuper_stret");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002477 SmallVector<QualType, 2> ArgTys;
2478 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002479 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002480 &ArgTys[0], 1,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002481 true /*isVariadic*/);
2482 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2483 SourceLocation(),
2484 SourceLocation(),
2485 msgSendIdent, msgSendType, 0,
2486 SC_Extern,
2487 SC_None, false);
2488}
2489
2490// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2491void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2492 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2493 SmallVector<QualType, 16> ArgTys;
2494 QualType argT = Context->getObjCIdType();
2495 assert(!argT.isNull() && "Can't find 'id' type");
2496 ArgTys.push_back(argT);
2497 argT = Context->getObjCSelType();
2498 assert(!argT.isNull() && "Can't find 'SEL' type");
2499 ArgTys.push_back(argT);
2500 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2501 &ArgTys[0], ArgTys.size(),
2502 true /*isVariadic*/);
2503 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2504 SourceLocation(),
2505 SourceLocation(),
2506 msgSendIdent, msgSendType, 0,
2507 SC_Extern,
2508 SC_None, false);
2509}
2510
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002511// SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002512void RewriteModernObjC::SynthGetClassFunctionDecl() {
2513 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2514 SmallVector<QualType, 16> ArgTys;
2515 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002516 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002517 &ArgTys[0], ArgTys.size());
2518 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2519 SourceLocation(),
2520 SourceLocation(),
2521 getClassIdent, getClassType, 0,
2522 SC_Extern,
2523 SC_None, false);
2524}
2525
2526// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2527void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2528 IdentifierInfo *getSuperClassIdent =
2529 &Context->Idents.get("class_getSuperclass");
2530 SmallVector<QualType, 16> ArgTys;
2531 ArgTys.push_back(Context->getObjCClassType());
2532 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2533 &ArgTys[0], ArgTys.size());
2534 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2535 SourceLocation(),
2536 SourceLocation(),
2537 getSuperClassIdent,
2538 getClassType, 0,
2539 SC_Extern,
2540 SC_None,
2541 false);
2542}
2543
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002544// SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002545void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2546 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2547 SmallVector<QualType, 16> ArgTys;
2548 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002549 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002550 &ArgTys[0], ArgTys.size());
2551 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2552 SourceLocation(),
2553 SourceLocation(),
2554 getClassIdent, getClassType, 0,
2555 SC_Extern,
2556 SC_None, false);
2557}
2558
2559Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2560 QualType strType = getConstantStringStructType();
2561
2562 std::string S = "__NSConstantStringImpl_";
2563
2564 std::string tmpName = InFileName;
2565 unsigned i;
2566 for (i=0; i < tmpName.length(); i++) {
2567 char c = tmpName.at(i);
2568 // replace any non alphanumeric characters with '_'.
2569 if (!isalpha(c) && (c < '0' || c > '9'))
2570 tmpName[i] = '_';
2571 }
2572 S += tmpName;
2573 S += "_";
2574 S += utostr(NumObjCStringLiterals++);
2575
2576 Preamble += "static __NSConstantStringImpl " + S;
2577 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2578 Preamble += "0x000007c8,"; // utf8_str
2579 // The pretty printer for StringLiteral handles escape characters properly.
2580 std::string prettyBufS;
2581 llvm::raw_string_ostream prettyBuf(prettyBufS);
Richard Smithd1420c62012-08-16 03:56:14 +00002582 Exp->getString()->printPretty(prettyBuf, 0, PrintingPolicy(LangOpts));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002583 Preamble += prettyBuf.str();
2584 Preamble += ",";
2585 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2586
2587 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2588 SourceLocation(), &Context->Idents.get(S),
2589 strType, 0, SC_Static, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002590 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002591 SourceLocation());
2592 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2593 Context->getPointerType(DRE->getType()),
2594 VK_RValue, OK_Ordinary,
2595 SourceLocation());
2596 // cast to NSConstantString *
2597 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2598 CK_CPointerToObjCPointerCast, Unop);
2599 ReplaceStmt(Exp, cast);
2600 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2601 return cast;
2602}
2603
Fariborz Jahanian55947042012-03-27 20:17:30 +00002604Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2605 unsigned IntSize =
2606 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2607
2608 Expr *FlagExp = IntegerLiteral::Create(*Context,
2609 llvm::APInt(IntSize, Exp->getValue()),
2610 Context->IntTy, Exp->getLocation());
2611 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2612 CK_BitCast, FlagExp);
2613 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2614 cast);
2615 ReplaceStmt(Exp, PE);
2616 return PE;
2617}
2618
Patrick Beardeb382ec2012-04-19 00:25:12 +00002619Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002620 // synthesize declaration of helper functions needed in this routine.
2621 if (!SelGetUidFunctionDecl)
2622 SynthSelGetUidFunctionDecl();
2623 // use objc_msgSend() for all.
2624 if (!MsgSendFunctionDecl)
2625 SynthMsgSendFunctionDecl();
2626 if (!GetClassFunctionDecl)
2627 SynthGetClassFunctionDecl();
2628
2629 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2630 SourceLocation StartLoc = Exp->getLocStart();
2631 SourceLocation EndLoc = Exp->getLocEnd();
2632
2633 // Synthesize a call to objc_msgSend().
2634 SmallVector<Expr*, 4> MsgExprs;
2635 SmallVector<Expr*, 4> ClsExprs;
2636 QualType argType = Context->getPointerType(Context->CharTy);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002637
Patrick Beardeb382ec2012-04-19 00:25:12 +00002638 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2639 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2640 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002641
Patrick Beardeb382ec2012-04-19 00:25:12 +00002642 IdentifierInfo *clsName = BoxingClass->getIdentifier();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002643 ClsExprs.push_back(StringLiteral::Create(*Context,
2644 clsName->getName(),
2645 StringLiteral::Ascii, false,
2646 argType, SourceLocation()));
2647 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2648 &ClsExprs[0],
2649 ClsExprs.size(),
2650 StartLoc, EndLoc);
2651 MsgExprs.push_back(Cls);
2652
Patrick Beardeb382ec2012-04-19 00:25:12 +00002653 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002654 // it will be the 2nd argument.
2655 SmallVector<Expr*, 4> SelExprs;
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002656 SelExprs.push_back(StringLiteral::Create(*Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002657 BoxingMethod->getSelector().getAsString(),
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002658 StringLiteral::Ascii, false,
2659 argType, SourceLocation()));
2660 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2661 &SelExprs[0], SelExprs.size(),
2662 StartLoc, EndLoc);
2663 MsgExprs.push_back(SelExp);
2664
Patrick Beardeb382ec2012-04-19 00:25:12 +00002665 // User provided sub-expression is the 3rd, and last, argument.
2666 Expr *subExpr = Exp->getSubExpr();
2667 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002668 QualType type = ICE->getType();
2669 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2670 CastKind CK = CK_BitCast;
2671 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2672 CK = CK_IntegralToBoolean;
Patrick Beardeb382ec2012-04-19 00:25:12 +00002673 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002674 }
Patrick Beardeb382ec2012-04-19 00:25:12 +00002675 MsgExprs.push_back(subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002676
2677 SmallVector<QualType, 4> ArgTypes;
2678 ArgTypes.push_back(Context->getObjCIdType());
2679 ArgTypes.push_back(Context->getObjCSelType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002680 for (ObjCMethodDecl::param_iterator PI = BoxingMethod->param_begin(),
2681 E = BoxingMethod->param_end(); PI != E; ++PI)
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002682 ArgTypes.push_back((*PI)->getType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002683
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002684 QualType returnType = Exp->getType();
2685 // Get the type, we will need to reference it in a couple spots.
2686 QualType msgSendType = MsgSendFlavor->getType();
2687
2688 // Create a reference to the objc_msgSend() declaration.
2689 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2690 VK_LValue, SourceLocation());
2691
2692 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002693 Context->getPointerType(Context->VoidTy),
2694 CK_BitCast, DRE);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002695
2696 // Now do the "normal" pointer to function cast.
2697 QualType castType =
Patrick Beardeb382ec2012-04-19 00:25:12 +00002698 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2699 BoxingMethod->isVariadic());
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002700 castType = Context->getPointerType(castType);
2701 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2702 cast);
2703
2704 // Don't forget the parens to enforce the proper binding.
2705 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2706
2707 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002708 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002709 FT->getResultType(), VK_RValue,
2710 EndLoc);
2711 ReplaceStmt(Exp, CE);
2712 return CE;
2713}
2714
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002715Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2716 // synthesize declaration of helper functions needed in this routine.
2717 if (!SelGetUidFunctionDecl)
2718 SynthSelGetUidFunctionDecl();
2719 // use objc_msgSend() for all.
2720 if (!MsgSendFunctionDecl)
2721 SynthMsgSendFunctionDecl();
2722 if (!GetClassFunctionDecl)
2723 SynthGetClassFunctionDecl();
2724
2725 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2726 SourceLocation StartLoc = Exp->getLocStart();
2727 SourceLocation EndLoc = Exp->getLocEnd();
2728
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002729 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002730 QualType IntQT = Context->IntTy;
2731 QualType NSArrayFType =
2732 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002733 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002734 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2735 DeclRefExpr *NSArrayDRE =
2736 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2737 SourceLocation());
2738
2739 SmallVector<Expr*, 16> InitExprs;
2740 unsigned NumElements = Exp->getNumElements();
2741 unsigned UnsignedIntSize =
2742 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2743 Expr *count = IntegerLiteral::Create(*Context,
2744 llvm::APInt(UnsignedIntSize, NumElements),
2745 Context->UnsignedIntTy, SourceLocation());
2746 InitExprs.push_back(count);
2747 for (unsigned i = 0; i < NumElements; i++)
2748 InitExprs.push_back(Exp->getElement(i));
2749 Expr *NSArrayCallExpr =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002750 new (Context) CallExpr(*Context, NSArrayDRE, InitExprs,
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002751 NSArrayFType, VK_LValue, SourceLocation());
2752
2753 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2754 SourceLocation(),
2755 &Context->Idents.get("arr"),
2756 Context->getPointerType(Context->VoidPtrTy), 0,
2757 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00002758 ICIS_NoInit);
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002759 MemberExpr *ArrayLiteralME =
2760 new (Context) MemberExpr(NSArrayCallExpr, false, ARRFD,
2761 SourceLocation(),
2762 ARRFD->getType(), VK_LValue,
2763 OK_Ordinary);
2764 QualType ConstIdT = Context->getObjCIdType().withConst();
2765 CStyleCastExpr * ArrayLiteralObjects =
2766 NoTypeInfoCStyleCastExpr(Context,
2767 Context->getPointerType(ConstIdT),
2768 CK_BitCast,
2769 ArrayLiteralME);
2770
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002771 // Synthesize a call to objc_msgSend().
2772 SmallVector<Expr*, 32> MsgExprs;
2773 SmallVector<Expr*, 4> ClsExprs;
2774 QualType argType = Context->getPointerType(Context->CharTy);
2775 QualType expType = Exp->getType();
2776
2777 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2778 ObjCInterfaceDecl *Class =
2779 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2780
2781 IdentifierInfo *clsName = Class->getIdentifier();
2782 ClsExprs.push_back(StringLiteral::Create(*Context,
2783 clsName->getName(),
2784 StringLiteral::Ascii, false,
2785 argType, SourceLocation()));
2786 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2787 &ClsExprs[0],
2788 ClsExprs.size(),
2789 StartLoc, EndLoc);
2790 MsgExprs.push_back(Cls);
2791
2792 // Create a call to sel_registerName("arrayWithObjects:count:").
2793 // it will be the 2nd argument.
2794 SmallVector<Expr*, 4> SelExprs;
2795 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
2796 SelExprs.push_back(StringLiteral::Create(*Context,
2797 ArrayMethod->getSelector().getAsString(),
2798 StringLiteral::Ascii, false,
2799 argType, SourceLocation()));
2800 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2801 &SelExprs[0], SelExprs.size(),
2802 StartLoc, EndLoc);
2803 MsgExprs.push_back(SelExp);
2804
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002805 // (const id [])objects
2806 MsgExprs.push_back(ArrayLiteralObjects);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002807
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002808 // (NSUInteger)cnt
2809 Expr *cnt = IntegerLiteral::Create(*Context,
2810 llvm::APInt(UnsignedIntSize, NumElements),
2811 Context->UnsignedIntTy, SourceLocation());
2812 MsgExprs.push_back(cnt);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002813
2814
2815 SmallVector<QualType, 4> ArgTypes;
2816 ArgTypes.push_back(Context->getObjCIdType());
2817 ArgTypes.push_back(Context->getObjCSelType());
2818 for (ObjCMethodDecl::param_iterator PI = ArrayMethod->param_begin(),
2819 E = ArrayMethod->param_end(); PI != E; ++PI)
2820 ArgTypes.push_back((*PI)->getType());
2821
2822 QualType returnType = Exp->getType();
2823 // Get the type, we will need to reference it in a couple spots.
2824 QualType msgSendType = MsgSendFlavor->getType();
2825
2826 // Create a reference to the objc_msgSend() declaration.
2827 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2828 VK_LValue, SourceLocation());
2829
2830 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2831 Context->getPointerType(Context->VoidTy),
2832 CK_BitCast, DRE);
2833
2834 // Now do the "normal" pointer to function cast.
2835 QualType castType =
2836 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2837 ArrayMethod->isVariadic());
2838 castType = Context->getPointerType(castType);
2839 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2840 cast);
2841
2842 // Don't forget the parens to enforce the proper binding.
2843 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2844
2845 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002846 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002847 FT->getResultType(), VK_RValue,
2848 EndLoc);
2849 ReplaceStmt(Exp, CE);
2850 return CE;
2851}
2852
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002853Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2854 // synthesize declaration of helper functions needed in this routine.
2855 if (!SelGetUidFunctionDecl)
2856 SynthSelGetUidFunctionDecl();
2857 // use objc_msgSend() for all.
2858 if (!MsgSendFunctionDecl)
2859 SynthMsgSendFunctionDecl();
2860 if (!GetClassFunctionDecl)
2861 SynthGetClassFunctionDecl();
2862
2863 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2864 SourceLocation StartLoc = Exp->getLocStart();
2865 SourceLocation EndLoc = Exp->getLocEnd();
2866
2867 // Build the expression: __NSContainer_literal(int, ...).arr
2868 QualType IntQT = Context->IntTy;
2869 QualType NSDictFType =
2870 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
2871 std::string NSDictFName("__NSContainer_literal");
2872 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2873 DeclRefExpr *NSDictDRE =
2874 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2875 SourceLocation());
2876
2877 SmallVector<Expr*, 16> KeyExprs;
2878 SmallVector<Expr*, 16> ValueExprs;
2879
2880 unsigned NumElements = Exp->getNumElements();
2881 unsigned UnsignedIntSize =
2882 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2883 Expr *count = IntegerLiteral::Create(*Context,
2884 llvm::APInt(UnsignedIntSize, NumElements),
2885 Context->UnsignedIntTy, SourceLocation());
2886 KeyExprs.push_back(count);
2887 ValueExprs.push_back(count);
2888 for (unsigned i = 0; i < NumElements; i++) {
2889 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2890 KeyExprs.push_back(Element.Key);
2891 ValueExprs.push_back(Element.Value);
2892 }
2893
2894 // (const id [])objects
2895 Expr *NSValueCallExpr =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002896 new (Context) CallExpr(*Context, NSDictDRE, ValueExprs,
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002897 NSDictFType, VK_LValue, SourceLocation());
2898
2899 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2900 SourceLocation(),
2901 &Context->Idents.get("arr"),
2902 Context->getPointerType(Context->VoidPtrTy), 0,
2903 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00002904 ICIS_NoInit);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002905 MemberExpr *DictLiteralValueME =
2906 new (Context) MemberExpr(NSValueCallExpr, false, ARRFD,
2907 SourceLocation(),
2908 ARRFD->getType(), VK_LValue,
2909 OK_Ordinary);
2910 QualType ConstIdT = Context->getObjCIdType().withConst();
2911 CStyleCastExpr * DictValueObjects =
2912 NoTypeInfoCStyleCastExpr(Context,
2913 Context->getPointerType(ConstIdT),
2914 CK_BitCast,
2915 DictLiteralValueME);
2916 // (const id <NSCopying> [])keys
2917 Expr *NSKeyCallExpr =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002918 new (Context) CallExpr(*Context, NSDictDRE, KeyExprs,
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002919 NSDictFType, VK_LValue, SourceLocation());
2920
2921 MemberExpr *DictLiteralKeyME =
2922 new (Context) MemberExpr(NSKeyCallExpr, false, ARRFD,
2923 SourceLocation(),
2924 ARRFD->getType(), VK_LValue,
2925 OK_Ordinary);
2926
2927 CStyleCastExpr * DictKeyObjects =
2928 NoTypeInfoCStyleCastExpr(Context,
2929 Context->getPointerType(ConstIdT),
2930 CK_BitCast,
2931 DictLiteralKeyME);
2932
2933
2934
2935 // Synthesize a call to objc_msgSend().
2936 SmallVector<Expr*, 32> MsgExprs;
2937 SmallVector<Expr*, 4> ClsExprs;
2938 QualType argType = Context->getPointerType(Context->CharTy);
2939 QualType expType = Exp->getType();
2940
2941 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2942 ObjCInterfaceDecl *Class =
2943 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2944
2945 IdentifierInfo *clsName = Class->getIdentifier();
2946 ClsExprs.push_back(StringLiteral::Create(*Context,
2947 clsName->getName(),
2948 StringLiteral::Ascii, false,
2949 argType, SourceLocation()));
2950 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2951 &ClsExprs[0],
2952 ClsExprs.size(),
2953 StartLoc, EndLoc);
2954 MsgExprs.push_back(Cls);
2955
2956 // Create a call to sel_registerName("arrayWithObjects:count:").
2957 // it will be the 2nd argument.
2958 SmallVector<Expr*, 4> SelExprs;
2959 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
2960 SelExprs.push_back(StringLiteral::Create(*Context,
2961 DictMethod->getSelector().getAsString(),
2962 StringLiteral::Ascii, false,
2963 argType, SourceLocation()));
2964 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2965 &SelExprs[0], SelExprs.size(),
2966 StartLoc, EndLoc);
2967 MsgExprs.push_back(SelExp);
2968
2969 // (const id [])objects
2970 MsgExprs.push_back(DictValueObjects);
2971
2972 // (const id <NSCopying> [])keys
2973 MsgExprs.push_back(DictKeyObjects);
2974
2975 // (NSUInteger)cnt
2976 Expr *cnt = IntegerLiteral::Create(*Context,
2977 llvm::APInt(UnsignedIntSize, NumElements),
2978 Context->UnsignedIntTy, SourceLocation());
2979 MsgExprs.push_back(cnt);
2980
2981
2982 SmallVector<QualType, 8> ArgTypes;
2983 ArgTypes.push_back(Context->getObjCIdType());
2984 ArgTypes.push_back(Context->getObjCSelType());
2985 for (ObjCMethodDecl::param_iterator PI = DictMethod->param_begin(),
2986 E = DictMethod->param_end(); PI != E; ++PI) {
2987 QualType T = (*PI)->getType();
2988 if (const PointerType* PT = T->getAs<PointerType>()) {
2989 QualType PointeeTy = PT->getPointeeType();
2990 convertToUnqualifiedObjCType(PointeeTy);
2991 T = Context->getPointerType(PointeeTy);
2992 }
2993 ArgTypes.push_back(T);
2994 }
2995
2996 QualType returnType = Exp->getType();
2997 // Get the type, we will need to reference it in a couple spots.
2998 QualType msgSendType = MsgSendFlavor->getType();
2999
3000 // Create a reference to the objc_msgSend() declaration.
3001 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
3002 VK_LValue, SourceLocation());
3003
3004 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
3005 Context->getPointerType(Context->VoidTy),
3006 CK_BitCast, DRE);
3007
3008 // Now do the "normal" pointer to function cast.
3009 QualType castType =
3010 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3011 DictMethod->isVariadic());
3012 castType = Context->getPointerType(castType);
3013 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3014 cast);
3015
3016 // Don't forget the parens to enforce the proper binding.
3017 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3018
3019 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003020 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00003021 FT->getResultType(), VK_RValue,
3022 EndLoc);
3023 ReplaceStmt(Exp, CE);
3024 return CE;
3025}
3026
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003027// struct __rw_objc_super {
3028// struct objc_object *object; struct objc_object *superClass;
3029// };
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003030QualType RewriteModernObjC::getSuperStructType() {
3031 if (!SuperStructDecl) {
3032 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3033 SourceLocation(), SourceLocation(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003034 &Context->Idents.get("__rw_objc_super"));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003035 QualType FieldTypes[2];
3036
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003037 // struct objc_object *object;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003038 FieldTypes[0] = Context->getObjCIdType();
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003039 // struct objc_object *superClass;
3040 FieldTypes[1] = Context->getObjCIdType();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003041
3042 // Create fields
3043 for (unsigned i = 0; i < 2; ++i) {
3044 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
3045 SourceLocation(),
3046 SourceLocation(), 0,
3047 FieldTypes[i], 0,
3048 /*BitWidth=*/0,
3049 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00003050 ICIS_NoInit));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003051 }
3052
3053 SuperStructDecl->completeDefinition();
3054 }
3055 return Context->getTagDeclType(SuperStructDecl);
3056}
3057
3058QualType RewriteModernObjC::getConstantStringStructType() {
3059 if (!ConstantStringDecl) {
3060 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3061 SourceLocation(), SourceLocation(),
3062 &Context->Idents.get("__NSConstantStringImpl"));
3063 QualType FieldTypes[4];
3064
3065 // struct objc_object *receiver;
3066 FieldTypes[0] = Context->getObjCIdType();
3067 // int flags;
3068 FieldTypes[1] = Context->IntTy;
3069 // char *str;
3070 FieldTypes[2] = Context->getPointerType(Context->CharTy);
3071 // long length;
3072 FieldTypes[3] = Context->LongTy;
3073
3074 // Create fields
3075 for (unsigned i = 0; i < 4; ++i) {
3076 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3077 ConstantStringDecl,
3078 SourceLocation(),
3079 SourceLocation(), 0,
3080 FieldTypes[i], 0,
3081 /*BitWidth=*/0,
3082 /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00003083 ICIS_NoInit));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003084 }
3085
3086 ConstantStringDecl->completeDefinition();
3087 }
3088 return Context->getTagDeclType(ConstantStringDecl);
3089}
3090
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003091/// getFunctionSourceLocation - returns start location of a function
3092/// definition. Complication arises when function has declared as
3093/// extern "C" or extern "C" {...}
3094static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3095 FunctionDecl *FD) {
3096 if (FD->isExternC() && !FD->isMain()) {
3097 const DeclContext *DC = FD->getDeclContext();
3098 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3099 // if it is extern "C" {...}, return function decl's own location.
3100 if (!LSD->getRBraceLoc().isValid())
3101 return LSD->getExternLoc();
3102 }
3103 if (FD->getStorageClassAsWritten() != SC_None)
3104 R.RewriteBlockLiteralFunctionDecl(FD);
3105 return FD->getTypeSpecStartLoc();
3106}
3107
Fariborz Jahanian96205962012-11-06 17:30:23 +00003108void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
3109
3110 SourceLocation Location = D->getLocation();
3111
3112 if (Location.isFileID()) {
3113 std::string LineString("#line ");
3114 PresumedLoc PLoc = SM->getPresumedLoc(Location);
3115 LineString += utostr(PLoc.getLine());
3116 LineString += " \"";
NAKAMURA Takumiba529a92012-11-06 22:45:31 +00003117 LineString += Lexer::Stringify(PLoc.getFilename());
Fariborz Jahanian96205962012-11-06 17:30:23 +00003118 if (isa<ObjCMethodDecl>(D))
3119 LineString += "\"";
3120 else LineString += "\"\n";
3121
3122 Location = D->getLocStart();
3123 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3124 if (FD->isExternC() && !FD->isMain()) {
3125 const DeclContext *DC = FD->getDeclContext();
3126 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3127 // if it is extern "C" {...}, return function decl's own location.
3128 if (!LSD->getRBraceLoc().isValid())
3129 Location = LSD->getExternLoc();
3130 }
3131 }
3132 InsertText(Location, LineString);
3133 }
3134}
3135
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003136/// SynthMsgSendStretCallExpr - This routine translates message expression
3137/// into a call to objc_msgSend_stret() entry point. Tricky part is that
3138/// nil check on receiver must be performed before calling objc_msgSend_stret.
3139/// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3140/// msgSendType - function type of objc_msgSend_stret(...)
3141/// returnType - Result type of the method being synthesized.
3142/// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
3143/// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
3144/// starting with receiver.
3145/// Method - Method being rewritten.
3146Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
3147 QualType msgSendType,
3148 QualType returnType,
3149 SmallVectorImpl<QualType> &ArgTypes,
3150 SmallVectorImpl<Expr*> &MsgExprs,
3151 ObjCMethodDecl *Method) {
3152 // Now do the "normal" pointer to function cast.
3153 QualType castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3154 Method ? Method->isVariadic() : false);
3155 castType = Context->getPointerType(castType);
3156
3157 // build type for containing the objc_msgSend_stret object.
3158 static unsigned stretCount=0;
3159 std::string name = "__Stret"; name += utostr(stretCount);
Fariborz Jahanian2ca5af22012-07-25 21:48:36 +00003160 std::string str =
3161 "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
3162 str += "struct "; str += name;
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003163 str += " {\n\t";
3164 str += name;
3165 str += "(id receiver, SEL sel";
3166 for (unsigned i = 2; i < ArgTypes.size(); i++) {
Fariborz Jahanian6734ec42012-06-29 19:55:46 +00003167 std::string ArgName = "arg"; ArgName += utostr(i);
3168 ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3169 str += ", "; str += ArgName;
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003170 }
3171 // could be vararg.
3172 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
Fariborz Jahanian6734ec42012-06-29 19:55:46 +00003173 std::string ArgName = "arg"; ArgName += utostr(i);
3174 MsgExprs[i]->getType().getAsStringInternal(ArgName,
3175 Context->getPrintingPolicy());
3176 str += ", "; str += ArgName;
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003177 }
3178
3179 str += ") {\n";
3180 str += "\t if (receiver == 0)\n";
3181 str += "\t memset((void*)&s, 0, sizeof(s));\n";
3182 str += "\t else\n";
3183 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3184 str += ")(void *)objc_msgSend_stret)(receiver, sel";
3185 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3186 str += ", arg"; str += utostr(i);
3187 }
3188 // could be vararg.
3189 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3190 str += ", arg"; str += utostr(i);
3191 }
3192
3193 str += ");\n";
3194 str += "\t}\n";
3195 str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3196 str += " s;\n";
3197 str += "};\n\n";
Fariborz Jahaniana6e5a6e2012-08-21 18:56:50 +00003198 SourceLocation FunLocStart;
3199 if (CurFunctionDef)
3200 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3201 else {
3202 assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
3203 FunLocStart = CurMethodDef->getLocStart();
3204 }
3205
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003206 InsertText(FunLocStart, str);
3207 ++stretCount;
3208
3209 // AST for __Stretn(receiver, args).s;
3210 IdentifierInfo *ID = &Context->Idents.get(name);
3211 FunctionDecl *FD = FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
3212 SourceLocation(), ID, castType, 0, SC_Extern,
3213 SC_None, false, false);
3214 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, castType, VK_RValue,
3215 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003216 CallExpr *STCE = new (Context) CallExpr(*Context, DRE, MsgExprs,
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003217 castType, VK_LValue, SourceLocation());
3218
3219 FieldDecl *FieldD = FieldDecl::Create(*Context, 0, SourceLocation(),
3220 SourceLocation(),
3221 &Context->Idents.get("s"),
3222 returnType, 0,
3223 /*BitWidth=*/0, /*Mutable=*/true,
3224 ICIS_NoInit);
3225 MemberExpr *ME = new (Context) MemberExpr(STCE, false, FieldD, SourceLocation(),
3226 FieldD->getType(), VK_LValue,
3227 OK_Ordinary);
3228
3229 return ME;
3230}
3231
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003232Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3233 SourceLocation StartLoc,
3234 SourceLocation EndLoc) {
3235 if (!SelGetUidFunctionDecl)
3236 SynthSelGetUidFunctionDecl();
3237 if (!MsgSendFunctionDecl)
3238 SynthMsgSendFunctionDecl();
3239 if (!MsgSendSuperFunctionDecl)
3240 SynthMsgSendSuperFunctionDecl();
3241 if (!MsgSendStretFunctionDecl)
3242 SynthMsgSendStretFunctionDecl();
3243 if (!MsgSendSuperStretFunctionDecl)
3244 SynthMsgSendSuperStretFunctionDecl();
3245 if (!MsgSendFpretFunctionDecl)
3246 SynthMsgSendFpretFunctionDecl();
3247 if (!GetClassFunctionDecl)
3248 SynthGetClassFunctionDecl();
3249 if (!GetSuperClassFunctionDecl)
3250 SynthGetSuperClassFunctionDecl();
3251 if (!GetMetaClassFunctionDecl)
3252 SynthGetMetaClassFunctionDecl();
3253
3254 // default to objc_msgSend().
3255 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3256 // May need to use objc_msgSend_stret() as well.
3257 FunctionDecl *MsgSendStretFlavor = 0;
3258 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
3259 QualType resultType = mDecl->getResultType();
3260 if (resultType->isRecordType())
3261 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3262 else if (resultType->isRealFloatingType())
3263 MsgSendFlavor = MsgSendFpretFunctionDecl;
3264 }
3265
3266 // Synthesize a call to objc_msgSend().
3267 SmallVector<Expr*, 8> MsgExprs;
3268 switch (Exp->getReceiverKind()) {
3269 case ObjCMessageExpr::SuperClass: {
3270 MsgSendFlavor = MsgSendSuperFunctionDecl;
3271 if (MsgSendStretFlavor)
3272 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3273 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3274
3275 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3276
3277 SmallVector<Expr*, 4> InitExprs;
3278
3279 // set the receiver to self, the first argument to all methods.
3280 InitExprs.push_back(
3281 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3282 CK_BitCast,
3283 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003284 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003285 Context->getObjCIdType(),
3286 VK_RValue,
3287 SourceLocation()))
3288 ); // set the 'receiver'.
3289
3290 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3291 SmallVector<Expr*, 8> ClsExprs;
3292 QualType argType = Context->getPointerType(Context->CharTy);
3293 ClsExprs.push_back(StringLiteral::Create(*Context,
3294 ClassDecl->getIdentifier()->getName(),
3295 StringLiteral::Ascii, false,
3296 argType, SourceLocation()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003297 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003298 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3299 &ClsExprs[0],
3300 ClsExprs.size(),
3301 StartLoc,
3302 EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003303 ClsExprs.clear();
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003304 ClsExprs.push_back(Cls);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003305 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3306 &ClsExprs[0], ClsExprs.size(),
3307 StartLoc, EndLoc);
3308
3309 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3310 // To turn off a warning, type-cast to 'id'
3311 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3312 NoTypeInfoCStyleCastExpr(Context,
3313 Context->getObjCIdType(),
3314 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003315 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003316 QualType superType = getSuperStructType();
3317 Expr *SuperRep;
3318
3319 if (LangOpts.MicrosoftExt) {
3320 SynthSuperContructorFunctionDecl();
3321 // Simulate a contructor call...
3322 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003323 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003324 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003325 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003326 superType, VK_LValue,
3327 SourceLocation());
3328 // The code for super is a little tricky to prevent collision with
3329 // the structure definition in the header. The rewriter has it's own
3330 // internal definition (__rw_objc_super) that is uses. This is why
3331 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003332 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003333 //
3334 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3335 Context->getPointerType(SuperRep->getType()),
3336 VK_RValue, OK_Ordinary,
3337 SourceLocation());
3338 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3339 Context->getPointerType(superType),
3340 CK_BitCast, SuperRep);
3341 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003342 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003343 InitListExpr *ILE =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003344 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003345 SourceLocation());
3346 TypeSourceInfo *superTInfo
3347 = Context->getTrivialTypeSourceInfo(superType);
3348 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3349 superType, VK_LValue,
3350 ILE, false);
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003351 // struct __rw_objc_super *
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003352 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3353 Context->getPointerType(SuperRep->getType()),
3354 VK_RValue, OK_Ordinary,
3355 SourceLocation());
3356 }
3357 MsgExprs.push_back(SuperRep);
3358 break;
3359 }
3360
3361 case ObjCMessageExpr::Class: {
3362 SmallVector<Expr*, 8> ClsExprs;
3363 QualType argType = Context->getPointerType(Context->CharTy);
3364 ObjCInterfaceDecl *Class
3365 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3366 IdentifierInfo *clsName = Class->getIdentifier();
3367 ClsExprs.push_back(StringLiteral::Create(*Context,
3368 clsName->getName(),
3369 StringLiteral::Ascii, false,
3370 argType, SourceLocation()));
3371 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3372 &ClsExprs[0],
3373 ClsExprs.size(),
3374 StartLoc, EndLoc);
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003375 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3376 Context->getObjCIdType(),
3377 CK_BitCast, Cls);
3378 MsgExprs.push_back(ArgExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003379 break;
3380 }
3381
3382 case ObjCMessageExpr::SuperInstance:{
3383 MsgSendFlavor = MsgSendSuperFunctionDecl;
3384 if (MsgSendStretFlavor)
3385 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3386 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3387 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3388 SmallVector<Expr*, 4> InitExprs;
3389
3390 InitExprs.push_back(
3391 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3392 CK_BitCast,
3393 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003394 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003395 Context->getObjCIdType(),
3396 VK_RValue, SourceLocation()))
3397 ); // set the 'receiver'.
3398
3399 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3400 SmallVector<Expr*, 8> ClsExprs;
3401 QualType argType = Context->getPointerType(Context->CharTy);
3402 ClsExprs.push_back(StringLiteral::Create(*Context,
3403 ClassDecl->getIdentifier()->getName(),
3404 StringLiteral::Ascii, false, argType,
3405 SourceLocation()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003406 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003407 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3408 &ClsExprs[0],
3409 ClsExprs.size(),
3410 StartLoc, EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003411 ClsExprs.clear();
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003412 ClsExprs.push_back(Cls);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003413 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3414 &ClsExprs[0], ClsExprs.size(),
3415 StartLoc, EndLoc);
3416
3417 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3418 // To turn off a warning, type-cast to 'id'
3419 InitExprs.push_back(
3420 // set 'super class', using class_getSuperclass().
3421 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3422 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003423 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003424 QualType superType = getSuperStructType();
3425 Expr *SuperRep;
3426
3427 if (LangOpts.MicrosoftExt) {
3428 SynthSuperContructorFunctionDecl();
3429 // Simulate a contructor call...
3430 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003431 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003432 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003433 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003434 superType, VK_LValue, SourceLocation());
3435 // The code for super is a little tricky to prevent collision with
3436 // the structure definition in the header. The rewriter has it's own
3437 // internal definition (__rw_objc_super) that is uses. This is why
3438 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003439 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003440 //
3441 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3442 Context->getPointerType(SuperRep->getType()),
3443 VK_RValue, OK_Ordinary,
3444 SourceLocation());
3445 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3446 Context->getPointerType(superType),
3447 CK_BitCast, SuperRep);
3448 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003449 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003450 InitListExpr *ILE =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003451 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003452 SourceLocation());
3453 TypeSourceInfo *superTInfo
3454 = Context->getTrivialTypeSourceInfo(superType);
3455 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3456 superType, VK_RValue, ILE,
3457 false);
3458 }
3459 MsgExprs.push_back(SuperRep);
3460 break;
3461 }
3462
3463 case ObjCMessageExpr::Instance: {
3464 // Remove all type-casts because it may contain objc-style types; e.g.
3465 // Foo<Proto> *.
3466 Expr *recExpr = Exp->getInstanceReceiver();
3467 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3468 recExpr = CE->getSubExpr();
3469 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3470 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3471 ? CK_BlockPointerToObjCPointerCast
3472 : CK_CPointerToObjCPointerCast;
3473
3474 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3475 CK, recExpr);
3476 MsgExprs.push_back(recExpr);
3477 break;
3478 }
3479 }
3480
3481 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3482 SmallVector<Expr*, 8> SelExprs;
3483 QualType argType = Context->getPointerType(Context->CharTy);
3484 SelExprs.push_back(StringLiteral::Create(*Context,
3485 Exp->getSelector().getAsString(),
3486 StringLiteral::Ascii, false,
3487 argType, SourceLocation()));
3488 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3489 &SelExprs[0], SelExprs.size(),
3490 StartLoc,
3491 EndLoc);
3492 MsgExprs.push_back(SelExp);
3493
3494 // Now push any user supplied arguments.
3495 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3496 Expr *userExpr = Exp->getArg(i);
3497 // Make all implicit casts explicit...ICE comes in handy:-)
3498 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3499 // Reuse the ICE type, it is exactly what the doctor ordered.
3500 QualType type = ICE->getType();
3501 if (needToScanForQualifiers(type))
3502 type = Context->getObjCIdType();
3503 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3504 (void)convertBlockPointerToFunctionPointer(type);
3505 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3506 CastKind CK;
3507 if (SubExpr->getType()->isIntegralType(*Context) &&
3508 type->isBooleanType()) {
3509 CK = CK_IntegralToBoolean;
3510 } else if (type->isObjCObjectPointerType()) {
3511 if (SubExpr->getType()->isBlockPointerType()) {
3512 CK = CK_BlockPointerToObjCPointerCast;
3513 } else if (SubExpr->getType()->isPointerType()) {
3514 CK = CK_CPointerToObjCPointerCast;
3515 } else {
3516 CK = CK_BitCast;
3517 }
3518 } else {
3519 CK = CK_BitCast;
3520 }
3521
3522 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3523 }
3524 // Make id<P...> cast into an 'id' cast.
3525 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3526 if (CE->getType()->isObjCQualifiedIdType()) {
3527 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3528 userExpr = CE->getSubExpr();
3529 CastKind CK;
3530 if (userExpr->getType()->isIntegralType(*Context)) {
3531 CK = CK_IntegralToPointer;
3532 } else if (userExpr->getType()->isBlockPointerType()) {
3533 CK = CK_BlockPointerToObjCPointerCast;
3534 } else if (userExpr->getType()->isPointerType()) {
3535 CK = CK_CPointerToObjCPointerCast;
3536 } else {
3537 CK = CK_BitCast;
3538 }
3539 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3540 CK, userExpr);
3541 }
3542 }
3543 MsgExprs.push_back(userExpr);
3544 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3545 // out the argument in the original expression (since we aren't deleting
3546 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3547 //Exp->setArg(i, 0);
3548 }
3549 // Generate the funky cast.
3550 CastExpr *cast;
3551 SmallVector<QualType, 8> ArgTypes;
3552 QualType returnType;
3553
3554 // Push 'id' and 'SEL', the 2 implicit arguments.
3555 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3556 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3557 else
3558 ArgTypes.push_back(Context->getObjCIdType());
3559 ArgTypes.push_back(Context->getObjCSelType());
3560 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3561 // Push any user argument types.
3562 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3563 E = OMD->param_end(); PI != E; ++PI) {
3564 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
3565 ? Context->getObjCIdType()
3566 : (*PI)->getType();
3567 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3568 (void)convertBlockPointerToFunctionPointer(t);
3569 ArgTypes.push_back(t);
3570 }
3571 returnType = Exp->getType();
3572 convertToUnqualifiedObjCType(returnType);
3573 (void)convertBlockPointerToFunctionPointer(returnType);
3574 } else {
3575 returnType = Context->getObjCIdType();
3576 }
3577 // Get the type, we will need to reference it in a couple spots.
3578 QualType msgSendType = MsgSendFlavor->getType();
3579
3580 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003581 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003582 VK_LValue, SourceLocation());
3583
3584 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3585 // If we don't do this cast, we get the following bizarre warning/note:
3586 // xx.m:13: warning: function called through a non-compatible type
3587 // xx.m:13: note: if this code is reached, the program will abort
3588 cast = NoTypeInfoCStyleCastExpr(Context,
3589 Context->getPointerType(Context->VoidTy),
3590 CK_BitCast, DRE);
3591
3592 // Now do the "normal" pointer to function cast.
3593 QualType castType =
3594 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3595 // If we don't have a method decl, force a variadic cast.
3596 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
3597 castType = Context->getPointerType(castType);
3598 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3599 cast);
3600
3601 // Don't forget the parens to enforce the proper binding.
3602 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3603
3604 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003605 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
3606 FT->getResultType(), VK_RValue, EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003607 Stmt *ReplacingStmt = CE;
3608 if (MsgSendStretFlavor) {
3609 // We have the method which returns a struct/union. Must also generate
3610 // call to objc_msgSend_stret and hang both varieties on a conditional
3611 // expression which dictate which one to envoke depending on size of
3612 // method's return type.
3613
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003614 Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3615 msgSendType, returnType,
3616 ArgTypes, MsgExprs,
3617 Exp->getMethodDecl());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003618
3619 // Build sizeof(returnType)
3620 UnaryExprOrTypeTraitExpr *sizeofExpr =
3621 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3622 Context->getTrivialTypeSourceInfo(returnType),
3623 Context->getSizeType(), SourceLocation(),
3624 SourceLocation());
3625 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3626 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3627 // For X86 it is more complicated and some kind of target specific routine
3628 // is needed to decide what to do.
3629 unsigned IntSize =
3630 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
3631 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3632 llvm::APInt(IntSize, 8),
3633 Context->IntTy,
3634 SourceLocation());
3635 BinaryOperator *lessThanExpr =
3636 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
Lang Hamesbe9af122012-10-02 04:45:10 +00003637 VK_RValue, OK_Ordinary, SourceLocation(),
3638 false);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003639 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3640 ConditionalOperator *CondExpr =
3641 new (Context) ConditionalOperator(lessThanExpr,
3642 SourceLocation(), CE,
3643 SourceLocation(), STCE,
3644 returnType, VK_RValue, OK_Ordinary);
3645 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3646 CondExpr);
3647 }
3648 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3649 return ReplacingStmt;
3650}
3651
3652Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3653 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3654 Exp->getLocEnd());
3655
3656 // Now do the actual rewrite.
3657 ReplaceStmt(Exp, ReplacingStmt);
3658
3659 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3660 return ReplacingStmt;
3661}
3662
3663// typedef struct objc_object Protocol;
3664QualType RewriteModernObjC::getProtocolType() {
3665 if (!ProtocolTypeDecl) {
3666 TypeSourceInfo *TInfo
3667 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3668 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3669 SourceLocation(), SourceLocation(),
3670 &Context->Idents.get("Protocol"),
3671 TInfo);
3672 }
3673 return Context->getTypeDeclType(ProtocolTypeDecl);
3674}
3675
3676/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3677/// a synthesized/forward data reference (to the protocol's metadata).
3678/// The forward references (and metadata) are generated in
3679/// RewriteModernObjC::HandleTranslationUnit().
3680Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00003681 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3682 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003683 IdentifierInfo *ID = &Context->Idents.get(Name);
3684 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3685 SourceLocation(), ID, getProtocolType(), 0,
3686 SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00003687 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3688 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003689 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3690 Context->getPointerType(DRE->getType()),
3691 VK_RValue, OK_Ordinary, SourceLocation());
3692 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3693 CK_BitCast,
3694 DerefExpr);
3695 ReplaceStmt(Exp, castExpr);
3696 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3697 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3698 return castExpr;
3699
3700}
3701
3702bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3703 const char *endBuf) {
3704 while (startBuf < endBuf) {
3705 if (*startBuf == '#') {
3706 // Skip whitespace.
3707 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3708 ;
3709 if (!strncmp(startBuf, "if", strlen("if")) ||
3710 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3711 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3712 !strncmp(startBuf, "define", strlen("define")) ||
3713 !strncmp(startBuf, "undef", strlen("undef")) ||
3714 !strncmp(startBuf, "else", strlen("else")) ||
3715 !strncmp(startBuf, "elif", strlen("elif")) ||
3716 !strncmp(startBuf, "endif", strlen("endif")) ||
3717 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3718 !strncmp(startBuf, "include", strlen("include")) ||
3719 !strncmp(startBuf, "import", strlen("import")) ||
3720 !strncmp(startBuf, "include_next", strlen("include_next")))
3721 return true;
3722 }
3723 startBuf++;
3724 }
3725 return false;
3726}
3727
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003728/// IsTagDefinedInsideClass - This routine checks that a named tagged type
3729/// is defined inside an objective-c class. If so, it returns true.
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00003730bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003731 TagDecl *Tag,
3732 bool &IsNamedDefinition) {
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003733 if (!IDecl)
3734 return false;
3735 SourceLocation TagLocation;
3736 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3737 RD = RD->getDefinition();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003738 if (!RD || !RD->getDeclName().getAsIdentifierInfo())
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003739 return false;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003740 IsNamedDefinition = true;
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003741 TagLocation = RD->getLocation();
3742 return Context->getSourceManager().isBeforeInTranslationUnit(
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003743 IDecl->getLocation(), TagLocation);
3744 }
3745 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3746 if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3747 return false;
3748 IsNamedDefinition = true;
3749 TagLocation = ED->getLocation();
3750 return Context->getSourceManager().isBeforeInTranslationUnit(
3751 IDecl->getLocation(), TagLocation);
3752
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003753 }
3754 return false;
3755}
3756
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003757/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003758/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003759bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3760 std::string &Result) {
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00003761 if (isa<TypedefType>(Type)) {
3762 Result += "\t";
3763 return false;
3764 }
3765
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003766 if (Type->isArrayType()) {
3767 QualType ElemTy = Context->getBaseElementType(Type);
3768 return RewriteObjCFieldDeclType(ElemTy, Result);
3769 }
3770 else if (Type->isRecordType()) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003771 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3772 if (RD->isCompleteDefinition()) {
3773 if (RD->isStruct())
3774 Result += "\n\tstruct ";
3775 else if (RD->isUnion())
3776 Result += "\n\tunion ";
3777 else
3778 assert(false && "class not allowed as an ivar type");
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003779
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003780 Result += RD->getName();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003781 if (GlobalDefinedTags.count(RD)) {
3782 // struct/union is defined globally, use it.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003783 Result += " ";
3784 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003785 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003786 Result += " {\n";
3787 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003788 e = RD->field_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00003789 FieldDecl *FD = *i;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003790 RewriteObjCFieldDecl(FD, Result);
3791 }
3792 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003793 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003794 }
3795 }
3796 else if (Type->isEnumeralType()) {
3797 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3798 if (ED->isCompleteDefinition()) {
3799 Result += "\n\tenum ";
3800 Result += ED->getName();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003801 if (GlobalDefinedTags.count(ED)) {
3802 // Enum is globall defined, use it.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003803 Result += " ";
3804 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003805 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003806
3807 Result += " {\n";
3808 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3809 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3810 Result += "\t"; Result += EC->getName(); Result += " = ";
3811 llvm::APSInt Val = EC->getInitVal();
3812 Result += Val.toString(10);
3813 Result += ",\n";
3814 }
3815 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003816 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003817 }
3818 }
3819
3820 Result += "\t";
3821 convertObjCTypeToCStyleType(Type);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003822 return false;
3823}
3824
3825
3826/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3827/// It handles elaborated types, as well as enum types in the process.
3828void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3829 std::string &Result) {
3830 QualType Type = fieldDecl->getType();
3831 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003832
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003833 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3834 if (!EleboratedType)
3835 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003836 Result += Name;
3837 if (fieldDecl->isBitField()) {
3838 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3839 }
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003840 else if (EleboratedType && Type->isArrayType()) {
3841 CanQualType CType = Context->getCanonicalType(Type);
3842 while (isa<ArrayType>(CType)) {
3843 if (const ConstantArrayType *CAT = Context->getAsConstantArrayType(CType)) {
3844 Result += "[";
3845 llvm::APInt Dim = CAT->getSize();
3846 Result += utostr(Dim.getZExtValue());
3847 Result += "]";
3848 }
3849 CType = CType->getAs<ArrayType>()->getElementType();
3850 }
3851 }
3852
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003853 Result += ";\n";
3854}
3855
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003856/// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3857/// named aggregate types into the input buffer.
3858void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3859 std::string &Result) {
3860 QualType Type = fieldDecl->getType();
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00003861 if (isa<TypedefType>(Type))
3862 return;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003863 if (Type->isArrayType())
3864 Type = Context->getBaseElementType(Type);
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00003865 ObjCContainerDecl *IDecl =
3866 dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003867
3868 TagDecl *TD = 0;
3869 if (Type->isRecordType()) {
3870 TD = Type->getAs<RecordType>()->getDecl();
3871 }
3872 else if (Type->isEnumeralType()) {
3873 TD = Type->getAs<EnumType>()->getDecl();
3874 }
3875
3876 if (TD) {
3877 if (GlobalDefinedTags.count(TD))
3878 return;
3879
3880 bool IsNamedDefinition = false;
3881 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3882 RewriteObjCFieldDeclType(Type, Result);
3883 Result += ";";
3884 }
3885 if (IsNamedDefinition)
3886 GlobalDefinedTags.insert(TD);
3887 }
3888
3889}
3890
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003891/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3892/// an objective-c class with ivars.
3893void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3894 std::string &Result) {
3895 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3896 assert(CDecl->getName() != "" &&
3897 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003898 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003899 SmallVector<ObjCIvarDecl *, 8> IVars;
3900 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003901 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003902 IVars.push_back(IVD);
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003903
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003904 SourceLocation LocStart = CDecl->getLocStart();
3905 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003906
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003907 const char *startBuf = SM->getCharacterData(LocStart);
3908 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003909
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003910 // If no ivars and no root or if its root, directly or indirectly,
3911 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003912 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003913 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3914 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3915 ReplaceText(LocStart, endBuf-startBuf, Result);
3916 return;
3917 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003918
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003919 // Insert named struct/union definitions inside class to
3920 // outer scope. This follows semantics of locally defined
3921 // struct/unions in objective-c classes.
3922 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3923 RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
3924
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003925 Result += "\nstruct ";
3926 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003927 Result += "_IMPL {\n";
3928
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003929 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003930 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3931 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3932 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003933 }
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003934
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003935 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3936 RewriteObjCFieldDecl(IVars[i], Result);
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00003937
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003938 Result += "};\n";
3939 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3940 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003941 // Mark this struct as having been generated.
3942 if (!ObjCSynthesizedStructs.insert(CDecl))
3943 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003944}
3945
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003946/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3947/// have been referenced in an ivar access expression.
3948void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3949 std::string &Result) {
3950 // write out ivar offset symbols which have been referenced in an ivar
3951 // access expression.
3952 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3953 if (Ivars.empty())
3954 return;
3955 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
3956 e = Ivars.end(); i != e; i++) {
3957 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003958 Result += "\n";
3959 if (LangOpts.MicrosoftExt)
3960 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003961 Result += "extern \"C\" ";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003962 if (LangOpts.MicrosoftExt &&
3963 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003964 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
3965 Result += "__declspec(dllimport) ";
3966
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00003967 Result += "unsigned long ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003968 WriteInternalIvarName(CDecl, IvarDecl, Result);
3969 Result += ";";
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003970 }
3971}
3972
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003973//===----------------------------------------------------------------------===//
3974// Meta Data Emission
3975//===----------------------------------------------------------------------===//
3976
3977
3978/// RewriteImplementations - This routine rewrites all method implementations
3979/// and emits meta-data.
3980
3981void RewriteModernObjC::RewriteImplementations() {
3982 int ClsDefCount = ClassImplementation.size();
3983 int CatDefCount = CategoryImplementation.size();
3984
3985 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003986 for (int i = 0; i < ClsDefCount; i++) {
3987 ObjCImplementationDecl *OIMP = ClassImplementation[i];
3988 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
3989 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00003990 assert(false &&
3991 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003992 RewriteImplementationDecl(OIMP);
3993 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003994
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003995 for (int i = 0; i < CatDefCount; i++) {
3996 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
3997 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
3998 if (CDecl->isImplicitInterfaceDecl())
3999 assert(false &&
4000 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00004001 RewriteImplementationDecl(CIMP);
4002 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004003}
4004
4005void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
4006 const std::string &Name,
4007 ValueDecl *VD, bool def) {
4008 assert(BlockByRefDeclNo.count(VD) &&
4009 "RewriteByRefString: ByRef decl missing");
4010 if (def)
4011 ResultStr += "struct ";
4012 ResultStr += "__Block_byref_" + Name +
4013 "_" + utostr(BlockByRefDeclNo[VD]) ;
4014}
4015
4016static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4017 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4018 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4019 return false;
4020}
4021
4022std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4023 StringRef funcName,
4024 std::string Tag) {
4025 const FunctionType *AFT = CE->getFunctionType();
4026 QualType RT = AFT->getResultType();
4027 std::string StructRef = "struct " + Tag;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00004028 SourceLocation BlockLoc = CE->getExprLoc();
4029 std::string S;
4030 ConvertSourceLocationToLineDirective(BlockLoc, S);
4031
4032 S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
4033 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004034
4035 BlockDecl *BD = CE->getBlockDecl();
4036
4037 if (isa<FunctionNoProtoType>(AFT)) {
4038 // No user-supplied arguments. Still need to pass in a pointer to the
4039 // block (to reference imported block decl refs).
4040 S += "(" + StructRef + " *__cself)";
4041 } else if (BD->param_empty()) {
4042 S += "(" + StructRef + " *__cself)";
4043 } else {
4044 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4045 assert(FT && "SynthesizeBlockFunc: No function proto");
4046 S += '(';
4047 // first add the implicit argument.
4048 S += StructRef + " *__cself, ";
4049 std::string ParamStr;
4050 for (BlockDecl::param_iterator AI = BD->param_begin(),
4051 E = BD->param_end(); AI != E; ++AI) {
4052 if (AI != BD->param_begin()) S += ", ";
4053 ParamStr = (*AI)->getNameAsString();
4054 QualType QT = (*AI)->getType();
Fariborz Jahanian2610f902012-03-27 16:42:20 +00004055 (void)convertBlockPointerToFunctionPointer(QT);
4056 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004057 S += ParamStr;
4058 }
4059 if (FT->isVariadic()) {
4060 if (!BD->param_empty()) S += ", ";
4061 S += "...";
4062 }
4063 S += ')';
4064 }
4065 S += " {\n";
4066
4067 // Create local declarations to avoid rewriting all closure decl ref exprs.
4068 // First, emit a declaration for all "by ref" decls.
4069 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4070 E = BlockByRefDecls.end(); I != E; ++I) {
4071 S += " ";
4072 std::string Name = (*I)->getNameAsString();
4073 std::string TypeString;
4074 RewriteByRefString(TypeString, Name, (*I));
4075 TypeString += " *";
4076 Name = TypeString + Name;
4077 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4078 }
4079 // Next, emit a declaration for all "by copy" declarations.
4080 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4081 E = BlockByCopyDecls.end(); I != E; ++I) {
4082 S += " ";
4083 // Handle nested closure invocation. For example:
4084 //
4085 // void (^myImportedClosure)(void);
4086 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
4087 //
4088 // void (^anotherClosure)(void);
4089 // anotherClosure = ^(void) {
4090 // myImportedClosure(); // import and invoke the closure
4091 // };
4092 //
4093 if (isTopLevelBlockPointerType((*I)->getType())) {
4094 RewriteBlockPointerTypeVariable(S, (*I));
4095 S += " = (";
4096 RewriteBlockPointerType(S, (*I)->getType());
4097 S += ")";
4098 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4099 }
4100 else {
4101 std::string Name = (*I)->getNameAsString();
4102 QualType QT = (*I)->getType();
4103 if (HasLocalVariableExternalStorage(*I))
4104 QT = Context->getPointerType(QT);
4105 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
4106 S += Name + " = __cself->" +
4107 (*I)->getNameAsString() + "; // bound by copy\n";
4108 }
4109 }
4110 std::string RewrittenStr = RewrittenBlockExprs[CE];
4111 const char *cstr = RewrittenStr.c_str();
4112 while (*cstr++ != '{') ;
4113 S += cstr;
4114 S += "\n";
4115 return S;
4116}
4117
4118std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4119 StringRef funcName,
4120 std::string Tag) {
4121 std::string StructRef = "struct " + Tag;
4122 std::string S = "static void __";
4123
4124 S += funcName;
4125 S += "_block_copy_" + utostr(i);
4126 S += "(" + StructRef;
4127 S += "*dst, " + StructRef;
4128 S += "*src) {";
4129 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4130 E = ImportedBlockDecls.end(); I != E; ++I) {
4131 ValueDecl *VD = (*I);
4132 S += "_Block_object_assign((void*)&dst->";
4133 S += (*I)->getNameAsString();
4134 S += ", (void*)src->";
4135 S += (*I)->getNameAsString();
4136 if (BlockByRefDeclsPtrSet.count((*I)))
4137 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4138 else if (VD->getType()->isBlockPointerType())
4139 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4140 else
4141 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4142 }
4143 S += "}\n";
4144
4145 S += "\nstatic void __";
4146 S += funcName;
4147 S += "_block_dispose_" + utostr(i);
4148 S += "(" + StructRef;
4149 S += "*src) {";
4150 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4151 E = ImportedBlockDecls.end(); I != E; ++I) {
4152 ValueDecl *VD = (*I);
4153 S += "_Block_object_dispose((void*)src->";
4154 S += (*I)->getNameAsString();
4155 if (BlockByRefDeclsPtrSet.count((*I)))
4156 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4157 else if (VD->getType()->isBlockPointerType())
4158 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4159 else
4160 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4161 }
4162 S += "}\n";
4163 return S;
4164}
4165
4166std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4167 std::string Desc) {
4168 std::string S = "\nstruct " + Tag;
4169 std::string Constructor = " " + Tag;
4170
4171 S += " {\n struct __block_impl impl;\n";
4172 S += " struct " + Desc;
4173 S += "* Desc;\n";
4174
4175 Constructor += "(void *fp, "; // Invoke function pointer.
4176 Constructor += "struct " + Desc; // Descriptor pointer.
4177 Constructor += " *desc";
4178
4179 if (BlockDeclRefs.size()) {
4180 // Output all "by copy" declarations.
4181 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4182 E = BlockByCopyDecls.end(); I != E; ++I) {
4183 S += " ";
4184 std::string FieldName = (*I)->getNameAsString();
4185 std::string ArgName = "_" + FieldName;
4186 // Handle nested closure invocation. For example:
4187 //
4188 // void (^myImportedBlock)(void);
4189 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
4190 //
4191 // void (^anotherBlock)(void);
4192 // anotherBlock = ^(void) {
4193 // myImportedBlock(); // import and invoke the closure
4194 // };
4195 //
4196 if (isTopLevelBlockPointerType((*I)->getType())) {
4197 S += "struct __block_impl *";
4198 Constructor += ", void *" + ArgName;
4199 } else {
4200 QualType QT = (*I)->getType();
4201 if (HasLocalVariableExternalStorage(*I))
4202 QT = Context->getPointerType(QT);
4203 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4204 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4205 Constructor += ", " + ArgName;
4206 }
4207 S += FieldName + ";\n";
4208 }
4209 // Output all "by ref" declarations.
4210 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4211 E = BlockByRefDecls.end(); I != E; ++I) {
4212 S += " ";
4213 std::string FieldName = (*I)->getNameAsString();
4214 std::string ArgName = "_" + FieldName;
4215 {
4216 std::string TypeString;
4217 RewriteByRefString(TypeString, FieldName, (*I));
4218 TypeString += " *";
4219 FieldName = TypeString + FieldName;
4220 ArgName = TypeString + ArgName;
4221 Constructor += ", " + ArgName;
4222 }
4223 S += FieldName + "; // by ref\n";
4224 }
4225 // Finish writing the constructor.
4226 Constructor += ", int flags=0)";
4227 // Initialize all "by copy" arguments.
4228 bool firsTime = true;
4229 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4230 E = BlockByCopyDecls.end(); I != E; ++I) {
4231 std::string Name = (*I)->getNameAsString();
4232 if (firsTime) {
4233 Constructor += " : ";
4234 firsTime = false;
4235 }
4236 else
4237 Constructor += ", ";
4238 if (isTopLevelBlockPointerType((*I)->getType()))
4239 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4240 else
4241 Constructor += Name + "(_" + Name + ")";
4242 }
4243 // Initialize all "by ref" arguments.
4244 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4245 E = BlockByRefDecls.end(); I != E; ++I) {
4246 std::string Name = (*I)->getNameAsString();
4247 if (firsTime) {
4248 Constructor += " : ";
4249 firsTime = false;
4250 }
4251 else
4252 Constructor += ", ";
4253 Constructor += Name + "(_" + Name + "->__forwarding)";
4254 }
4255
4256 Constructor += " {\n";
4257 if (GlobalVarDecl)
4258 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4259 else
4260 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4261 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4262
4263 Constructor += " Desc = desc;\n";
4264 } else {
4265 // Finish writing the constructor.
4266 Constructor += ", int flags=0) {\n";
4267 if (GlobalVarDecl)
4268 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4269 else
4270 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4271 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4272 Constructor += " Desc = desc;\n";
4273 }
4274 Constructor += " ";
4275 Constructor += "}\n";
4276 S += Constructor;
4277 S += "};\n";
4278 return S;
4279}
4280
4281std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4282 std::string ImplTag, int i,
4283 StringRef FunName,
4284 unsigned hasCopy) {
4285 std::string S = "\nstatic struct " + DescTag;
4286
Fariborz Jahanian8b08adb2012-05-03 21:44:12 +00004287 S += " {\n size_t reserved;\n";
4288 S += " size_t Block_size;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004289 if (hasCopy) {
4290 S += " void (*copy)(struct ";
4291 S += ImplTag; S += "*, struct ";
4292 S += ImplTag; S += "*);\n";
4293
4294 S += " void (*dispose)(struct ";
4295 S += ImplTag; S += "*);\n";
4296 }
4297 S += "} ";
4298
4299 S += DescTag + "_DATA = { 0, sizeof(struct ";
4300 S += ImplTag + ")";
4301 if (hasCopy) {
4302 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4303 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4304 }
4305 S += "};\n";
4306 return S;
4307}
4308
4309void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4310 StringRef FunName) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004311 bool RewriteSC = (GlobalVarDecl &&
4312 !Blocks.empty() &&
4313 GlobalVarDecl->getStorageClass() == SC_Static &&
4314 GlobalVarDecl->getType().getCVRQualifiers());
4315 if (RewriteSC) {
4316 std::string SC(" void __");
4317 SC += GlobalVarDecl->getNameAsString();
4318 SC += "() {}";
4319 InsertText(FunLocStart, SC);
4320 }
4321
4322 // Insert closures that were part of the function.
4323 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4324 CollectBlockDeclRefInfo(Blocks[i]);
4325 // Need to copy-in the inner copied-in variables not actually used in this
4326 // block.
4327 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00004328 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004329 ValueDecl *VD = Exp->getDecl();
4330 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00004331 if (!VD->hasAttr<BlocksAttr>()) {
4332 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4333 BlockByCopyDeclsPtrSet.insert(VD);
4334 BlockByCopyDecls.push_back(VD);
4335 }
4336 continue;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004337 }
John McCallf4b88a42012-03-10 09:33:50 +00004338
4339 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004340 BlockByRefDeclsPtrSet.insert(VD);
4341 BlockByRefDecls.push_back(VD);
4342 }
John McCallf4b88a42012-03-10 09:33:50 +00004343
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004344 // imported objects in the inner blocks not used in the outer
4345 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00004346 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004347 VD->getType()->isBlockPointerType())
4348 ImportedBlockDecls.insert(VD);
4349 }
4350
4351 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4352 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4353
4354 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4355
4356 InsertText(FunLocStart, CI);
4357
4358 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4359
4360 InsertText(FunLocStart, CF);
4361
4362 if (ImportedBlockDecls.size()) {
4363 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4364 InsertText(FunLocStart, HF);
4365 }
4366 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4367 ImportedBlockDecls.size() > 0);
4368 InsertText(FunLocStart, BD);
4369
4370 BlockDeclRefs.clear();
4371 BlockByRefDecls.clear();
4372 BlockByRefDeclsPtrSet.clear();
4373 BlockByCopyDecls.clear();
4374 BlockByCopyDeclsPtrSet.clear();
4375 ImportedBlockDecls.clear();
4376 }
4377 if (RewriteSC) {
4378 // Must insert any 'const/volatile/static here. Since it has been
4379 // removed as result of rewriting of block literals.
4380 std::string SC;
4381 if (GlobalVarDecl->getStorageClass() == SC_Static)
4382 SC = "static ";
4383 if (GlobalVarDecl->getType().isConstQualified())
4384 SC += "const ";
4385 if (GlobalVarDecl->getType().isVolatileQualified())
4386 SC += "volatile ";
4387 if (GlobalVarDecl->getType().isRestrictQualified())
4388 SC += "restrict ";
4389 InsertText(FunLocStart, SC);
4390 }
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004391 if (GlobalConstructionExp) {
4392 // extra fancy dance for global literal expression.
4393
4394 // Always the latest block expression on the block stack.
4395 std::string Tag = "__";
4396 Tag += FunName;
4397 Tag += "_block_impl_";
4398 Tag += utostr(Blocks.size()-1);
4399 std::string globalBuf = "static ";
4400 globalBuf += Tag; globalBuf += " ";
4401 std::string SStr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004402
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004403 llvm::raw_string_ostream constructorExprBuf(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +00004404 GlobalConstructionExp->printPretty(constructorExprBuf, 0,
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004405 PrintingPolicy(LangOpts));
4406 globalBuf += constructorExprBuf.str();
4407 globalBuf += ";\n";
4408 InsertText(FunLocStart, globalBuf);
4409 GlobalConstructionExp = 0;
4410 }
4411
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004412 Blocks.clear();
4413 InnerDeclRefsCount.clear();
4414 InnerDeclRefs.clear();
4415 RewrittenBlockExprs.clear();
4416}
4417
4418void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Fariborz Jahanian04189532012-04-25 17:56:48 +00004419 SourceLocation FunLocStart =
4420 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4421 : FD->getTypeSpecStartLoc();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004422 StringRef FuncName = FD->getName();
4423
4424 SynthesizeBlockLiterals(FunLocStart, FuncName);
4425}
4426
4427static void BuildUniqueMethodName(std::string &Name,
4428 ObjCMethodDecl *MD) {
4429 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4430 Name = IFace->getName();
4431 Name += "__" + MD->getSelector().getAsString();
4432 // Convert colons to underscores.
4433 std::string::size_type loc = 0;
4434 while ((loc = Name.find(":", loc)) != std::string::npos)
4435 Name.replace(loc, 1, "_");
4436}
4437
4438void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4439 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4440 //SourceLocation FunLocStart = MD->getLocStart();
4441 SourceLocation FunLocStart = MD->getLocStart();
4442 std::string FuncName;
4443 BuildUniqueMethodName(FuncName, MD);
4444 SynthesizeBlockLiterals(FunLocStart, FuncName);
4445}
4446
4447void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4448 for (Stmt::child_range CI = S->children(); CI; ++CI)
4449 if (*CI) {
4450 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4451 GetBlockDeclRefExprs(CBE->getBody());
4452 else
4453 GetBlockDeclRefExprs(*CI);
4454 }
4455 // Handle specific things.
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004456 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4457 if (DRE->refersToEnclosingLocal()) {
4458 // FIXME: Handle enums.
4459 if (!isa<FunctionDecl>(DRE->getDecl()))
4460 BlockDeclRefs.push_back(DRE);
4461 if (HasLocalVariableExternalStorage(DRE->getDecl()))
4462 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004463 }
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004464 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004465
4466 return;
4467}
4468
4469void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +00004470 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004471 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
4472 for (Stmt::child_range CI = S->children(); CI; ++CI)
4473 if (*CI) {
4474 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4475 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4476 GetInnerBlockDeclRefExprs(CBE->getBody(),
4477 InnerBlockDeclRefs,
4478 InnerContexts);
4479 }
4480 else
4481 GetInnerBlockDeclRefExprs(*CI,
4482 InnerBlockDeclRefs,
4483 InnerContexts);
4484
4485 }
4486 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00004487 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4488 if (DRE->refersToEnclosingLocal()) {
4489 if (!isa<FunctionDecl>(DRE->getDecl()) &&
4490 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
4491 InnerBlockDeclRefs.push_back(DRE);
4492 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4493 if (Var->isFunctionOrMethodVarDecl())
4494 ImportedLocalExternalDecls.insert(Var);
4495 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004496 }
4497
4498 return;
4499}
4500
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004501/// convertObjCTypeToCStyleType - This routine converts such objc types
4502/// as qualified objects, and blocks to their closest c/c++ types that
4503/// it can. It returns true if input type was modified.
4504bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4505 QualType oldT = T;
4506 convertBlockPointerToFunctionPointer(T);
4507 if (T->isFunctionPointerType()) {
4508 QualType PointeeTy;
4509 if (const PointerType* PT = T->getAs<PointerType>()) {
4510 PointeeTy = PT->getPointeeType();
4511 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4512 T = convertFunctionTypeOfBlocks(FT);
4513 T = Context->getPointerType(T);
4514 }
4515 }
4516 }
4517
4518 convertToUnqualifiedObjCType(T);
4519 return T != oldT;
4520}
4521
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004522/// convertFunctionTypeOfBlocks - This routine converts a function type
4523/// whose result type may be a block pointer or whose argument type(s)
4524/// might be block pointers to an equivalent function type replacing
4525/// all block pointers to function pointers.
4526QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4527 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4528 // FTP will be null for closures that don't take arguments.
4529 // Generate a funky cast.
4530 SmallVector<QualType, 8> ArgTypes;
4531 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004532 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004533
4534 if (FTP) {
4535 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4536 E = FTP->arg_type_end(); I && (I != E); ++I) {
4537 QualType t = *I;
4538 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004539 if (convertObjCTypeToCStyleType(t))
4540 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004541 ArgTypes.push_back(t);
4542 }
4543 }
4544 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004545 if (modified)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004546 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
4547 else FuncType = QualType(FT, 0);
4548 return FuncType;
4549}
4550
4551Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4552 // Navigate to relevant type information.
4553 const BlockPointerType *CPT = 0;
4554
4555 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4556 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004557 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4558 CPT = MExpr->getType()->getAs<BlockPointerType>();
4559 }
4560 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4561 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4562 }
4563 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4564 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4565 else if (const ConditionalOperator *CEXPR =
4566 dyn_cast<ConditionalOperator>(BlockExp)) {
4567 Expr *LHSExp = CEXPR->getLHS();
4568 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4569 Expr *RHSExp = CEXPR->getRHS();
4570 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4571 Expr *CONDExp = CEXPR->getCond();
4572 ConditionalOperator *CondExpr =
4573 new (Context) ConditionalOperator(CONDExp,
4574 SourceLocation(), cast<Expr>(LHSStmt),
4575 SourceLocation(), cast<Expr>(RHSStmt),
4576 Exp->getType(), VK_RValue, OK_Ordinary);
4577 return CondExpr;
4578 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4579 CPT = IRE->getType()->getAs<BlockPointerType>();
4580 } else if (const PseudoObjectExpr *POE
4581 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4582 CPT = POE->getType()->castAs<BlockPointerType>();
4583 } else {
4584 assert(1 && "RewriteBlockClass: Bad type");
4585 }
4586 assert(CPT && "RewriteBlockClass: Bad type");
4587 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4588 assert(FT && "RewriteBlockClass: Bad type");
4589 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4590 // FTP will be null for closures that don't take arguments.
4591
4592 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4593 SourceLocation(), SourceLocation(),
4594 &Context->Idents.get("__block_impl"));
4595 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4596
4597 // Generate a funky cast.
4598 SmallVector<QualType, 8> ArgTypes;
4599
4600 // Push the block argument type.
4601 ArgTypes.push_back(PtrBlock);
4602 if (FTP) {
4603 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4604 E = FTP->arg_type_end(); I && (I != E); ++I) {
4605 QualType t = *I;
4606 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4607 if (!convertBlockPointerToFunctionPointer(t))
4608 convertToUnqualifiedObjCType(t);
4609 ArgTypes.push_back(t);
4610 }
4611 }
4612 // Now do the pointer to function cast.
4613 QualType PtrToFuncCastType
4614 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
4615
4616 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4617
4618 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4619 CK_BitCast,
4620 const_cast<Expr*>(BlockExp));
4621 // Don't forget the parens to enforce the proper binding.
4622 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4623 BlkCast);
4624 //PE->dump();
4625
4626 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4627 SourceLocation(),
4628 &Context->Idents.get("FuncPtr"),
4629 Context->VoidPtrTy, 0,
4630 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00004631 ICIS_NoInit);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004632 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4633 FD->getType(), VK_LValue,
4634 OK_Ordinary);
4635
4636
4637 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4638 CK_BitCast, ME);
4639 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4640
4641 SmallVector<Expr*, 8> BlkExprs;
4642 // Add the implicit argument.
4643 BlkExprs.push_back(BlkCast);
4644 // Add the user arguments.
4645 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4646 E = Exp->arg_end(); I != E; ++I) {
4647 BlkExprs.push_back(*I);
4648 }
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004649 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004650 Exp->getType(), VK_RValue,
4651 SourceLocation());
4652 return CE;
4653}
4654
4655// We need to return the rewritten expression to handle cases where the
John McCallf4b88a42012-03-10 09:33:50 +00004656// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004657// For example:
4658//
4659// int main() {
4660// __block Foo *f;
4661// __block int i;
4662//
4663// void (^myblock)() = ^() {
John McCallf4b88a42012-03-10 09:33:50 +00004664// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004665// i = 77;
4666// };
4667//}
John McCallf4b88a42012-03-10 09:33:50 +00004668Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004669 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4670 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00004671 ValueDecl *VD = DeclRefExp->getDecl();
4672 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004673
4674 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4675 SourceLocation(),
4676 &Context->Idents.get("__forwarding"),
4677 Context->VoidPtrTy, 0,
4678 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00004679 ICIS_NoInit);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004680 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4681 FD, SourceLocation(),
4682 FD->getType(), VK_LValue,
4683 OK_Ordinary);
4684
4685 StringRef Name = VD->getName();
4686 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
4687 &Context->Idents.get(Name),
4688 Context->VoidPtrTy, 0,
4689 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00004690 ICIS_NoInit);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004691 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4692 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4693
4694
4695
4696 // Need parens to enforce precedence.
4697 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4698 DeclRefExp->getExprLoc(),
4699 ME);
4700 ReplaceStmt(DeclRefExp, PE);
4701 return PE;
4702}
4703
4704// Rewrites the imported local variable V with external storage
4705// (static, extern, etc.) as *V
4706//
4707Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4708 ValueDecl *VD = DRE->getDecl();
4709 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4710 if (!ImportedLocalExternalDecls.count(Var))
4711 return DRE;
4712 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4713 VK_LValue, OK_Ordinary,
4714 DRE->getLocation());
4715 // Need parens to enforce precedence.
4716 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4717 Exp);
4718 ReplaceStmt(DRE, PE);
4719 return PE;
4720}
4721
4722void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4723 SourceLocation LocStart = CE->getLParenLoc();
4724 SourceLocation LocEnd = CE->getRParenLoc();
4725
4726 // Need to avoid trying to rewrite synthesized casts.
4727 if (LocStart.isInvalid())
4728 return;
4729 // Need to avoid trying to rewrite casts contained in macros.
4730 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4731 return;
4732
4733 const char *startBuf = SM->getCharacterData(LocStart);
4734 const char *endBuf = SM->getCharacterData(LocEnd);
4735 QualType QT = CE->getType();
4736 const Type* TypePtr = QT->getAs<Type>();
4737 if (isa<TypeOfExprType>(TypePtr)) {
4738 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4739 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4740 std::string TypeAsString = "(";
4741 RewriteBlockPointerType(TypeAsString, QT);
4742 TypeAsString += ")";
4743 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4744 return;
4745 }
4746 // advance the location to startArgList.
4747 const char *argPtr = startBuf;
4748
4749 while (*argPtr++ && (argPtr < endBuf)) {
4750 switch (*argPtr) {
4751 case '^':
4752 // Replace the '^' with '*'.
4753 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4754 ReplaceText(LocStart, 1, "*");
4755 break;
4756 }
4757 }
4758 return;
4759}
4760
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004761void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4762 CastKind CastKind = IC->getCastKind();
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004763 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4764 CastKind != CK_AnyPointerToBlockPointerCast)
4765 return;
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004766
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004767 QualType QT = IC->getType();
4768 (void)convertBlockPointerToFunctionPointer(QT);
4769 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4770 std::string Str = "(";
4771 Str += TypeString;
4772 Str += ")";
4773 InsertText(IC->getSubExpr()->getLocStart(), &Str[0], Str.size());
4774
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004775 return;
4776}
4777
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004778void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4779 SourceLocation DeclLoc = FD->getLocation();
4780 unsigned parenCount = 0;
4781
4782 // We have 1 or more arguments that have closure pointers.
4783 const char *startBuf = SM->getCharacterData(DeclLoc);
4784 const char *startArgList = strchr(startBuf, '(');
4785
4786 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4787
4788 parenCount++;
4789 // advance the location to startArgList.
4790 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4791 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4792
4793 const char *argPtr = startArgList;
4794
4795 while (*argPtr++ && parenCount) {
4796 switch (*argPtr) {
4797 case '^':
4798 // Replace the '^' with '*'.
4799 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4800 ReplaceText(DeclLoc, 1, "*");
4801 break;
4802 case '(':
4803 parenCount++;
4804 break;
4805 case ')':
4806 parenCount--;
4807 break;
4808 }
4809 }
4810 return;
4811}
4812
4813bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4814 const FunctionProtoType *FTP;
4815 const PointerType *PT = QT->getAs<PointerType>();
4816 if (PT) {
4817 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4818 } else {
4819 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4820 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4821 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4822 }
4823 if (FTP) {
4824 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4825 E = FTP->arg_type_end(); I != E; ++I)
4826 if (isTopLevelBlockPointerType(*I))
4827 return true;
4828 }
4829 return false;
4830}
4831
4832bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4833 const FunctionProtoType *FTP;
4834 const PointerType *PT = QT->getAs<PointerType>();
4835 if (PT) {
4836 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4837 } else {
4838 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4839 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4840 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4841 }
4842 if (FTP) {
4843 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4844 E = FTP->arg_type_end(); I != E; ++I) {
4845 if ((*I)->isObjCQualifiedIdType())
4846 return true;
4847 if ((*I)->isObjCObjectPointerType() &&
4848 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4849 return true;
4850 }
4851
4852 }
4853 return false;
4854}
4855
4856void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4857 const char *&RParen) {
4858 const char *argPtr = strchr(Name, '(');
4859 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4860
4861 LParen = argPtr; // output the start.
4862 argPtr++; // skip past the left paren.
4863 unsigned parenCount = 1;
4864
4865 while (*argPtr && parenCount) {
4866 switch (*argPtr) {
4867 case '(': parenCount++; break;
4868 case ')': parenCount--; break;
4869 default: break;
4870 }
4871 if (parenCount) argPtr++;
4872 }
4873 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4874 RParen = argPtr; // output the end
4875}
4876
4877void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4878 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4879 RewriteBlockPointerFunctionArgs(FD);
4880 return;
4881 }
4882 // Handle Variables and Typedefs.
4883 SourceLocation DeclLoc = ND->getLocation();
4884 QualType DeclT;
4885 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4886 DeclT = VD->getType();
4887 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4888 DeclT = TDD->getUnderlyingType();
4889 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4890 DeclT = FD->getType();
4891 else
4892 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4893
4894 const char *startBuf = SM->getCharacterData(DeclLoc);
4895 const char *endBuf = startBuf;
4896 // scan backward (from the decl location) for the end of the previous decl.
4897 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4898 startBuf--;
4899 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4900 std::string buf;
4901 unsigned OrigLength=0;
4902 // *startBuf != '^' if we are dealing with a pointer to function that
4903 // may take block argument types (which will be handled below).
4904 if (*startBuf == '^') {
4905 // Replace the '^' with '*', computing a negative offset.
4906 buf = '*';
4907 startBuf++;
4908 OrigLength++;
4909 }
4910 while (*startBuf != ')') {
4911 buf += *startBuf;
4912 startBuf++;
4913 OrigLength++;
4914 }
4915 buf += ')';
4916 OrigLength++;
4917
4918 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4919 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4920 // Replace the '^' with '*' for arguments.
4921 // Replace id<P> with id/*<>*/
4922 DeclLoc = ND->getLocation();
4923 startBuf = SM->getCharacterData(DeclLoc);
4924 const char *argListBegin, *argListEnd;
4925 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4926 while (argListBegin < argListEnd) {
4927 if (*argListBegin == '^')
4928 buf += '*';
4929 else if (*argListBegin == '<') {
4930 buf += "/*";
4931 buf += *argListBegin++;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004932 OrigLength++;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004933 while (*argListBegin != '>') {
4934 buf += *argListBegin++;
4935 OrigLength++;
4936 }
4937 buf += *argListBegin;
4938 buf += "*/";
4939 }
4940 else
4941 buf += *argListBegin;
4942 argListBegin++;
4943 OrigLength++;
4944 }
4945 buf += ')';
4946 OrigLength++;
4947 }
4948 ReplaceText(Start, OrigLength, buf);
4949
4950 return;
4951}
4952
4953
4954/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4955/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4956/// struct Block_byref_id_object *src) {
4957/// _Block_object_assign (&_dest->object, _src->object,
4958/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4959/// [|BLOCK_FIELD_IS_WEAK]) // object
4960/// _Block_object_assign(&_dest->object, _src->object,
4961/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4962/// [|BLOCK_FIELD_IS_WEAK]) // block
4963/// }
4964/// And:
4965/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4966/// _Block_object_dispose(_src->object,
4967/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4968/// [|BLOCK_FIELD_IS_WEAK]) // object
4969/// _Block_object_dispose(_src->object,
4970/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4971/// [|BLOCK_FIELD_IS_WEAK]) // block
4972/// }
4973
4974std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4975 int flag) {
4976 std::string S;
4977 if (CopyDestroyCache.count(flag))
4978 return S;
4979 CopyDestroyCache.insert(flag);
4980 S = "static void __Block_byref_id_object_copy_";
4981 S += utostr(flag);
4982 S += "(void *dst, void *src) {\n";
4983
4984 // offset into the object pointer is computed as:
4985 // void * + void* + int + int + void* + void *
4986 unsigned IntSize =
4987 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4988 unsigned VoidPtrSize =
4989 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4990
4991 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4992 S += " _Block_object_assign((char*)dst + ";
4993 S += utostr(offset);
4994 S += ", *(void * *) ((char*)src + ";
4995 S += utostr(offset);
4996 S += "), ";
4997 S += utostr(flag);
4998 S += ");\n}\n";
4999
5000 S += "static void __Block_byref_id_object_dispose_";
5001 S += utostr(flag);
5002 S += "(void *src) {\n";
5003 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5004 S += utostr(offset);
5005 S += "), ";
5006 S += utostr(flag);
5007 S += ");\n}\n";
5008 return S;
5009}
5010
5011/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5012/// the declaration into:
5013/// struct __Block_byref_ND {
5014/// void *__isa; // NULL for everything except __weak pointers
5015/// struct __Block_byref_ND *__forwarding;
5016/// int32_t __flags;
5017/// int32_t __size;
5018/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5019/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
5020/// typex ND;
5021/// };
5022///
5023/// It then replaces declaration of ND variable with:
5024/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5025/// __size=sizeof(struct __Block_byref_ND),
5026/// ND=initializer-if-any};
5027///
5028///
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005029void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
5030 bool lastDecl) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005031 int flag = 0;
5032 int isa = 0;
5033 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
5034 if (DeclLoc.isInvalid())
5035 // If type location is missing, it is because of missing type (a warning).
5036 // Use variable's location which is good for this case.
5037 DeclLoc = ND->getLocation();
5038 const char *startBuf = SM->getCharacterData(DeclLoc);
5039 SourceLocation X = ND->getLocEnd();
5040 X = SM->getExpansionLoc(X);
5041 const char *endBuf = SM->getCharacterData(X);
5042 std::string Name(ND->getNameAsString());
5043 std::string ByrefType;
5044 RewriteByRefString(ByrefType, Name, ND, true);
5045 ByrefType += " {\n";
5046 ByrefType += " void *__isa;\n";
5047 RewriteByRefString(ByrefType, Name, ND);
5048 ByrefType += " *__forwarding;\n";
5049 ByrefType += " int __flags;\n";
5050 ByrefType += " int __size;\n";
5051 // Add void *__Block_byref_id_object_copy;
5052 // void *__Block_byref_id_object_dispose; if needed.
5053 QualType Ty = ND->getType();
5054 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
5055 if (HasCopyAndDispose) {
5056 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5057 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5058 }
5059
5060 QualType T = Ty;
5061 (void)convertBlockPointerToFunctionPointer(T);
5062 T.getAsStringInternal(Name, Context->getPrintingPolicy());
5063
5064 ByrefType += " " + Name + ";\n";
5065 ByrefType += "};\n";
5066 // Insert this type in global scope. It is needed by helper function.
5067 SourceLocation FunLocStart;
5068 if (CurFunctionDef)
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00005069 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005070 else {
5071 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5072 FunLocStart = CurMethodDef->getLocStart();
5073 }
5074 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005075
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005076 if (Ty.isObjCGCWeak()) {
5077 flag |= BLOCK_FIELD_IS_WEAK;
5078 isa = 1;
5079 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005080 if (HasCopyAndDispose) {
5081 flag = BLOCK_BYREF_CALLER;
5082 QualType Ty = ND->getType();
5083 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5084 if (Ty->isBlockPointerType())
5085 flag |= BLOCK_FIELD_IS_BLOCK;
5086 else
5087 flag |= BLOCK_FIELD_IS_OBJECT;
5088 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5089 if (!HF.empty())
5090 InsertText(FunLocStart, HF);
5091 }
5092
5093 // struct __Block_byref_ND ND =
5094 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5095 // initializer-if-any};
5096 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanian104dbf92012-04-11 23:57:12 +00005097 // FIXME. rewriter does not support __block c++ objects which
5098 // require construction.
Fariborz Jahanian65a7c682012-04-26 23:20:25 +00005099 if (hasInit)
5100 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5101 CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5102 if (CXXDecl && CXXDecl->isDefaultConstructor())
5103 hasInit = false;
5104 }
5105
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005106 unsigned flags = 0;
5107 if (HasCopyAndDispose)
5108 flags |= BLOCK_HAS_COPY_DISPOSE;
5109 Name = ND->getNameAsString();
5110 ByrefType.clear();
5111 RewriteByRefString(ByrefType, Name, ND);
5112 std::string ForwardingCastType("(");
5113 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005114 ByrefType += " " + Name + " = {(void*)";
5115 ByrefType += utostr(isa);
5116 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
5117 ByrefType += utostr(flags);
5118 ByrefType += ", ";
5119 ByrefType += "sizeof(";
5120 RewriteByRefString(ByrefType, Name, ND);
5121 ByrefType += ")";
5122 if (HasCopyAndDispose) {
5123 ByrefType += ", __Block_byref_id_object_copy_";
5124 ByrefType += utostr(flag);
5125 ByrefType += ", __Block_byref_id_object_dispose_";
5126 ByrefType += utostr(flag);
5127 }
5128
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005129 if (!firstDecl) {
5130 // In multiple __block declarations, and for all but 1st declaration,
5131 // find location of the separating comma. This would be start location
5132 // where new text is to be inserted.
5133 DeclLoc = ND->getLocation();
5134 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5135 const char *commaBuf = startDeclBuf;
5136 while (*commaBuf != ',')
5137 commaBuf--;
5138 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5139 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5140 startBuf = commaBuf;
5141 }
5142
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005143 if (!hasInit) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005144 ByrefType += "};\n";
5145 unsigned nameSize = Name.size();
5146 // for block or function pointer declaration. Name is aleady
5147 // part of the declaration.
5148 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5149 nameSize = 1;
5150 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5151 }
5152 else {
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005153 ByrefType += ", ";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005154 SourceLocation startLoc;
5155 Expr *E = ND->getInit();
5156 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5157 startLoc = ECE->getLParenLoc();
5158 else
5159 startLoc = E->getLocStart();
5160 startLoc = SM->getExpansionLoc(startLoc);
5161 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005162 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005163
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005164 const char separator = lastDecl ? ';' : ',';
5165 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5166 const char *separatorBuf = strchr(startInitializerBuf, separator);
5167 assert((*separatorBuf == separator) &&
5168 "RewriteByRefVar: can't find ';' or ','");
5169 SourceLocation separatorLoc =
5170 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
5171
5172 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005173 }
5174 return;
5175}
5176
5177void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5178 // Add initializers for any closure decl refs.
5179 GetBlockDeclRefExprs(Exp->getBody());
5180 if (BlockDeclRefs.size()) {
5181 // Unique all "by copy" declarations.
5182 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005183 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005184 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5185 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5186 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5187 }
5188 }
5189 // Unique all "by ref" declarations.
5190 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005191 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005192 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5193 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5194 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5195 }
5196 }
5197 // Find any imported blocks...they will need special attention.
5198 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005199 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005200 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5201 BlockDeclRefs[i]->getType()->isBlockPointerType())
5202 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5203 }
5204}
5205
5206FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5207 IdentifierInfo *ID = &Context->Idents.get(name);
5208 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5209 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5210 SourceLocation(), ID, FType, 0, SC_Extern,
5211 SC_None, false, false);
5212}
5213
5214Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +00005215 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00005216
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005217 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00005218
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005219 Blocks.push_back(Exp);
5220
5221 CollectBlockDeclRefInfo(Exp);
5222
5223 // Add inner imported variables now used in current block.
5224 int countOfInnerDecls = 0;
5225 if (!InnerBlockDeclRefs.empty()) {
5226 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00005227 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005228 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00005229 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005230 // We need to save the copied-in variables in nested
5231 // blocks because it is needed at the end for some of the API generations.
5232 // See SynthesizeBlockLiterals routine.
5233 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5234 BlockDeclRefs.push_back(Exp);
5235 BlockByCopyDeclsPtrSet.insert(VD);
5236 BlockByCopyDecls.push_back(VD);
5237 }
John McCallf4b88a42012-03-10 09:33:50 +00005238 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005239 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5240 BlockDeclRefs.push_back(Exp);
5241 BlockByRefDeclsPtrSet.insert(VD);
5242 BlockByRefDecls.push_back(VD);
5243 }
5244 }
5245 // Find any imported blocks...they will need special attention.
5246 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005247 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005248 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5249 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5250 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5251 }
5252 InnerDeclRefsCount.push_back(countOfInnerDecls);
5253
5254 std::string FuncName;
5255
5256 if (CurFunctionDef)
5257 FuncName = CurFunctionDef->getNameAsString();
5258 else if (CurMethodDef)
5259 BuildUniqueMethodName(FuncName, CurMethodDef);
5260 else if (GlobalVarDecl)
5261 FuncName = std::string(GlobalVarDecl->getNameAsString());
5262
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005263 bool GlobalBlockExpr =
5264 block->getDeclContext()->getRedeclContext()->isFileContext();
5265
5266 if (GlobalBlockExpr && !GlobalVarDecl) {
5267 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5268 GlobalBlockExpr = false;
5269 }
5270
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005271 std::string BlockNumber = utostr(Blocks.size()-1);
5272
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005273 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5274
5275 // Get a pointer to the function type so we can cast appropriately.
5276 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5277 QualType FType = Context->getPointerType(BFT);
5278
5279 FunctionDecl *FD;
5280 Expr *NewRep;
5281
5282 // Simulate a contructor call...
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005283 std::string Tag;
5284
5285 if (GlobalBlockExpr)
5286 Tag = "__global_";
5287 else
5288 Tag = "__";
5289 Tag += FuncName + "_block_impl_" + BlockNumber;
5290
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005291 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00005292 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005293 SourceLocation());
5294
5295 SmallVector<Expr*, 4> InitExprs;
5296
5297 // Initialize the block function.
5298 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00005299 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5300 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005301 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5302 CK_BitCast, Arg);
5303 InitExprs.push_back(castExpr);
5304
5305 // Initialize the block descriptor.
5306 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5307
5308 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5309 SourceLocation(), SourceLocation(),
5310 &Context->Idents.get(DescData.c_str()),
5311 Context->VoidPtrTy, 0,
5312 SC_Static, SC_None);
5313 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00005314 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005315 Context->VoidPtrTy,
5316 VK_LValue,
5317 SourceLocation()),
5318 UO_AddrOf,
5319 Context->getPointerType(Context->VoidPtrTy),
5320 VK_RValue, OK_Ordinary,
5321 SourceLocation());
5322 InitExprs.push_back(DescRefExpr);
5323
5324 // Add initializers for any closure decl refs.
5325 if (BlockDeclRefs.size()) {
5326 Expr *Exp;
5327 // Output all "by copy" declarations.
5328 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
5329 E = BlockByCopyDecls.end(); I != E; ++I) {
5330 if (isObjCType((*I)->getType())) {
5331 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5332 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005333 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5334 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005335 if (HasLocalVariableExternalStorage(*I)) {
5336 QualType QT = (*I)->getType();
5337 QT = Context->getPointerType(QT);
5338 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5339 OK_Ordinary, SourceLocation());
5340 }
5341 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5342 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005343 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5344 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005345 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5346 CK_BitCast, Arg);
5347 } else {
5348 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005349 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5350 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005351 if (HasLocalVariableExternalStorage(*I)) {
5352 QualType QT = (*I)->getType();
5353 QT = Context->getPointerType(QT);
5354 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5355 OK_Ordinary, SourceLocation());
5356 }
5357
5358 }
5359 InitExprs.push_back(Exp);
5360 }
5361 // Output all "by ref" declarations.
5362 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
5363 E = BlockByRefDecls.end(); I != E; ++I) {
5364 ValueDecl *ND = (*I);
5365 std::string Name(ND->getNameAsString());
5366 std::string RecName;
5367 RewriteByRefString(RecName, Name, ND, true);
5368 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5369 + sizeof("struct"));
5370 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5371 SourceLocation(), SourceLocation(),
5372 II);
5373 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5374 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5375
5376 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005377 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005378 SourceLocation());
5379 bool isNestedCapturedVar = false;
5380 if (block)
5381 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5382 ce = block->capture_end(); ci != ce; ++ci) {
5383 const VarDecl *variable = ci->getVariable();
5384 if (variable == ND && ci->isNested()) {
5385 assert (ci->isByRef() &&
5386 "SynthBlockInitExpr - captured block variable is not byref");
5387 isNestedCapturedVar = true;
5388 break;
5389 }
5390 }
5391 // captured nested byref variable has its address passed. Do not take
5392 // its address again.
5393 if (!isNestedCapturedVar)
5394 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5395 Context->getPointerType(Exp->getType()),
5396 VK_RValue, OK_Ordinary, SourceLocation());
5397 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5398 InitExprs.push_back(Exp);
5399 }
5400 }
5401 if (ImportedBlockDecls.size()) {
5402 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5403 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5404 unsigned IntSize =
5405 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5406 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5407 Context->IntTy, SourceLocation());
5408 InitExprs.push_back(FlagExp);
5409 }
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005410 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005411 FType, VK_LValue, SourceLocation());
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005412
5413 if (GlobalBlockExpr) {
5414 assert (GlobalConstructionExp == 0 &&
5415 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5416 GlobalConstructionExp = NewRep;
5417 NewRep = DRE;
5418 }
5419
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005420 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5421 Context->getPointerType(NewRep->getType()),
5422 VK_RValue, OK_Ordinary, SourceLocation());
5423 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5424 NewRep);
5425 BlockDeclRefs.clear();
5426 BlockByRefDecls.clear();
5427 BlockByRefDeclsPtrSet.clear();
5428 BlockByCopyDecls.clear();
5429 BlockByCopyDeclsPtrSet.clear();
5430 ImportedBlockDecls.clear();
5431 return NewRep;
5432}
5433
5434bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5435 if (const ObjCForCollectionStmt * CS =
5436 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5437 return CS->getElement() == DS;
5438 return false;
5439}
5440
5441//===----------------------------------------------------------------------===//
5442// Function Body / Expression rewriting
5443//===----------------------------------------------------------------------===//
5444
5445Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5446 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5447 isa<DoStmt>(S) || isa<ForStmt>(S))
5448 Stmts.push_back(S);
5449 else if (isa<ObjCForCollectionStmt>(S)) {
5450 Stmts.push_back(S);
5451 ObjCBcLabelNo.push_back(++BcLabelCount);
5452 }
5453
5454 // Pseudo-object operations and ivar references need special
5455 // treatment because we're going to recursively rewrite them.
5456 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5457 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5458 return RewritePropertyOrImplicitSetter(PseudoOp);
5459 } else {
5460 return RewritePropertyOrImplicitGetter(PseudoOp);
5461 }
5462 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5463 return RewriteObjCIvarRefExpr(IvarRefExpr);
5464 }
5465
5466 SourceRange OrigStmtRange = S->getSourceRange();
5467
5468 // Perform a bottom up rewrite of all children.
5469 for (Stmt::child_range CI = S->children(); CI; ++CI)
5470 if (*CI) {
5471 Stmt *childStmt = (*CI);
5472 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5473 if (newStmt) {
5474 *CI = newStmt;
5475 }
5476 }
5477
5478 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00005479 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005480 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5481 InnerContexts.insert(BE->getBlockDecl());
5482 ImportedLocalExternalDecls.clear();
5483 GetInnerBlockDeclRefExprs(BE->getBody(),
5484 InnerBlockDeclRefs, InnerContexts);
5485 // Rewrite the block body in place.
5486 Stmt *SaveCurrentBody = CurrentBody;
5487 CurrentBody = BE->getBody();
5488 PropParentMap = 0;
5489 // block literal on rhs of a property-dot-sytax assignment
5490 // must be replaced by its synthesize ast so getRewrittenText
5491 // works as expected. In this case, what actually ends up on RHS
5492 // is the blockTranscribed which is the helper function for the
5493 // block literal; as in: self.c = ^() {[ace ARR];};
5494 bool saveDisableReplaceStmt = DisableReplaceStmt;
5495 DisableReplaceStmt = false;
5496 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5497 DisableReplaceStmt = saveDisableReplaceStmt;
5498 CurrentBody = SaveCurrentBody;
5499 PropParentMap = 0;
5500 ImportedLocalExternalDecls.clear();
5501 // Now we snarf the rewritten text and stash it away for later use.
5502 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5503 RewrittenBlockExprs[BE] = Str;
5504
5505 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5506
5507 //blockTranscribed->dump();
5508 ReplaceStmt(S, blockTranscribed);
5509 return blockTranscribed;
5510 }
5511 // Handle specific things.
5512 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5513 return RewriteAtEncode(AtEncode);
5514
5515 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5516 return RewriteAtSelector(AtSelector);
5517
5518 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5519 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian55947042012-03-27 20:17:30 +00005520
5521 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5522 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00005523
Patrick Beardeb382ec2012-04-19 00:25:12 +00005524 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5525 return RewriteObjCBoxedExpr(BoxedExpr);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00005526
5527 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5528 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005529
5530 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5531 dyn_cast<ObjCDictionaryLiteral>(S))
5532 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005533
5534 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5535#if 0
5536 // Before we rewrite it, put the original message expression in a comment.
5537 SourceLocation startLoc = MessExpr->getLocStart();
5538 SourceLocation endLoc = MessExpr->getLocEnd();
5539
5540 const char *startBuf = SM->getCharacterData(startLoc);
5541 const char *endBuf = SM->getCharacterData(endLoc);
5542
5543 std::string messString;
5544 messString += "// ";
5545 messString.append(startBuf, endBuf-startBuf+1);
5546 messString += "\n";
5547
5548 // FIXME: Missing definition of
5549 // InsertText(clang::SourceLocation, char const*, unsigned int).
5550 // InsertText(startLoc, messString.c_str(), messString.size());
5551 // Tried this, but it didn't work either...
5552 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5553#endif
5554 return RewriteMessageExpr(MessExpr);
5555 }
5556
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00005557 if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
5558 dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5559 return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5560 }
5561
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005562 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5563 return RewriteObjCTryStmt(StmtTry);
5564
5565 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5566 return RewriteObjCSynchronizedStmt(StmtTry);
5567
5568 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5569 return RewriteObjCThrowStmt(StmtThrow);
5570
5571 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5572 return RewriteObjCProtocolExpr(ProtocolExp);
5573
5574 if (ObjCForCollectionStmt *StmtForCollection =
5575 dyn_cast<ObjCForCollectionStmt>(S))
5576 return RewriteObjCForCollectionStmt(StmtForCollection,
5577 OrigStmtRange.getEnd());
5578 if (BreakStmt *StmtBreakStmt =
5579 dyn_cast<BreakStmt>(S))
5580 return RewriteBreakStmt(StmtBreakStmt);
5581 if (ContinueStmt *StmtContinueStmt =
5582 dyn_cast<ContinueStmt>(S))
5583 return RewriteContinueStmt(StmtContinueStmt);
5584
5585 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5586 // and cast exprs.
5587 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5588 // FIXME: What we're doing here is modifying the type-specifier that
5589 // precedes the first Decl. In the future the DeclGroup should have
5590 // a separate type-specifier that we can rewrite.
5591 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5592 // the context of an ObjCForCollectionStmt. For example:
5593 // NSArray *someArray;
5594 // for (id <FooProtocol> index in someArray) ;
5595 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5596 // and it depends on the original text locations/positions.
5597 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5598 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5599
5600 // Blocks rewrite rules.
5601 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5602 DI != DE; ++DI) {
5603 Decl *SD = *DI;
5604 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5605 if (isTopLevelBlockPointerType(ND->getType()))
5606 RewriteBlockPointerDecl(ND);
5607 else if (ND->getType()->isFunctionPointerType())
5608 CheckFunctionPointerDecl(ND->getType(), ND);
5609 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5610 if (VD->hasAttr<BlocksAttr>()) {
5611 static unsigned uniqueByrefDeclCount = 0;
5612 assert(!BlockByRefDeclNo.count(ND) &&
5613 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5614 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005615 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005616 }
5617 else
5618 RewriteTypeOfDecl(VD);
5619 }
5620 }
5621 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5622 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5623 RewriteBlockPointerDecl(TD);
5624 else if (TD->getUnderlyingType()->isFunctionPointerType())
5625 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5626 }
5627 }
5628 }
5629
5630 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5631 RewriteObjCQualifiedInterfaceTypes(CE);
5632
5633 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5634 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5635 assert(!Stmts.empty() && "Statement stack is empty");
5636 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5637 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5638 && "Statement stack mismatch");
5639 Stmts.pop_back();
5640 }
5641 // Handle blocks rewriting.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005642 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5643 ValueDecl *VD = DRE->getDecl();
5644 if (VD->hasAttr<BlocksAttr>())
5645 return RewriteBlockDeclRefExpr(DRE);
5646 if (HasLocalVariableExternalStorage(VD))
5647 return RewriteLocalVariableExternalStorage(DRE);
5648 }
5649
5650 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5651 if (CE->getCallee()->getType()->isBlockPointerType()) {
5652 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5653 ReplaceStmt(S, BlockCall);
5654 return BlockCall;
5655 }
5656 }
5657 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5658 RewriteCastExpr(CE);
5659 }
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00005660 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5661 RewriteImplicitCastObjCExpr(ICE);
5662 }
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00005663#if 0
Fariborz Jahanian653b7cf2012-04-13 18:00:54 +00005664
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005665 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5666 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5667 ICE->getSubExpr(),
5668 SourceLocation());
5669 // Get the new text.
5670 std::string SStr;
5671 llvm::raw_string_ostream Buf(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +00005672 Replacement->printPretty(Buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005673 const std::string &Str = Buf.str();
5674
5675 printf("CAST = %s\n", &Str[0]);
5676 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5677 delete S;
5678 return Replacement;
5679 }
5680#endif
5681 // Return this stmt unmodified.
5682 return S;
5683}
5684
5685void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5686 for (RecordDecl::field_iterator i = RD->field_begin(),
5687 e = RD->field_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00005688 FieldDecl *FD = *i;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005689 if (isTopLevelBlockPointerType(FD->getType()))
5690 RewriteBlockPointerDecl(FD);
5691 if (FD->getType()->isObjCQualifiedIdType() ||
5692 FD->getType()->isObjCQualifiedInterfaceType())
5693 RewriteObjCQualifiedInterfaceTypes(FD);
5694 }
5695}
5696
5697/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5698/// main file of the input.
5699void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5700 switch (D->getKind()) {
5701 case Decl::Function: {
5702 FunctionDecl *FD = cast<FunctionDecl>(D);
5703 if (FD->isOverloadedOperator())
5704 return;
5705
5706 // Since function prototypes don't have ParmDecl's, we check the function
5707 // prototype. This enables us to rewrite function declarations and
5708 // definitions using the same code.
5709 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5710
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00005711 if (!FD->isThisDeclarationADefinition())
5712 break;
5713
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005714 // FIXME: If this should support Obj-C++, support CXXTryStmt
5715 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5716 CurFunctionDef = FD;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005717 CurrentBody = Body;
5718 Body =
5719 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5720 FD->setBody(Body);
5721 CurrentBody = 0;
5722 if (PropParentMap) {
5723 delete PropParentMap;
5724 PropParentMap = 0;
5725 }
5726 // This synthesizes and inserts the block "impl" struct, invoke function,
5727 // and any copy/dispose helper functions.
5728 InsertBlockLiteralsWithinFunction(FD);
Fariborz Jahanian96205962012-11-06 17:30:23 +00005729 RewriteLineDirective(D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005730 CurFunctionDef = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005731 }
5732 break;
5733 }
5734 case Decl::ObjCMethod: {
5735 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5736 if (CompoundStmt *Body = MD->getCompoundBody()) {
5737 CurMethodDef = MD;
5738 CurrentBody = Body;
5739 Body =
5740 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5741 MD->setBody(Body);
5742 CurrentBody = 0;
5743 if (PropParentMap) {
5744 delete PropParentMap;
5745 PropParentMap = 0;
5746 }
5747 InsertBlockLiteralsWithinMethod(MD);
Fariborz Jahanian96205962012-11-06 17:30:23 +00005748 RewriteLineDirective(D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005749 CurMethodDef = 0;
5750 }
5751 break;
5752 }
5753 case Decl::ObjCImplementation: {
5754 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5755 ClassImplementation.push_back(CI);
5756 break;
5757 }
5758 case Decl::ObjCCategoryImpl: {
5759 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5760 CategoryImplementation.push_back(CI);
5761 break;
5762 }
5763 case Decl::Var: {
5764 VarDecl *VD = cast<VarDecl>(D);
5765 RewriteObjCQualifiedInterfaceTypes(VD);
5766 if (isTopLevelBlockPointerType(VD->getType()))
5767 RewriteBlockPointerDecl(VD);
5768 else if (VD->getType()->isFunctionPointerType()) {
5769 CheckFunctionPointerDecl(VD->getType(), VD);
5770 if (VD->getInit()) {
5771 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5772 RewriteCastExpr(CE);
5773 }
5774 }
5775 } else if (VD->getType()->isRecordType()) {
5776 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5777 if (RD->isCompleteDefinition())
5778 RewriteRecordBody(RD);
5779 }
5780 if (VD->getInit()) {
5781 GlobalVarDecl = VD;
5782 CurrentBody = VD->getInit();
5783 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5784 CurrentBody = 0;
5785 if (PropParentMap) {
5786 delete PropParentMap;
5787 PropParentMap = 0;
5788 }
5789 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5790 GlobalVarDecl = 0;
5791
5792 // This is needed for blocks.
5793 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5794 RewriteCastExpr(CE);
5795 }
5796 }
5797 break;
5798 }
5799 case Decl::TypeAlias:
5800 case Decl::Typedef: {
5801 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5802 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5803 RewriteBlockPointerDecl(TD);
5804 else if (TD->getUnderlyingType()->isFunctionPointerType())
5805 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5806 }
5807 break;
5808 }
5809 case Decl::CXXRecord:
5810 case Decl::Record: {
5811 RecordDecl *RD = cast<RecordDecl>(D);
5812 if (RD->isCompleteDefinition())
5813 RewriteRecordBody(RD);
5814 break;
5815 }
5816 default:
5817 break;
5818 }
5819 // Nothing yet.
5820}
5821
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005822/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5823/// protocol reference symbols in the for of:
5824/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5825static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5826 ObjCProtocolDecl *PDecl,
5827 std::string &Result) {
5828 // Also output .objc_protorefs$B section and its meta-data.
5829 if (Context->getLangOpts().MicrosoftExt)
Fariborz Jahanianbd78cfa2012-04-27 21:39:49 +00005830 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005831 Result += "struct _protocol_t *";
5832 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5833 Result += PDecl->getNameAsString();
5834 Result += " = &";
5835 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5836 Result += ";\n";
5837}
5838
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005839void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5840 if (Diags.hasErrorOccurred())
5841 return;
5842
5843 RewriteInclude();
5844
5845 // Here's a great place to add any extra declarations that may be needed.
5846 // Write out meta data for each @protocol(<expr>).
5847 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005848 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005849 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005850 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
5851 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005852
5853 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +00005854
5855 if (ClassImplementation.size() || CategoryImplementation.size())
5856 RewriteImplementations();
5857
Fariborz Jahanian57317782012-02-21 23:58:41 +00005858 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5859 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5860 // Write struct declaration for the class matching its ivar declarations.
5861 // Note that for modern abi, this is postponed until the end of TU
5862 // because class extensions and the implementation might declare their own
5863 // private ivars.
5864 RewriteInterfaceDecl(CDecl);
5865 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005866
5867 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5868 // we are done.
5869 if (const RewriteBuffer *RewriteBuf =
5870 Rewrite.getRewriteBufferFor(MainFileID)) {
5871 //printf("Changed:\n");
5872 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5873 } else {
5874 llvm::errs() << "No changes\n";
5875 }
5876
5877 if (ClassImplementation.size() || CategoryImplementation.size() ||
5878 ProtocolExprDecls.size()) {
5879 // Rewrite Objective-c meta data*
5880 std::string ResultStr;
5881 RewriteMetaDataIntoBuffer(ResultStr);
5882 // Emit metadata.
5883 *OutFile << ResultStr;
5884 }
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005885 // Emit ImageInfo;
5886 {
5887 std::string ResultStr;
5888 WriteImageInfo(ResultStr);
5889 *OutFile << ResultStr;
5890 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005891 OutFile->flush();
5892}
5893
5894void RewriteModernObjC::Initialize(ASTContext &context) {
5895 InitializeCommon(context);
5896
Fariborz Jahanian6991bc52012-03-10 17:45:38 +00005897 Preamble += "#ifndef __OBJC2__\n";
5898 Preamble += "#define __OBJC2__\n";
5899 Preamble += "#endif\n";
5900
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005901 // declaring objc_selector outside the parameter list removes a silly
5902 // scope related warning...
5903 if (IsHeader)
5904 Preamble = "#pragma once\n";
5905 Preamble += "struct objc_selector; struct objc_class;\n";
Fariborz Jahaniane2d87bc2012-04-12 23:52:52 +00005906 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
5907 Preamble += "\n\tstruct objc_object *superClass; ";
5908 // Add a constructor for creating temporary objects.
5909 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
5910 Preamble += ": object(o), superClass(s) {} ";
5911 Preamble += "\n};\n";
5912
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005913 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005914 // Define all sections using syntax that makes sense.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005915 // These are currently generated.
5916 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005917 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005918 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005919 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5920 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005921 // These are generated but not necessary for functionality.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005922 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005923 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5924 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005925 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005926
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005927 // These need be generated for performance. Currently they are not,
5928 // using API calls instead.
5929 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5930 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5931 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5932
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005933 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005934 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5935 Preamble += "typedef struct objc_object Protocol;\n";
5936 Preamble += "#define _REWRITER_typedef_Protocol\n";
5937 Preamble += "#endif\n";
5938 if (LangOpts.MicrosoftExt) {
5939 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5940 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005941 }
5942 else
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005943 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005944
5945 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
5946 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
5947 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
5948 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
5949 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
5950
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00005951 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005952 Preamble += "(const char *);\n";
5953 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5954 Preamble += "(struct objc_class *);\n";
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00005955 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005956 Preamble += "(const char *);\n";
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005957 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005958 // @synchronized hooks.
Aaron Ballman2d234d732012-09-06 16:44:16 +00005959 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
5960 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005961 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5962 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5963 Preamble += "struct __objcFastEnumerationState {\n\t";
5964 Preamble += "unsigned long state;\n\t";
5965 Preamble += "void **itemsPtr;\n\t";
5966 Preamble += "unsigned long *mutationsPtr;\n\t";
5967 Preamble += "unsigned long extra[5];\n};\n";
5968 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5969 Preamble += "#define __FASTENUMERATIONSTATE\n";
5970 Preamble += "#endif\n";
5971 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5972 Preamble += "struct __NSConstantStringImpl {\n";
5973 Preamble += " int *isa;\n";
5974 Preamble += " int flags;\n";
5975 Preamble += " char *str;\n";
5976 Preamble += " long length;\n";
5977 Preamble += "};\n";
5978 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5979 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5980 Preamble += "#else\n";
5981 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5982 Preamble += "#endif\n";
5983 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5984 Preamble += "#endif\n";
5985 // Blocks preamble.
5986 Preamble += "#ifndef BLOCK_IMPL\n";
5987 Preamble += "#define BLOCK_IMPL\n";
5988 Preamble += "struct __block_impl {\n";
5989 Preamble += " void *isa;\n";
5990 Preamble += " int Flags;\n";
5991 Preamble += " int Reserved;\n";
5992 Preamble += " void *FuncPtr;\n";
5993 Preamble += "};\n";
5994 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5995 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5996 Preamble += "extern \"C\" __declspec(dllexport) "
5997 "void _Block_object_assign(void *, const void *, const int);\n";
5998 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5999 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
6000 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
6001 Preamble += "#else\n";
6002 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
6003 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
6004 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
6005 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
6006 Preamble += "#endif\n";
6007 Preamble += "#endif\n";
6008 if (LangOpts.MicrosoftExt) {
6009 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
6010 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
6011 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
6012 Preamble += "#define __attribute__(X)\n";
6013 Preamble += "#endif\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00006014 Preamble += "#ifndef __weak\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006015 Preamble += "#define __weak\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00006016 Preamble += "#endif\n";
6017 Preamble += "#ifndef __block\n";
6018 Preamble += "#define __block\n";
6019 Preamble += "#endif\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006020 }
6021 else {
6022 Preamble += "#define __block\n";
6023 Preamble += "#define __weak\n";
6024 }
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00006025
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006026 // Declarations required for modern objective-c array and dictionary literals.
6027 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00006028 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006029 Preamble += " void * *arr;\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00006030 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006031 Preamble += "\tva_list marker;\n";
6032 Preamble += "\tva_start(marker, count);\n";
6033 Preamble += "\tarr = new void *[count];\n";
6034 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
6035 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
6036 Preamble += "\tva_end( marker );\n";
6037 Preamble += " };\n";
Fariborz Jahanian13a9c022012-05-02 23:53:46 +00006038 Preamble += " ~__NSContainer_literal() {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006039 Preamble += "\tdelete[] arr;\n";
6040 Preamble += " }\n";
6041 Preamble += "};\n";
6042
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00006043 // Declaration required for implementation of @autoreleasepool statement.
6044 Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
6045 Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
6046 Preamble += "struct __AtAutoreleasePool {\n";
6047 Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
6048 Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
6049 Preamble += " void * atautoreleasepoolobj;\n";
6050 Preamble += "};\n";
6051
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006052 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
6053 // as this avoids warning in any 64bit/32bit compilation model.
6054 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6055}
6056
6057/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
6058/// ivar offset.
6059void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
6060 std::string &Result) {
6061 if (ivar->isBitField()) {
6062 // FIXME: The hack below doesn't work for bitfields. For now, we simply
6063 // place all bitfields at offset 0.
6064 Result += "0";
6065 } else {
6066 Result += "__OFFSETOFIVAR__(struct ";
6067 Result += ivar->getContainingInterface()->getNameAsString();
6068 if (LangOpts.MicrosoftExt)
6069 Result += "_IMPL";
6070 Result += ", ";
6071 Result += ivar->getNameAsString();
6072 Result += ")";
6073 }
6074}
6075
6076/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6077/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006078/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006079/// char *attributes;
6080/// }
6081
6082/// struct _prop_list_t {
6083/// uint32_t entsize; // sizeof(struct _prop_t)
6084/// uint32_t count_of_properties;
6085/// struct _prop_t prop_list[count_of_properties];
6086/// }
6087
6088/// struct _protocol_t;
6089
6090/// struct _protocol_list_t {
6091/// long protocol_count; // Note, this is 32/64 bit
6092/// struct _protocol_t * protocol_list[protocol_count];
6093/// }
6094
6095/// struct _objc_method {
6096/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006097/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006098/// char *_imp;
6099/// }
6100
6101/// struct _method_list_t {
6102/// uint32_t entsize; // sizeof(struct _objc_method)
6103/// uint32_t method_count;
6104/// struct _objc_method method_list[method_count];
6105/// }
6106
6107/// struct _protocol_t {
6108/// id isa; // NULL
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006109/// const char *protocol_name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006110/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006111/// const struct method_list_t *instance_methods;
6112/// const struct method_list_t *class_methods;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006113/// const struct method_list_t *optionalInstanceMethods;
6114/// const struct method_list_t *optionalClassMethods;
6115/// const struct _prop_list_t * properties;
6116/// const uint32_t size; // sizeof(struct _protocol_t)
6117/// const uint32_t flags; // = 0
6118/// const char ** extendedMethodTypes;
6119/// }
6120
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006121/// struct _ivar_t {
6122/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00006123/// const char *name;
6124/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006125/// uint32_t alignment;
6126/// uint32_t size;
6127/// }
6128
6129/// struct _ivar_list_t {
6130/// uint32 entsize; // sizeof(struct _ivar_t)
6131/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00006132/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006133/// }
6134
6135/// struct _class_ro_t {
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006136/// uint32_t flags;
6137/// uint32_t instanceStart;
6138/// uint32_t instanceSize;
6139/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006140/// const uint8_t *ivarLayout;
6141/// const char *name;
6142/// const struct _method_list_t *baseMethods;
6143/// const struct _protocol_list_t *baseProtocols;
6144/// const struct _ivar_list_t *ivars;
6145/// const uint8_t *weakIvarLayout;
6146/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006147/// }
6148
6149/// struct _class_t {
6150/// struct _class_t *isa;
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00006151/// struct _class_t *superclass;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006152/// void *cache;
6153/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006154/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006155/// }
6156
6157/// struct _category_t {
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006158/// const char *name;
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006159/// struct _class_t *cls;
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006160/// const struct _method_list_t *instance_methods;
6161/// const struct _method_list_t *class_methods;
6162/// const struct _protocol_list_t *protocols;
6163/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006164/// }
6165
6166/// MessageRefTy - LLVM for:
6167/// struct _message_ref_t {
6168/// IMP messenger;
6169/// SEL name;
6170/// };
6171
6172/// SuperMessageRefTy - LLVM for:
6173/// struct _super_message_ref_t {
6174/// SUPER_IMP messenger;
6175/// SEL name;
6176/// };
6177
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006178static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006179 static bool meta_data_declared = false;
6180 if (meta_data_declared)
6181 return;
6182
6183 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006184 Result += "\tconst char *name;\n";
6185 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006186 Result += "};\n";
6187
6188 Result += "\nstruct _protocol_t;\n";
6189
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006190 Result += "\nstruct _objc_method {\n";
6191 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006192 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006193 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006194 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006195
6196 Result += "\nstruct _protocol_t {\n";
6197 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006198 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006199 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006200 Result += "\tconst struct method_list_t *instance_methods;\n";
6201 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006202 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6203 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6204 Result += "\tconst struct _prop_list_t * properties;\n";
6205 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
6206 Result += "\tconst unsigned int flags; // = 0\n";
6207 Result += "\tconst char ** extendedMethodTypes;\n";
6208 Result += "};\n";
6209
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006210 Result += "\nstruct _ivar_t {\n";
6211 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00006212 Result += "\tconst char *name;\n";
6213 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006214 Result += "\tunsigned int alignment;\n";
6215 Result += "\tunsigned int size;\n";
6216 Result += "};\n";
6217
6218 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006219 Result += "\tunsigned int flags;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006220 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006221 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006222 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6223 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006224 Result += "\tunsigned int reserved;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006225 Result += "\tconst unsigned char *ivarLayout;\n";
6226 Result += "\tconst char *name;\n";
6227 Result += "\tconst struct _method_list_t *baseMethods;\n";
6228 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6229 Result += "\tconst struct _ivar_list_t *ivars;\n";
6230 Result += "\tconst unsigned char *weakIvarLayout;\n";
6231 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006232 Result += "};\n";
6233
6234 Result += "\nstruct _class_t {\n";
6235 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00006236 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006237 Result += "\tvoid *cache;\n";
6238 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006239 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006240 Result += "};\n";
6241
6242 Result += "\nstruct _category_t {\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006243 Result += "\tconst char *name;\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006244 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006245 Result += "\tconst struct _method_list_t *instance_methods;\n";
6246 Result += "\tconst struct _method_list_t *class_methods;\n";
6247 Result += "\tconst struct _protocol_list_t *protocols;\n";
6248 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006249 Result += "};\n";
6250
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006251 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006252 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006253 meta_data_declared = true;
6254}
6255
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006256static void Write_protocol_list_t_TypeDecl(std::string &Result,
6257 long super_protocol_count) {
6258 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6259 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6260 Result += "\tstruct _protocol_t *super_protocols[";
6261 Result += utostr(super_protocol_count); Result += "];\n";
6262 Result += "}";
6263}
6264
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006265static void Write_method_list_t_TypeDecl(std::string &Result,
6266 unsigned int method_count) {
6267 Result += "struct /*_method_list_t*/"; Result += " {\n";
6268 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6269 Result += "\tunsigned int method_count;\n";
6270 Result += "\tstruct _objc_method method_list[";
6271 Result += utostr(method_count); Result += "];\n";
6272 Result += "}";
6273}
6274
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006275static void Write__prop_list_t_TypeDecl(std::string &Result,
6276 unsigned int property_count) {
6277 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6278 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6279 Result += "\tunsigned int count_of_properties;\n";
6280 Result += "\tstruct _prop_t prop_list[";
6281 Result += utostr(property_count); Result += "];\n";
6282 Result += "}";
6283}
6284
Fariborz Jahanianae932952012-02-10 20:47:10 +00006285static void Write__ivar_list_t_TypeDecl(std::string &Result,
6286 unsigned int ivar_count) {
6287 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6288 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6289 Result += "\tunsigned int count;\n";
6290 Result += "\tstruct _ivar_t ivar_list[";
6291 Result += utostr(ivar_count); Result += "];\n";
6292 Result += "}";
6293}
6294
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006295static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6296 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6297 StringRef VarName,
6298 StringRef ProtocolName) {
6299 if (SuperProtocols.size() > 0) {
6300 Result += "\nstatic ";
6301 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6302 Result += " "; Result += VarName;
6303 Result += ProtocolName;
6304 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6305 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6306 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6307 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6308 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6309 Result += SuperPD->getNameAsString();
6310 if (i == e-1)
6311 Result += "\n};\n";
6312 else
6313 Result += ",\n";
6314 }
6315 }
6316}
6317
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006318static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6319 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006320 ArrayRef<ObjCMethodDecl *> Methods,
6321 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006322 StringRef TopLevelDeclName,
6323 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006324 if (Methods.size() > 0) {
6325 Result += "\nstatic ";
6326 Write_method_list_t_TypeDecl(Result, Methods.size());
6327 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006328 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006329 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6330 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6331 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6332 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6333 ObjCMethodDecl *MD = Methods[i];
6334 if (i == 0)
6335 Result += "\t{{(struct objc_selector *)\"";
6336 else
6337 Result += "\t{(struct objc_selector *)\"";
6338 Result += (MD)->getSelector().getAsString(); Result += "\"";
6339 Result += ", ";
6340 std::string MethodTypeString;
6341 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6342 Result += "\""; Result += MethodTypeString; Result += "\"";
6343 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006344 if (!MethodImpl)
6345 Result += "0";
6346 else {
6347 Result += "(void *)";
6348 Result += RewriteObj.MethodInternalNames[MD];
6349 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006350 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006351 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006352 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006353 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006354 }
6355 Result += "};\n";
6356 }
6357}
6358
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006359static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006360 ASTContext *Context, std::string &Result,
6361 ArrayRef<ObjCPropertyDecl *> Properties,
6362 const Decl *Container,
6363 StringRef VarName,
6364 StringRef ProtocolName) {
6365 if (Properties.size() > 0) {
6366 Result += "\nstatic ";
6367 Write__prop_list_t_TypeDecl(Result, Properties.size());
6368 Result += " "; Result += VarName;
6369 Result += ProtocolName;
6370 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6371 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6372 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6373 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6374 ObjCPropertyDecl *PropDecl = Properties[i];
6375 if (i == 0)
6376 Result += "\t{{\"";
6377 else
6378 Result += "\t{\"";
6379 Result += PropDecl->getName(); Result += "\",";
6380 std::string PropertyTypeString, QuotePropertyTypeString;
6381 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6382 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6383 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6384 if (i == e-1)
6385 Result += "}}\n";
6386 else
6387 Result += "},\n";
6388 }
6389 Result += "};\n";
6390 }
6391}
6392
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006393// Metadata flags
6394enum MetaDataDlags {
6395 CLS = 0x0,
6396 CLS_META = 0x1,
6397 CLS_ROOT = 0x2,
6398 OBJC2_CLS_HIDDEN = 0x10,
6399 CLS_EXCEPTION = 0x20,
6400
6401 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6402 CLS_HAS_IVAR_RELEASER = 0x40,
6403 /// class was compiled with -fobjc-arr
6404 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6405};
6406
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006407static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6408 unsigned int flags,
6409 const std::string &InstanceStart,
6410 const std::string &InstanceSize,
6411 ArrayRef<ObjCMethodDecl *>baseMethods,
6412 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6413 ArrayRef<ObjCIvarDecl *>ivars,
6414 ArrayRef<ObjCPropertyDecl *>Properties,
6415 StringRef VarName,
6416 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006417 Result += "\nstatic struct _class_ro_t ";
6418 Result += VarName; Result += ClassName;
6419 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6420 Result += "\t";
6421 Result += llvm::utostr(flags); Result += ", ";
6422 Result += InstanceStart; Result += ", ";
6423 Result += InstanceSize; Result += ", \n";
6424 Result += "\t";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006425 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6426 if (Triple.getArch() == llvm::Triple::x86_64)
6427 // uint32_t const reserved; // only when building for 64bit targets
6428 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006429 // const uint8_t * const ivarLayout;
6430 Result += "0, \n\t";
6431 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006432 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006433 if (baseMethods.size() > 0) {
6434 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006435 if (metaclass)
6436 Result += "_OBJC_$_CLASS_METHODS_";
6437 else
6438 Result += "_OBJC_$_INSTANCE_METHODS_";
6439 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006440 Result += ",\n\t";
6441 }
6442 else
6443 Result += "0, \n\t";
6444
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006445 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006446 Result += "(const struct _objc_protocol_list *)&";
6447 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6448 Result += ",\n\t";
6449 }
6450 else
6451 Result += "0, \n\t";
6452
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006453 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006454 Result += "(const struct _ivar_list_t *)&";
6455 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6456 Result += ",\n\t";
6457 }
6458 else
6459 Result += "0, \n\t";
6460
6461 // weakIvarLayout
6462 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006463 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006464 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006465 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006466 Result += ",\n";
6467 }
6468 else
6469 Result += "0, \n";
6470
6471 Result += "};\n";
6472}
6473
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006474static void Write_class_t(ASTContext *Context, std::string &Result,
6475 StringRef VarName,
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006476 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6477 bool rootClass = (!CDecl->getSuperClass());
6478 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006479
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006480 if (!rootClass) {
6481 // Find the Root class
6482 RootClass = CDecl->getSuperClass();
6483 while (RootClass->getSuperClass()) {
6484 RootClass = RootClass->getSuperClass();
6485 }
6486 }
6487
6488 if (metaclass && rootClass) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006489 // Need to handle a case of use of forward declaration.
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006490 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006491 Result += "extern \"C\" ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006492 if (CDecl->getImplementation())
6493 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006494 else
6495 Result += "__declspec(dllimport) ";
6496
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006497 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006498 Result += CDecl->getNameAsString();
6499 Result += ";\n";
6500 }
6501 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006502 if (!rootClass) {
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006503 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006504 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006505 Result += "extern \"C\" ";
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006506 if (SuperClass->getImplementation())
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006507 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006508 else
6509 Result += "__declspec(dllimport) ";
6510
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006511 Result += "struct _class_t ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006512 Result += VarName;
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006513 Result += SuperClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006514 Result += ";\n";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006515
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006516 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006517 Result += "extern \"C\" ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006518 if (RootClass->getImplementation())
6519 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006520 else
6521 Result += "__declspec(dllimport) ";
6522
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006523 Result += "struct _class_t ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006524 Result += VarName;
6525 Result += RootClass->getNameAsString();
6526 Result += ";\n";
6527 }
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006528 }
6529
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006530 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6531 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006532 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6533 Result += "\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006534 if (metaclass) {
6535 if (!rootClass) {
6536 Result += "0, // &"; Result += VarName;
6537 Result += RootClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006538 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006539 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006540 Result += CDecl->getSuperClass()->getNameAsString();
6541 Result += ",\n\t";
6542 }
6543 else {
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006544 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006545 Result += CDecl->getNameAsString();
6546 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006547 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006548 Result += ",\n\t";
6549 }
6550 }
6551 else {
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006552 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006553 Result += CDecl->getNameAsString();
6554 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006555 if (!rootClass) {
6556 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006557 Result += CDecl->getSuperClass()->getNameAsString();
6558 Result += ",\n\t";
6559 }
6560 else
6561 Result += "0,\n\t";
6562 }
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006563 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6564 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6565 if (metaclass)
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006566 Result += "&_OBJC_METACLASS_RO_$_";
6567 else
6568 Result += "&_OBJC_CLASS_RO_$_";
6569 Result += CDecl->getNameAsString();
6570 Result += ",\n};\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006571
6572 // Add static function to initialize some of the meta-data fields.
6573 // avoid doing it twice.
6574 if (metaclass)
6575 return;
6576
6577 const ObjCInterfaceDecl *SuperClass =
6578 rootClass ? CDecl : CDecl->getSuperClass();
6579
6580 Result += "static void OBJC_CLASS_SETUP_$_";
6581 Result += CDecl->getNameAsString();
6582 Result += "(void ) {\n";
6583 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6584 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006585 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006586
6587 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006588 Result += ".superclass = ";
6589 if (rootClass)
6590 Result += "&OBJC_CLASS_$_";
6591 else
6592 Result += "&OBJC_METACLASS_$_";
6593
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006594 Result += SuperClass->getNameAsString(); Result += ";\n";
6595
6596 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6597 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6598
6599 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6600 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6601 Result += CDecl->getNameAsString(); Result += ";\n";
6602
6603 if (!rootClass) {
6604 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6605 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6606 Result += SuperClass->getNameAsString(); Result += ";\n";
6607 }
6608
6609 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6610 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6611 Result += "}\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006612}
6613
Fariborz Jahanian61186122012-02-17 18:40:41 +00006614static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6615 std::string &Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006616 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006617 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006618 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6619 ArrayRef<ObjCMethodDecl *> ClassMethods,
6620 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6621 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006622 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi20f89392012-03-21 03:21:46 +00006623 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006624 // must declare an extern class object in case this class is not implemented
6625 // in this TU.
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006626 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006627 Result += "extern \"C\" ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006628 if (ClassDecl->getImplementation())
6629 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006630 else
6631 Result += "__declspec(dllimport) ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006632
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006633 Result += "struct _class_t ";
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006634 Result += "OBJC_CLASS_$_"; Result += ClassName;
6635 Result += ";\n";
6636
Fariborz Jahanian61186122012-02-17 18:40:41 +00006637 Result += "\nstatic struct _category_t ";
6638 Result += "_OBJC_$_CATEGORY_";
6639 Result += ClassName; Result += "_$_"; Result += CatName;
6640 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6641 Result += "{\n";
6642 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006643 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanian61186122012-02-17 18:40:41 +00006644 Result += ",\n";
6645 if (InstanceMethods.size() > 0) {
6646 Result += "\t(const struct _method_list_t *)&";
6647 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6648 Result += ClassName; Result += "_$_"; Result += CatName;
6649 Result += ",\n";
6650 }
6651 else
6652 Result += "\t0,\n";
6653
6654 if (ClassMethods.size() > 0) {
6655 Result += "\t(const struct _method_list_t *)&";
6656 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6657 Result += ClassName; Result += "_$_"; Result += CatName;
6658 Result += ",\n";
6659 }
6660 else
6661 Result += "\t0,\n";
6662
6663 if (RefedProtocols.size() > 0) {
6664 Result += "\t(const struct _protocol_list_t *)&";
6665 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6666 Result += ClassName; Result += "_$_"; Result += CatName;
6667 Result += ",\n";
6668 }
6669 else
6670 Result += "\t0,\n";
6671
6672 if (ClassProperties.size() > 0) {
6673 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6674 Result += ClassName; Result += "_$_"; Result += CatName;
6675 Result += ",\n";
6676 }
6677 else
6678 Result += "\t0,\n";
6679
6680 Result += "};\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006681
6682 // Add static function to initialize the class pointer in the category structure.
6683 Result += "static void OBJC_CATEGORY_SETUP_$_";
6684 Result += ClassDecl->getNameAsString();
6685 Result += "_$_";
6686 Result += CatName;
6687 Result += "(void ) {\n";
6688 Result += "\t_OBJC_$_CATEGORY_";
6689 Result += ClassDecl->getNameAsString();
6690 Result += "_$_";
6691 Result += CatName;
6692 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6693 Result += ";\n}\n";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006694}
6695
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006696static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6697 ASTContext *Context, std::string &Result,
6698 ArrayRef<ObjCMethodDecl *> Methods,
6699 StringRef VarName,
6700 StringRef ProtocolName) {
6701 if (Methods.size() == 0)
6702 return;
6703
6704 Result += "\nstatic const char *";
6705 Result += VarName; Result += ProtocolName;
6706 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6707 Result += "{\n";
6708 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6709 ObjCMethodDecl *MD = Methods[i];
6710 std::string MethodTypeString, QuoteMethodTypeString;
6711 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6712 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6713 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6714 if (i == e-1)
6715 Result += "\n};\n";
6716 else {
6717 Result += ",\n";
6718 }
6719 }
6720}
6721
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006722static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6723 ASTContext *Context,
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006724 std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006725 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006726 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006727 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6728 // this is what happens:
6729 /**
6730 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6731 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6732 Class->getVisibility() == HiddenVisibility)
6733 Visibility shoud be: HiddenVisibility;
6734 else
6735 Visibility shoud be: DefaultVisibility;
6736 */
6737
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006738 Result += "\n";
6739 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6740 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006741 if (Context->getLangOpts().MicrosoftExt)
6742 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6743
6744 if (!Context->getLangOpts().MicrosoftExt ||
6745 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanian117591f2012-03-10 01:34:42 +00006746 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006747 Result += "extern \"C\" unsigned long int ";
Fariborz Jahaniand1c84d32012-03-10 00:53:02 +00006748 else
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006749 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006750 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006751 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6752 Result += " = ";
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006753 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6754 Result += ";\n";
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006755 }
6756}
6757
Fariborz Jahanianae932952012-02-10 20:47:10 +00006758static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6759 ASTContext *Context, std::string &Result,
6760 ArrayRef<ObjCIvarDecl *> Ivars,
6761 StringRef VarName,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006762 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanianae932952012-02-10 20:47:10 +00006763 if (Ivars.size() > 0) {
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006764 Write_IvarOffsetVar(RewriteObj, Context, Result, Ivars, CDecl);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006765
Fariborz Jahanianae932952012-02-10 20:47:10 +00006766 Result += "\nstatic ";
6767 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6768 Result += " "; Result += VarName;
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006769 Result += CDecl->getNameAsString();
Fariborz Jahanianae932952012-02-10 20:47:10 +00006770 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6771 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6772 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6773 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6774 ObjCIvarDecl *IvarDecl = Ivars[i];
6775 if (i == 0)
6776 Result += "\t{{";
6777 else
6778 Result += "\t {";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006779 Result += "(unsigned long int *)&";
6780 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006781 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00006782
6783 Result += "\""; Result += IvarDecl->getName(); Result += "\", ";
6784 std::string IvarTypeString, QuoteIvarTypeString;
6785 Context->getObjCEncodingForType(IvarDecl->getType(), IvarTypeString,
6786 IvarDecl);
6787 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6788 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6789
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006790 // FIXME. this alignment represents the host alignment and need be changed to
6791 // represent the target alignment.
6792 unsigned Align = Context->getTypeAlign(IvarDecl->getType())/8;
6793 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006794 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00006795 CharUnits Size = Context->getTypeSizeInChars(IvarDecl->getType());
6796 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00006797 if (i == e-1)
6798 Result += "}}\n";
6799 else
6800 Result += "},\n";
6801 }
6802 Result += "};\n";
6803 }
6804}
6805
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006806/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006807void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
6808 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006809
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006810 // Do not synthesize the protocol more than once.
6811 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6812 return;
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006813 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006814
6815 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6816 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006817 // Must write out all protocol definitions in current qualifier list,
6818 // and in their nested qualifiers before writing out current definition.
6819 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6820 E = PDecl->protocol_end(); I != E; ++I)
6821 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006822
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006823 // Construct method lists.
6824 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6825 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
6826 for (ObjCProtocolDecl::instmeth_iterator
6827 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
6828 I != E; ++I) {
6829 ObjCMethodDecl *MD = *I;
6830 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6831 OptInstanceMethods.push_back(MD);
6832 } else {
6833 InstanceMethods.push_back(MD);
6834 }
6835 }
6836
6837 for (ObjCProtocolDecl::classmeth_iterator
6838 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
6839 I != E; ++I) {
6840 ObjCMethodDecl *MD = *I;
6841 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6842 OptClassMethods.push_back(MD);
6843 } else {
6844 ClassMethods.push_back(MD);
6845 }
6846 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006847 std::vector<ObjCMethodDecl *> AllMethods;
6848 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6849 AllMethods.push_back(InstanceMethods[i]);
6850 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6851 AllMethods.push_back(ClassMethods[i]);
6852 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6853 AllMethods.push_back(OptInstanceMethods[i]);
6854 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6855 AllMethods.push_back(OptClassMethods[i]);
6856
6857 Write__extendedMethodTypes_initializer(*this, Context, Result,
6858 AllMethods,
6859 "_OBJC_PROTOCOL_METHOD_TYPES_",
6860 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006861 // Protocol's super protocol list
6862 std::vector<ObjCProtocolDecl *> SuperProtocols;
6863 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6864 E = PDecl->protocol_end(); I != E; ++I)
6865 SuperProtocols.push_back(*I);
6866
6867 Write_protocol_list_initializer(Context, Result, SuperProtocols,
6868 "_OBJC_PROTOCOL_REFS_",
6869 PDecl->getNameAsString());
6870
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006871 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006872 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006873 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006874
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006875 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006876 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006877 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006878
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006879 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006880 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006881 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006882
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006883 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006884 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006885 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006886
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006887 // Protocol's property metadata.
6888 std::vector<ObjCPropertyDecl *> ProtocolProperties;
6889 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
6890 E = PDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00006891 ProtocolProperties.push_back(*I);
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006892
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006893 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006894 /* Container */0,
6895 "_OBJC_PROTOCOL_PROPERTIES_",
6896 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006897
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006898 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006899 Result += "\n";
6900 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00006901 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006902 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006903 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006904 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
6905 Result += "\t0,\n"; // id is; is null
6906 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006907 if (SuperProtocols.size() > 0) {
6908 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6909 Result += PDecl->getNameAsString(); Result += ",\n";
6910 }
6911 else
6912 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006913 if (InstanceMethods.size() > 0) {
6914 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
6915 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006916 }
6917 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006918 Result += "\t0,\n";
6919
6920 if (ClassMethods.size() > 0) {
6921 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
6922 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006923 }
6924 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006925 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006926
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006927 if (OptInstanceMethods.size() > 0) {
6928 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
6929 Result += PDecl->getNameAsString(); Result += ",\n";
6930 }
6931 else
6932 Result += "\t0,\n";
6933
6934 if (OptClassMethods.size() > 0) {
6935 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
6936 Result += PDecl->getNameAsString(); Result += ",\n";
6937 }
6938 else
6939 Result += "\t0,\n";
6940
6941 if (ProtocolProperties.size() > 0) {
6942 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
6943 Result += PDecl->getNameAsString(); Result += ",\n";
6944 }
6945 else
6946 Result += "\t0,\n";
6947
6948 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6949 Result += "\t0,\n";
6950
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006951 if (AllMethods.size() > 0) {
6952 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6953 Result += PDecl->getNameAsString();
6954 Result += "\n};\n";
6955 }
6956 else
6957 Result += "\t0\n};\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006958
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006959 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00006960 Result += "static ";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006961 Result += "struct _protocol_t *";
6962 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6963 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6964 Result += ";\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006965
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006966 // Mark this protocol as having been generated.
6967 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
6968 llvm_unreachable("protocol already synthesized");
6969
6970}
6971
6972void RewriteModernObjC::RewriteObjCProtocolListMetaData(
6973 const ObjCList<ObjCProtocolDecl> &Protocols,
6974 StringRef prefix, StringRef ClassName,
6975 std::string &Result) {
6976 if (Protocols.empty()) return;
6977
6978 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006979 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006980
6981 // Output the top lovel protocol meta-data for the class.
6982 /* struct _objc_protocol_list {
6983 struct _objc_protocol_list *next;
6984 int protocol_count;
6985 struct _objc_protocol *class_protocols[];
6986 }
6987 */
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006988 Result += "\n";
6989 if (LangOpts.MicrosoftExt)
6990 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
6991 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006992 Result += "\tstruct _objc_protocol_list *next;\n";
6993 Result += "\tint protocol_count;\n";
6994 Result += "\tstruct _objc_protocol *class_protocols[";
6995 Result += utostr(Protocols.size());
6996 Result += "];\n} _OBJC_";
6997 Result += prefix;
6998 Result += "_PROTOCOLS_";
6999 Result += ClassName;
7000 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
7001 "{\n\t0, ";
7002 Result += utostr(Protocols.size());
7003 Result += "\n";
7004
7005 Result += "\t,{&_OBJC_PROTOCOL_";
7006 Result += Protocols[0]->getNameAsString();
7007 Result += " \n";
7008
7009 for (unsigned i = 1; i != Protocols.size(); i++) {
7010 Result += "\t ,&_OBJC_PROTOCOL_";
7011 Result += Protocols[i]->getNameAsString();
7012 Result += "\n";
7013 }
7014 Result += "\t }\n};\n";
7015}
7016
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007017/// hasObjCExceptionAttribute - Return true if this class or any super
7018/// class has the __objc_exception__ attribute.
7019/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
7020static bool hasObjCExceptionAttribute(ASTContext &Context,
7021 const ObjCInterfaceDecl *OID) {
7022 if (OID->hasAttr<ObjCExceptionAttr>())
7023 return true;
7024 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
7025 return hasObjCExceptionAttribute(Context, Super);
7026 return false;
7027}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007028
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007029void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
7030 std::string &Result) {
7031 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7032
7033 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00007034 if (CDecl->isImplicitInterfaceDecl())
7035 assert(false &&
7036 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00007037
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00007038 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanianae932952012-02-10 20:47:10 +00007039 SmallVector<ObjCIvarDecl *, 8> IVars;
7040
7041 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7042 IVD; IVD = IVD->getNextIvar()) {
7043 // Ignore unnamed bit-fields.
7044 if (!IVD->getDeclName())
7045 continue;
7046 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007047 }
7048
Fariborz Jahanianae932952012-02-10 20:47:10 +00007049 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007050 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007051 CDecl);
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007052
7053 // Build _objc_method_list for class's instance methods if needed
7054 SmallVector<ObjCMethodDecl *, 32>
7055 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7056
7057 // If any of our property implementations have associated getters or
7058 // setters, produce metadata for them as well.
7059 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7060 PropEnd = IDecl->propimpl_end();
7061 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00007062 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007063 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007064 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007065 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007066 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007067 if (!PD)
7068 continue;
7069 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00007070 if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007071 InstanceMethods.push_back(Getter);
7072 if (PD->isReadOnly())
7073 continue;
7074 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00007075 if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007076 InstanceMethods.push_back(Setter);
7077 }
7078
7079 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7080 "_OBJC_$_INSTANCE_METHODS_",
7081 IDecl->getNameAsString(), true);
7082
7083 SmallVector<ObjCMethodDecl *, 32>
7084 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7085
7086 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7087 "_OBJC_$_CLASS_METHODS_",
7088 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00007089
7090 // Protocols referenced in class declaration?
7091 // Protocol's super protocol list
7092 std::vector<ObjCProtocolDecl *> RefedProtocols;
7093 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7094 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7095 E = Protocols.end();
7096 I != E; ++I) {
7097 RefedProtocols.push_back(*I);
7098 // Must write out all protocol definitions in current qualifier list,
7099 // and in their nested qualifiers before writing out current definition.
7100 RewriteObjCProtocolMetaData(*I, Result);
7101 }
7102
7103 Write_protocol_list_initializer(Context, Result,
7104 RefedProtocols,
7105 "_OBJC_CLASS_PROTOCOLS_$_",
7106 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007107
7108 // Protocol's property metadata.
7109 std::vector<ObjCPropertyDecl *> ClassProperties;
7110 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7111 E = CDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00007112 ClassProperties.push_back(*I);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007113
7114 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanian2df089d2012-03-22 17:39:35 +00007115 /* Container */IDecl,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00007116 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007117 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007118
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007119
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007120 // Data for initializing _class_ro_t metaclass meta-data
7121 uint32_t flags = CLS_META;
7122 std::string InstanceSize;
7123 std::string InstanceStart;
7124
7125
7126 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7127 if (classIsHidden)
7128 flags |= OBJC2_CLS_HIDDEN;
7129
7130 if (!CDecl->getSuperClass())
7131 // class is root
7132 flags |= CLS_ROOT;
7133 InstanceSize = "sizeof(struct _class_t)";
7134 InstanceStart = InstanceSize;
7135 Write__class_ro_t_initializer(Context, Result, flags,
7136 InstanceStart, InstanceSize,
7137 ClassMethods,
7138 0,
7139 0,
7140 0,
7141 "_OBJC_METACLASS_RO_$_",
7142 CDecl->getNameAsString());
7143
7144
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007145 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007146 flags = CLS;
7147 if (classIsHidden)
7148 flags |= OBJC2_CLS_HIDDEN;
7149
7150 if (hasObjCExceptionAttribute(*Context, CDecl))
7151 flags |= CLS_EXCEPTION;
7152
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007153 if (!CDecl->getSuperClass())
7154 // class is root
7155 flags |= CLS_ROOT;
7156
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007157 InstanceSize.clear();
7158 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007159 if (!ObjCSynthesizedStructs.count(CDecl)) {
7160 InstanceSize = "0";
7161 InstanceStart = "0";
7162 }
7163 else {
7164 InstanceSize = "sizeof(struct ";
7165 InstanceSize += CDecl->getNameAsString();
7166 InstanceSize += "_IMPL)";
7167
7168 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7169 if (IVD) {
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00007170 RewriteIvarOffsetComputation(IVD, InstanceStart);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007171 }
7172 else
7173 InstanceStart = InstanceSize;
7174 }
7175 Write__class_ro_t_initializer(Context, Result, flags,
7176 InstanceStart, InstanceSize,
7177 InstanceMethods,
7178 RefedProtocols,
7179 IVars,
7180 ClassProperties,
7181 "_OBJC_CLASS_RO_$_",
7182 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00007183
7184 Write_class_t(Context, Result,
7185 "OBJC_METACLASS_$_",
7186 CDecl, /*metaclass*/true);
7187
7188 Write_class_t(Context, Result,
7189 "OBJC_CLASS_$_",
7190 CDecl, /*metaclass*/false);
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007191
7192 if (ImplementationIsNonLazy(IDecl))
7193 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00007194
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007195}
7196
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007197void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7198 int ClsDefCount = ClassImplementation.size();
7199 if (!ClsDefCount)
7200 return;
7201 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7202 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7203 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7204 for (int i = 0; i < ClsDefCount; i++) {
7205 ObjCImplementationDecl *IDecl = ClassImplementation[i];
7206 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7207 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7208 Result += CDecl->getName(); Result += ",\n";
7209 }
7210 Result += "};\n";
7211}
7212
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007213void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7214 int ClsDefCount = ClassImplementation.size();
7215 int CatDefCount = CategoryImplementation.size();
7216
7217 // For each implemented class, write out all its meta data.
7218 for (int i = 0; i < ClsDefCount; i++)
7219 RewriteObjCClassMetaData(ClassImplementation[i], Result);
7220
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007221 RewriteClassSetupInitHook(Result);
7222
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007223 // For each implemented category, write out all its meta data.
7224 for (int i = 0; i < CatDefCount; i++)
7225 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7226
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007227 RewriteCategorySetupInitHook(Result);
7228
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007229 if (ClsDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007230 if (LangOpts.MicrosoftExt)
7231 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007232 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7233 Result += llvm::utostr(ClsDefCount); Result += "]";
7234 Result +=
7235 " __attribute__((used, section (\"__DATA, __objc_classlist,"
7236 "regular,no_dead_strip\")))= {\n";
7237 for (int i = 0; i < ClsDefCount; i++) {
7238 Result += "\t&OBJC_CLASS_$_";
7239 Result += ClassImplementation[i]->getNameAsString();
7240 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007241 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007242 Result += "};\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007243
7244 if (!DefinedNonLazyClasses.empty()) {
7245 if (LangOpts.MicrosoftExt)
7246 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7247 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7248 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7249 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7250 Result += ",\n";
7251 }
7252 Result += "};\n";
7253 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007254 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00007255
7256 if (CatDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007257 if (LangOpts.MicrosoftExt)
7258 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanian61186122012-02-17 18:40:41 +00007259 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7260 Result += llvm::utostr(CatDefCount); Result += "]";
7261 Result +=
7262 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7263 "regular,no_dead_strip\")))= {\n";
7264 for (int i = 0; i < CatDefCount; i++) {
7265 Result += "\t&_OBJC_$_CATEGORY_";
7266 Result +=
7267 CategoryImplementation[i]->getClassInterface()->getNameAsString();
7268 Result += "_$_";
7269 Result += CategoryImplementation[i]->getNameAsString();
7270 Result += ",\n";
7271 }
7272 Result += "};\n";
7273 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007274
7275 if (!DefinedNonLazyCategories.empty()) {
7276 if (LangOpts.MicrosoftExt)
7277 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7278 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7279 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7280 Result += "\t&_OBJC_$_CATEGORY_";
7281 Result +=
7282 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7283 Result += "_$_";
7284 Result += DefinedNonLazyCategories[i]->getNameAsString();
7285 Result += ",\n";
7286 }
7287 Result += "};\n";
7288 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007289}
7290
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007291void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7292 if (LangOpts.MicrosoftExt)
7293 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7294
7295 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7296 // version 0, ObjCABI is 2
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00007297 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007298}
7299
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007300/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7301/// implementation.
7302void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7303 std::string &Result) {
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00007304 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007305 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7306 // Find category declaration for this implementation.
Fariborz Jahanian61186122012-02-17 18:40:41 +00007307 ObjCCategoryDecl *CDecl=0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007308 for (CDecl = ClassDecl->getCategoryList(); CDecl;
7309 CDecl = CDecl->getNextClassCategory())
7310 if (CDecl->getIdentifier() == IDecl->getIdentifier())
7311 break;
7312
7313 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00007314 FullCategoryName += "_$_";
7315 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007316
7317 // Build _objc_method_list for class's instance methods if needed
7318 SmallVector<ObjCMethodDecl *, 32>
7319 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7320
7321 // If any of our property implementations have associated getters or
7322 // setters, produce metadata for them as well.
7323 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7324 PropEnd = IDecl->propimpl_end();
7325 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00007326 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007327 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007328 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007329 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007330 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007331 if (!PD)
7332 continue;
7333 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7334 InstanceMethods.push_back(Getter);
7335 if (PD->isReadOnly())
7336 continue;
7337 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7338 InstanceMethods.push_back(Setter);
7339 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007340
Fariborz Jahanian61186122012-02-17 18:40:41 +00007341 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7342 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7343 FullCategoryName, true);
7344
7345 SmallVector<ObjCMethodDecl *, 32>
7346 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7347
7348 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7349 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7350 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007351
7352 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00007353 // Protocol's super protocol list
7354 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00007355 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
7356 E = CDecl->protocol_end();
7357
7358 I != E; ++I) {
Fariborz Jahanian61186122012-02-17 18:40:41 +00007359 RefedProtocols.push_back(*I);
7360 // Must write out all protocol definitions in current qualifier list,
7361 // and in their nested qualifiers before writing out current definition.
7362 RewriteObjCProtocolMetaData(*I, Result);
7363 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007364
Fariborz Jahanian61186122012-02-17 18:40:41 +00007365 Write_protocol_list_initializer(Context, Result,
7366 RefedProtocols,
7367 "_OBJC_CATEGORY_PROTOCOLS_$_",
7368 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007369
Fariborz Jahanian61186122012-02-17 18:40:41 +00007370 // Protocol's property metadata.
7371 std::vector<ObjCPropertyDecl *> ClassProperties;
7372 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7373 E = CDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00007374 ClassProperties.push_back(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007375
Fariborz Jahanian61186122012-02-17 18:40:41 +00007376 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanianebfa2722012-05-03 23:19:33 +00007377 /* Container */IDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007378 "_OBJC_$_PROP_LIST_",
7379 FullCategoryName);
7380
7381 Write_category_t(*this, Context, Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007382 CDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007383 ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007384 InstanceMethods,
7385 ClassMethods,
7386 RefedProtocols,
7387 ClassProperties);
7388
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007389 // Determine if this category is also "non-lazy".
7390 if (ImplementationIsNonLazy(IDecl))
7391 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007392
7393}
7394
7395void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7396 int CatDefCount = CategoryImplementation.size();
7397 if (!CatDefCount)
7398 return;
7399 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7400 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7401 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7402 for (int i = 0; i < CatDefCount; i++) {
7403 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7404 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7405 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7406 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7407 Result += ClassDecl->getName();
7408 Result += "_$_";
7409 Result += CatDecl->getName();
7410 Result += ",\n";
7411 }
7412 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007413}
7414
7415// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7416/// class methods.
7417template<typename MethodIterator>
7418void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7419 MethodIterator MethodEnd,
7420 bool IsInstanceMethod,
7421 StringRef prefix,
7422 StringRef ClassName,
7423 std::string &Result) {
7424 if (MethodBegin == MethodEnd) return;
7425
7426 if (!objc_impl_method) {
7427 /* struct _objc_method {
7428 SEL _cmd;
7429 char *method_types;
7430 void *_imp;
7431 }
7432 */
7433 Result += "\nstruct _objc_method {\n";
7434 Result += "\tSEL _cmd;\n";
7435 Result += "\tchar *method_types;\n";
7436 Result += "\tvoid *_imp;\n";
7437 Result += "};\n";
7438
7439 objc_impl_method = true;
7440 }
7441
7442 // Build _objc_method_list for class's methods if needed
7443
7444 /* struct {
7445 struct _objc_method_list *next_method;
7446 int method_count;
7447 struct _objc_method method_list[];
7448 }
7449 */
7450 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007451 Result += "\n";
7452 if (LangOpts.MicrosoftExt) {
7453 if (IsInstanceMethod)
7454 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7455 else
7456 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7457 }
7458 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007459 Result += "\tstruct _objc_method_list *next_method;\n";
7460 Result += "\tint method_count;\n";
7461 Result += "\tstruct _objc_method method_list[";
7462 Result += utostr(NumMethods);
7463 Result += "];\n} _OBJC_";
7464 Result += prefix;
7465 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7466 Result += "_METHODS_";
7467 Result += ClassName;
7468 Result += " __attribute__ ((used, section (\"__OBJC, __";
7469 Result += IsInstanceMethod ? "inst" : "cls";
7470 Result += "_meth\")))= ";
7471 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7472
7473 Result += "\t,{{(SEL)\"";
7474 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7475 std::string MethodTypeString;
7476 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7477 Result += "\", \"";
7478 Result += MethodTypeString;
7479 Result += "\", (void *)";
7480 Result += MethodInternalNames[*MethodBegin];
7481 Result += "}\n";
7482 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7483 Result += "\t ,{(SEL)\"";
7484 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7485 std::string MethodTypeString;
7486 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7487 Result += "\", \"";
7488 Result += MethodTypeString;
7489 Result += "\", (void *)";
7490 Result += MethodInternalNames[*MethodBegin];
7491 Result += "}\n";
7492 }
7493 Result += "\t }\n};\n";
7494}
7495
7496Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7497 SourceRange OldRange = IV->getSourceRange();
7498 Expr *BaseExpr = IV->getBase();
7499
7500 // Rewrite the base, but without actually doing replaces.
7501 {
7502 DisableReplaceStmtScope S(*this);
7503 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7504 IV->setBase(BaseExpr);
7505 }
7506
7507 ObjCIvarDecl *D = IV->getDecl();
7508
7509 Expr *Replacement = IV;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007510
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007511 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7512 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +00007513 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007514 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7515 // lookup which class implements the instance variable.
7516 ObjCInterfaceDecl *clsDeclared = 0;
7517 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7518 clsDeclared);
7519 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7520
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007521 // Build name of symbol holding ivar offset.
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007522 std::string IvarOffsetName;
7523 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
7524
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00007525 ReferencedIvars[clsDeclared].insert(D);
7526
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007527 // cast offset to "char *".
7528 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7529 Context->getPointerType(Context->CharTy),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007530 CK_BitCast,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007531 BaseExpr);
7532 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7533 SourceLocation(), &Context->Idents.get(IvarOffsetName),
7534 Context->UnsignedLongTy, 0, SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00007535 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7536 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007537 SourceLocation());
7538 BinaryOperator *addExpr =
7539 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7540 Context->getPointerType(Context->CharTy),
Lang Hamesbe9af122012-10-02 04:45:10 +00007541 VK_RValue, OK_Ordinary, SourceLocation(), false);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007542 // Don't forget the parens to enforce the proper binding.
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007543 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7544 SourceLocation(),
7545 addExpr);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007546 QualType IvarT = D->getType();
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007547
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00007548 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007549 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00007550 RD = RD->getDefinition();
7551 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007552 // decltype(((Foo_IMPL*)0)->bar) *
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00007553 ObjCContainerDecl *CDecl =
7554 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7555 // ivar in class extensions requires special treatment.
7556 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7557 CDecl = CatDecl->getClassInterface();
7558 std::string RecName = CDecl->getName();
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007559 RecName += "_IMPL";
7560 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
7561 SourceLocation(), SourceLocation(),
7562 &Context->Idents.get(RecName.c_str()));
7563 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7564 unsigned UnsignedIntSize =
7565 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7566 Expr *Zero = IntegerLiteral::Create(*Context,
7567 llvm::APInt(UnsignedIntSize, 0),
7568 Context->UnsignedIntTy, SourceLocation());
7569 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7570 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7571 Zero);
7572 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7573 SourceLocation(),
7574 &Context->Idents.get(D->getNameAsString()),
7575 IvarT, 0,
7576 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00007577 ICIS_NoInit);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007578 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
7579 FD->getType(), VK_LValue,
7580 OK_Ordinary);
7581 IvarT = Context->getDecltypeType(ME, ME->getType());
7582 }
7583 }
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007584 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007585 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007586
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007587 castExpr = NoTypeInfoCStyleCastExpr(Context,
7588 castT,
7589 CK_BitCast,
7590 PE);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007591
7592
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007593 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007594 VK_LValue, OK_Ordinary,
7595 SourceLocation());
7596 PE = new (Context) ParenExpr(OldRange.getBegin(),
7597 OldRange.getEnd(),
7598 Exp);
7599
7600 Replacement = PE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007601 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007602
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007603 ReplaceStmtWithRange(IV, Replacement, OldRange);
7604 return Replacement;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007605}