blob: 644ac57a940ee038fad9fe69f8f4c623bbd335eb [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
14#include "clang/Rewrite/ASTConsumers.h"
15#include "clang/Rewrite/Rewriter.h"
16#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);
244 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
245 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();
281 void RewriteForwardClassDecl(DeclGroupRef D);
282 void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG);
283 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
284 const std::string &typedefString);
285 void RewriteImplementations();
286 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
287 ObjCImplementationDecl *IMD,
288 ObjCCategoryImplDecl *CID);
289 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
290 void RewriteImplementationDecl(Decl *Dcl);
291 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
292 ObjCMethodDecl *MDecl, std::string &ResultStr);
293 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
294 const FunctionType *&FPRetType);
295 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
296 ValueDecl *VD, bool def=false);
297 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
298 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
299 void RewriteForwardProtocolDecl(DeclGroupRef D);
300 void RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG);
301 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
302 void RewriteProperty(ObjCPropertyDecl *prop);
303 void RewriteFunctionDecl(FunctionDecl *FD);
304 void RewriteBlockPointerType(std::string& Str, QualType Type);
305 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +0000306 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000307 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
308 void RewriteTypeOfDecl(VarDecl *VD);
309 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000310
311 std::string getIvarAccessString(ObjCIvarDecl *D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000312
313 // Expression Rewriting.
314 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
315 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
316 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
317 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
318 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
319 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
320 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian55947042012-03-27 20:17:30 +0000321 Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
Patrick Beardeb382ec2012-04-19 00:25:12 +0000322 Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
Fariborz Jahanian86cff602012-03-30 23:35:47 +0000323 Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000324 Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000325 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000326 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian042b91d2012-05-23 23:47:20 +0000327 Stmt *RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000328 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
329 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
330 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
331 SourceLocation OrigEnd);
332 Stmt *RewriteBreakStmt(BreakStmt *S);
333 Stmt *RewriteContinueStmt(ContinueStmt *S);
334 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +0000335 void RewriteImplicitCastObjCExpr(CastExpr *IE);
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000336 void RewriteLinkageSpec(LinkageSpecDecl *LSD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000337
338 // Block rewriting.
339 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
340
341 // Block specific rewrite rules.
342 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +0000343 void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
John McCallf4b88a42012-03-10 09:33:50 +0000344 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000345 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
346 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
347
348 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
349 std::string &Result);
350
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000351 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
Fariborz Jahanianb68258f2012-05-01 17:46:45 +0000352 bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
Fariborz Jahanian8fba8942012-04-30 23:20:30 +0000353 bool &IsNamedDefinition);
354 void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
355 std::string &Result);
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000356
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +0000357 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
358
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000359 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
360 std::string &Result);
361
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000362 virtual void Initialize(ASTContext &context);
363
Benjamin Kramer48d798c2012-06-02 10:20:41 +0000364 // Misc. AST transformation routines. Sometimes they end up calling
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000365 // rewriting routines on the new ASTs.
366 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
367 Expr **args, unsigned nargs,
368 SourceLocation StartLoc=SourceLocation(),
369 SourceLocation EndLoc=SourceLocation());
370
371 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
372 SourceLocation StartLoc=SourceLocation(),
373 SourceLocation EndLoc=SourceLocation());
374
375 void SynthCountByEnumWithState(std::string &buf);
376 void SynthMsgSendFunctionDecl();
377 void SynthMsgSendSuperFunctionDecl();
378 void SynthMsgSendStretFunctionDecl();
379 void SynthMsgSendFpretFunctionDecl();
380 void SynthMsgSendSuperStretFunctionDecl();
381 void SynthGetClassFunctionDecl();
382 void SynthGetMetaClassFunctionDecl();
383 void SynthGetSuperClassFunctionDecl();
384 void SynthSelGetUidFunctionDecl();
385 void SynthSuperContructorFunctionDecl();
386
387 // Rewriting metadata
388 template<typename MethodIterator>
389 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
390 MethodIterator MethodEnd,
391 bool IsInstanceMethod,
392 StringRef prefix,
393 StringRef ClassName,
394 std::string &Result);
Fariborz Jahanianda9624a2012-02-08 19:53:58 +0000395 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
396 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000397 void RewriteObjCProtocolListMetaData(
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000398 const ObjCList<ObjCProtocolDecl> &Prots,
399 StringRef prefix, StringRef ClassName, std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000400 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000401 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000402 void RewriteClassSetupInitHook(std::string &Result);
Fariborz Jahaniane0335782012-03-27 18:41:05 +0000403
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000404 void RewriteMetaDataIntoBuffer(std::string &Result);
405 void WriteImageInfo(std::string &Result);
406 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000407 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000408 void RewriteCategorySetupInitHook(std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000409
410 // Rewriting ivar
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000411 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000412 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000413 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000414
415
416 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
417 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
418 StringRef funcName, std::string Tag);
419 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
420 StringRef funcName, std::string Tag);
421 std::string SynthesizeBlockImpl(BlockExpr *CE,
422 std::string Tag, std::string Desc);
423 std::string SynthesizeBlockDescriptor(std::string DescTag,
424 std::string ImplTag,
425 int i, StringRef funcName,
426 unsigned hasCopy);
427 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
428 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
429 StringRef FunName);
430 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
431 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +0000432 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000433
434 // Misc. helper routines.
435 QualType getProtocolType();
436 void WarnAboutReturnGotoStmts(Stmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000437 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
438 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
439 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
440
441 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
442 void CollectBlockDeclRefInfo(BlockExpr *Exp);
443 void GetBlockDeclRefExprs(Stmt *S);
444 void GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +0000445 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000446 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
447
448 // We avoid calling Type::isBlockPointerType(), since it operates on the
449 // canonical type. We only care if the top-level type is a closure pointer.
450 bool isTopLevelBlockPointerType(QualType T) {
451 return isa<BlockPointerType>(T);
452 }
453
454 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
455 /// to a function pointer type and upon success, returns true; false
456 /// otherwise.
457 bool convertBlockPointerToFunctionPointer(QualType &T) {
458 if (isTopLevelBlockPointerType(T)) {
459 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
460 T = Context->getPointerType(BPT->getPointeeType());
461 return true;
462 }
463 return false;
464 }
465
Fariborz Jahanian164d6f82012-02-13 18:57:49 +0000466 bool convertObjCTypeToCStyleType(QualType &T);
467
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000468 bool needToScanForQualifiers(QualType T);
469 QualType getSuperStructType();
470 QualType getConstantStringStructType();
471 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
472 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
473
474 void convertToUnqualifiedObjCType(QualType &T) {
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000475 if (T->isObjCQualifiedIdType()) {
476 bool isConst = T.isConstQualified();
477 T = isConst ? Context->getObjCIdType().withConst()
478 : Context->getObjCIdType();
479 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000480 else if (T->isObjCQualifiedClassType())
481 T = Context->getObjCClassType();
482 else if (T->isObjCObjectPointerType() &&
483 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
484 if (const ObjCObjectPointerType * OBJPT =
485 T->getAsObjCInterfacePointerType()) {
486 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
487 T = QualType(IFaceT, 0);
488 T = Context->getPointerType(T);
489 }
490 }
491 }
492
493 // FIXME: This predicate seems like it would be useful to add to ASTContext.
494 bool isObjCType(QualType T) {
495 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
496 return false;
497
498 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
499
500 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
501 OCT == Context->getCanonicalType(Context->getObjCClassType()))
502 return true;
503
504 if (const PointerType *PT = OCT->getAs<PointerType>()) {
505 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
506 PT->getPointeeType()->isObjCQualifiedIdType())
507 return true;
508 }
509 return false;
510 }
511 bool PointerTypeTakesAnyBlockArguments(QualType QT);
512 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
513 void GetExtentOfArgList(const char *Name, const char *&LParen,
514 const char *&RParen);
515
516 void QuoteDoublequotes(std::string &From, std::string &To) {
517 for (unsigned i = 0; i < From.length(); i++) {
518 if (From[i] == '"')
519 To += "\\\"";
520 else
521 To += From[i];
522 }
523 }
524
525 QualType getSimpleFunctionType(QualType result,
526 const QualType *args,
527 unsigned numArgs,
528 bool variadic = false) {
529 if (result == Context->getObjCInstanceType())
530 result = Context->getObjCIdType();
531 FunctionProtoType::ExtProtoInfo fpi;
532 fpi.Variadic = variadic;
533 return Context->getFunctionType(result, args, numArgs, fpi);
534 }
535
536 // Helper function: create a CStyleCastExpr with trivial type source info.
537 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
538 CastKind Kind, Expr *E) {
539 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
540 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
541 SourceLocation(), SourceLocation());
542 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000543
544 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
545 IdentifierInfo* II = &Context->Idents.get("load");
546 Selector LoadSel = Context->Selectors.getSelector(0, &II);
547 return OD->getClassMethod(LoadSel) != 0;
548 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000549 };
550
551}
552
553void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
554 NamedDecl *D) {
555 if (const FunctionProtoType *fproto
556 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
557 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
558 E = fproto->arg_type_end(); I && (I != E); ++I)
559 if (isTopLevelBlockPointerType(*I)) {
560 // All the args are checked/rewritten. Don't call twice!
561 RewriteBlockPointerDecl(D);
562 break;
563 }
564 }
565}
566
567void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
568 const PointerType *PT = funcType->getAs<PointerType>();
569 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
570 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
571}
572
573static bool IsHeaderFile(const std::string &Filename) {
574 std::string::size_type DotPos = Filename.rfind('.');
575
576 if (DotPos == std::string::npos) {
577 // no file extension
578 return false;
579 }
580
581 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
582 // C header: .h
583 // C++ header: .hh or .H;
584 return Ext == "h" || Ext == "hh" || Ext == "H";
585}
586
587RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
588 DiagnosticsEngine &D, const LangOptions &LOpts,
589 bool silenceMacroWarn)
590 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
591 SilenceRewriteMacroWarning(silenceMacroWarn) {
592 IsHeader = IsHeaderFile(inFile);
593 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
594 "rewriting sub-expression within a macro (may not be correct)");
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +0000595 // FIXME. This should be an error. But if block is not called, it is OK. And it
596 // may break including some headers.
597 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
598 "rewriting block literal declared in global scope is not implemented");
599
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000600 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
601 DiagnosticsEngine::Warning,
602 "rewriter doesn't support user-specified control flow semantics "
603 "for @try/@finally (code may not execute properly)");
604}
605
606ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
607 raw_ostream* OS,
608 DiagnosticsEngine &Diags,
609 const LangOptions &LOpts,
610 bool SilenceRewriteMacroWarning) {
611 return new RewriteModernObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
612}
613
614void RewriteModernObjC::InitializeCommon(ASTContext &context) {
615 Context = &context;
616 SM = &Context->getSourceManager();
617 TUDecl = Context->getTranslationUnitDecl();
618 MsgSendFunctionDecl = 0;
619 MsgSendSuperFunctionDecl = 0;
620 MsgSendStretFunctionDecl = 0;
621 MsgSendSuperStretFunctionDecl = 0;
622 MsgSendFpretFunctionDecl = 0;
623 GetClassFunctionDecl = 0;
624 GetMetaClassFunctionDecl = 0;
625 GetSuperClassFunctionDecl = 0;
626 SelGetUidFunctionDecl = 0;
627 CFStringFunctionDecl = 0;
628 ConstantStringClassReference = 0;
629 NSStringRecord = 0;
630 CurMethodDef = 0;
631 CurFunctionDef = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000632 GlobalVarDecl = 0;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +0000633 GlobalConstructionExp = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000634 SuperStructDecl = 0;
635 ProtocolTypeDecl = 0;
636 ConstantStringDecl = 0;
637 BcLabelCount = 0;
638 SuperContructorFunctionDecl = 0;
639 NumObjCStringLiterals = 0;
640 PropParentMap = 0;
641 CurrentBody = 0;
642 DisableReplaceStmt = false;
643 objc_impl_method = false;
644
645 // Get the ID and start/end of the main file.
646 MainFileID = SM->getMainFileID();
647 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
648 MainFileStart = MainBuf->getBufferStart();
649 MainFileEnd = MainBuf->getBufferEnd();
650
David Blaikie4e4d0842012-03-11 07:00:24 +0000651 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000652}
653
654//===----------------------------------------------------------------------===//
655// Top Level Driver Code
656//===----------------------------------------------------------------------===//
657
658void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
659 if (Diags.hasErrorOccurred())
660 return;
661
662 // Two cases: either the decl could be in the main file, or it could be in a
663 // #included file. If the former, rewrite it now. If the later, check to see
664 // if we rewrote the #include/#import.
665 SourceLocation Loc = D->getLocation();
666 Loc = SM->getExpansionLoc(Loc);
667
668 // If this is for a builtin, ignore it.
669 if (Loc.isInvalid()) return;
670
671 // Look for built-in declarations that we need to refer during the rewrite.
672 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
673 RewriteFunctionDecl(FD);
674 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
675 // declared in <Foundation/NSString.h>
676 if (FVD->getName() == "_NSConstantStringClassReference") {
677 ConstantStringClassReference = FVD;
678 return;
679 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000680 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
681 RewriteCategoryDecl(CD);
682 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
683 if (PD->isThisDeclarationADefinition())
684 RewriteProtocolDecl(PD);
685 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
Fariborz Jahanian8e86b2d2012-04-04 17:16:15 +0000686 // FIXME. This will not work in all situations and leaving it out
687 // is harmless.
688 // RewriteLinkageSpec(LSD);
689
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000690 // Recurse into linkage specifications
691 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
692 DIEnd = LSD->decls_end();
693 DI != DIEnd; ) {
694 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
695 if (!IFace->isThisDeclarationADefinition()) {
696 SmallVector<Decl *, 8> DG;
697 SourceLocation StartLoc = IFace->getLocStart();
698 do {
699 if (isa<ObjCInterfaceDecl>(*DI) &&
700 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
701 StartLoc == (*DI)->getLocStart())
702 DG.push_back(*DI);
703 else
704 break;
705
706 ++DI;
707 } while (DI != DIEnd);
708 RewriteForwardClassDecl(DG);
709 continue;
710 }
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000711 else {
712 // Keep track of all interface declarations seen.
713 ObjCInterfacesSeen.push_back(IFace);
714 ++DI;
715 continue;
716 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000717 }
718
719 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
720 if (!Proto->isThisDeclarationADefinition()) {
721 SmallVector<Decl *, 8> DG;
722 SourceLocation StartLoc = Proto->getLocStart();
723 do {
724 if (isa<ObjCProtocolDecl>(*DI) &&
725 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
726 StartLoc == (*DI)->getLocStart())
727 DG.push_back(*DI);
728 else
729 break;
730
731 ++DI;
732 } while (DI != DIEnd);
733 RewriteForwardProtocolDecl(DG);
734 continue;
735 }
736 }
737
738 HandleTopLevelSingleDecl(*DI);
739 ++DI;
740 }
741 }
742 // If we have a decl in the main file, see if we should rewrite it.
743 if (SM->isFromMainFile(Loc))
744 return HandleDeclInMainFile(D);
745}
746
747//===----------------------------------------------------------------------===//
748// Syntactic (non-AST) Rewriting Code
749//===----------------------------------------------------------------------===//
750
751void RewriteModernObjC::RewriteInclude() {
752 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
753 StringRef MainBuf = SM->getBufferData(MainFileID);
754 const char *MainBufStart = MainBuf.begin();
755 const char *MainBufEnd = MainBuf.end();
756 size_t ImportLen = strlen("import");
757
758 // Loop over the whole file, looking for includes.
759 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
760 if (*BufPtr == '#') {
761 if (++BufPtr == MainBufEnd)
762 return;
763 while (*BufPtr == ' ' || *BufPtr == '\t')
764 if (++BufPtr == MainBufEnd)
765 return;
766 if (!strncmp(BufPtr, "import", ImportLen)) {
767 // replace import with include
768 SourceLocation ImportLoc =
769 LocStart.getLocWithOffset(BufPtr-MainBufStart);
770 ReplaceText(ImportLoc, ImportLen, "include");
771 BufPtr += ImportLen;
772 }
773 }
774 }
775}
776
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000777static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
778 ObjCIvarDecl *IvarDecl, std::string &Result) {
779 Result += "OBJC_IVAR_$_";
780 Result += IDecl->getName();
781 Result += "$";
782 Result += IvarDecl->getName();
783}
784
785std::string
786RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
787 const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
788
789 // Build name of symbol holding ivar offset.
790 std::string IvarOffsetName;
791 WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
792
793
794 std::string S = "(*(";
795 QualType IvarT = D->getType();
796
797 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
798 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
799 RD = RD->getDefinition();
800 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
801 // decltype(((Foo_IMPL*)0)->bar) *
802 ObjCContainerDecl *CDecl =
803 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
804 // ivar in class extensions requires special treatment.
805 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
806 CDecl = CatDecl->getClassInterface();
807 std::string RecName = CDecl->getName();
808 RecName += "_IMPL";
809 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
810 SourceLocation(), SourceLocation(),
811 &Context->Idents.get(RecName.c_str()));
812 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
813 unsigned UnsignedIntSize =
814 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
815 Expr *Zero = IntegerLiteral::Create(*Context,
816 llvm::APInt(UnsignedIntSize, 0),
817 Context->UnsignedIntTy, SourceLocation());
818 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
819 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
820 Zero);
821 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
822 SourceLocation(),
823 &Context->Idents.get(D->getNameAsString()),
824 IvarT, 0,
825 /*BitWidth=*/0, /*Mutable=*/true,
826 /*HasInit=*/false);
827 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
828 FD->getType(), VK_LValue,
829 OK_Ordinary);
830 IvarT = Context->getDecltypeType(ME, ME->getType());
831 }
832 }
833 convertObjCTypeToCStyleType(IvarT);
834 QualType castT = Context->getPointerType(IvarT);
835 std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
836 S += TypeString;
837 S += ")";
838
839 // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
840 S += "((char *)self + ";
841 S += IvarOffsetName;
842 S += "))";
843 ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000844 return S;
845}
846
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000847/// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
848/// been found in the class implementation. In this case, it must be synthesized.
849static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
850 ObjCPropertyDecl *PD,
851 bool getter) {
852 return getter ? !IMP->getInstanceMethod(PD->getGetterName())
853 : !IMP->getInstanceMethod(PD->getSetterName());
854
855}
856
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000857void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
858 ObjCImplementationDecl *IMD,
859 ObjCCategoryImplDecl *CID) {
860 static bool objcGetPropertyDefined = false;
861 static bool objcSetPropertyDefined = false;
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000862 SourceLocation startGetterSetterLoc;
863
864 if (PID->getLocStart().isValid()) {
865 SourceLocation startLoc = PID->getLocStart();
866 InsertText(startLoc, "// ");
867 const char *startBuf = SM->getCharacterData(startLoc);
868 assert((*startBuf == '@') && "bogus @synthesize location");
869 const char *semiBuf = strchr(startBuf, ';');
870 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
871 startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
872 }
873 else
874 startGetterSetterLoc = IMD ? IMD->getLocEnd() : CID->getLocEnd();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000875
876 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
877 return; // FIXME: is this correct?
878
879 // Generate the 'getter' function.
880 ObjCPropertyDecl *PD = PID->getPropertyDecl();
881 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
882
883 if (!OID)
884 return;
885 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000886 if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000887 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
888 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
889 ObjCPropertyDecl::OBJC_PR_copy));
890 std::string Getr;
891 if (GenGetProperty && !objcGetPropertyDefined) {
892 objcGetPropertyDefined = true;
893 // FIXME. Is this attribute correct in all cases?
894 Getr = "\nextern \"C\" __declspec(dllimport) "
895 "id objc_getProperty(id, SEL, long, bool);\n";
896 }
897 RewriteObjCMethodDecl(OID->getContainingInterface(),
898 PD->getGetterMethodDecl(), Getr);
899 Getr += "{ ";
900 // Synthesize an explicit cast to gain access to the ivar.
901 // See objc-act.c:objc_synthesize_new_getter() for details.
902 if (GenGetProperty) {
903 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
904 Getr += "typedef ";
905 const FunctionType *FPRetType = 0;
906 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
907 FPRetType);
908 Getr += " _TYPE";
909 if (FPRetType) {
910 Getr += ")"; // close the precedence "scope" for "*".
911
912 // Now, emit the argument types (if any).
913 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
914 Getr += "(";
915 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
916 if (i) Getr += ", ";
917 std::string ParamStr = FT->getArgType(i).getAsString(
918 Context->getPrintingPolicy());
919 Getr += ParamStr;
920 }
921 if (FT->isVariadic()) {
922 if (FT->getNumArgs()) Getr += ", ";
923 Getr += "...";
924 }
925 Getr += ")";
926 } else
927 Getr += "()";
928 }
929 Getr += ";\n";
930 Getr += "return (_TYPE)";
931 Getr += "objc_getProperty(self, _cmd, ";
932 RewriteIvarOffsetComputation(OID, Getr);
933 Getr += ", 1)";
934 }
935 else
936 Getr += "return " + getIvarAccessString(OID);
937 Getr += "; }";
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000938 InsertText(startGetterSetterLoc, Getr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000939 }
940
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000941 if (PD->isReadOnly() ||
942 !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000943 return;
944
945 // Generate the 'setter' function.
946 std::string Setr;
947 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
948 ObjCPropertyDecl::OBJC_PR_copy);
949 if (GenSetProperty && !objcSetPropertyDefined) {
950 objcSetPropertyDefined = true;
951 // FIXME. Is this attribute correct in all cases?
952 Setr = "\nextern \"C\" __declspec(dllimport) "
953 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
954 }
955
956 RewriteObjCMethodDecl(OID->getContainingInterface(),
957 PD->getSetterMethodDecl(), Setr);
958 Setr += "{ ";
959 // Synthesize an explicit cast to initialize the ivar.
960 // See objc-act.c:objc_synthesize_new_setter() for details.
961 if (GenSetProperty) {
962 Setr += "objc_setProperty (self, _cmd, ";
963 RewriteIvarOffsetComputation(OID, Setr);
964 Setr += ", (id)";
965 Setr += PD->getName();
966 Setr += ", ";
967 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
968 Setr += "0, ";
969 else
970 Setr += "1, ";
971 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
972 Setr += "1)";
973 else
974 Setr += "0)";
975 }
976 else {
977 Setr += getIvarAccessString(OID) + " = ";
978 Setr += PD->getName();
979 }
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000980 Setr += "; }\n";
981 InsertText(startGetterSetterLoc, Setr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000982}
983
984static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
985 std::string &typedefString) {
986 typedefString += "#ifndef _REWRITER_typedef_";
987 typedefString += ForwardDecl->getNameAsString();
988 typedefString += "\n";
989 typedefString += "#define _REWRITER_typedef_";
990 typedefString += ForwardDecl->getNameAsString();
991 typedefString += "\n";
992 typedefString += "typedef struct objc_object ";
993 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +0000994 // typedef struct { } _objc_exc_Classname;
995 typedefString += ";\ntypedef struct {} _objc_exc_";
996 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000997 typedefString += ";\n#endif\n";
998}
999
1000void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
1001 const std::string &typedefString) {
1002 SourceLocation startLoc = ClassDecl->getLocStart();
1003 const char *startBuf = SM->getCharacterData(startLoc);
1004 const char *semiPtr = strchr(startBuf, ';');
1005 // Replace the @class with typedefs corresponding to the classes.
1006 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
1007}
1008
1009void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
1010 std::string typedefString;
1011 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
1012 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
1013 if (I == D.begin()) {
1014 // Translate to typedef's that forward reference structs with the same name
1015 // as the class. As a convenience, we include the original declaration
1016 // as a comment.
1017 typedefString += "// @class ";
1018 typedefString += ForwardDecl->getNameAsString();
1019 typedefString += ";\n";
1020 }
1021 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1022 }
1023 DeclGroupRef::iterator I = D.begin();
1024 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
1025}
1026
1027void RewriteModernObjC::RewriteForwardClassDecl(
1028 const llvm::SmallVector<Decl*, 8> &D) {
1029 std::string typedefString;
1030 for (unsigned i = 0; i < D.size(); i++) {
1031 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
1032 if (i == 0) {
1033 typedefString += "// @class ";
1034 typedefString += ForwardDecl->getNameAsString();
1035 typedefString += ";\n";
1036 }
1037 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1038 }
1039 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
1040}
1041
1042void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
1043 // When method is a synthesized one, such as a getter/setter there is
1044 // nothing to rewrite.
1045 if (Method->isImplicit())
1046 return;
1047 SourceLocation LocStart = Method->getLocStart();
1048 SourceLocation LocEnd = Method->getLocEnd();
1049
1050 if (SM->getExpansionLineNumber(LocEnd) >
1051 SM->getExpansionLineNumber(LocStart)) {
1052 InsertText(LocStart, "#if 0\n");
1053 ReplaceText(LocEnd, 1, ";\n#endif\n");
1054 } else {
1055 InsertText(LocStart, "// ");
1056 }
1057}
1058
1059void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
1060 SourceLocation Loc = prop->getAtLoc();
1061
1062 ReplaceText(Loc, 0, "// ");
1063 // FIXME: handle properties that are declared across multiple lines.
1064}
1065
1066void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
1067 SourceLocation LocStart = CatDecl->getLocStart();
1068
1069 // FIXME: handle category headers that are declared across multiple lines.
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001070 if (CatDecl->getIvarRBraceLoc().isValid()) {
1071 ReplaceText(LocStart, 1, "/** ");
1072 ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1073 }
1074 else {
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001075 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001076 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001077
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001078 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
1079 E = CatDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001080 RewriteProperty(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001081
1082 for (ObjCCategoryDecl::instmeth_iterator
1083 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
1084 I != E; ++I)
1085 RewriteMethodDeclaration(*I);
1086 for (ObjCCategoryDecl::classmeth_iterator
1087 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
1088 I != E; ++I)
1089 RewriteMethodDeclaration(*I);
1090
1091 // Lastly, comment out the @end.
1092 ReplaceText(CatDecl->getAtEndRange().getBegin(),
1093 strlen("@end"), "/* @end */");
1094}
1095
1096void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1097 SourceLocation LocStart = PDecl->getLocStart();
1098 assert(PDecl->isThisDeclarationADefinition());
1099
1100 // FIXME: handle protocol headers that are declared across multiple lines.
1101 ReplaceText(LocStart, 0, "// ");
1102
1103 for (ObjCProtocolDecl::instmeth_iterator
1104 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
1105 I != E; ++I)
1106 RewriteMethodDeclaration(*I);
1107 for (ObjCProtocolDecl::classmeth_iterator
1108 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1109 I != E; ++I)
1110 RewriteMethodDeclaration(*I);
1111
1112 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1113 E = PDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001114 RewriteProperty(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001115
1116 // Lastly, comment out the @end.
1117 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1118 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
1119
1120 // Must comment out @optional/@required
1121 const char *startBuf = SM->getCharacterData(LocStart);
1122 const char *endBuf = SM->getCharacterData(LocEnd);
1123 for (const char *p = startBuf; p < endBuf; p++) {
1124 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1125 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1126 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1127
1128 }
1129 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1130 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1131 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1132
1133 }
1134 }
1135}
1136
1137void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1138 SourceLocation LocStart = (*D.begin())->getLocStart();
1139 if (LocStart.isInvalid())
1140 llvm_unreachable("Invalid SourceLocation");
1141 // FIXME: handle forward protocol that are declared across multiple lines.
1142 ReplaceText(LocStart, 0, "// ");
1143}
1144
1145void
1146RewriteModernObjC::RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG) {
1147 SourceLocation LocStart = DG[0]->getLocStart();
1148 if (LocStart.isInvalid())
1149 llvm_unreachable("Invalid SourceLocation");
1150 // FIXME: handle forward protocol that are declared across multiple lines.
1151 ReplaceText(LocStart, 0, "// ");
1152}
1153
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +00001154void
1155RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
1156 SourceLocation LocStart = LSD->getExternLoc();
1157 if (LocStart.isInvalid())
1158 llvm_unreachable("Invalid extern SourceLocation");
1159
1160 ReplaceText(LocStart, 0, "// ");
1161 if (!LSD->hasBraces())
1162 return;
1163 // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
1164 SourceLocation LocRBrace = LSD->getRBraceLoc();
1165 if (LocRBrace.isInvalid())
1166 llvm_unreachable("Invalid rbrace SourceLocation");
1167 ReplaceText(LocRBrace, 0, "// ");
1168}
1169
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001170void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1171 const FunctionType *&FPRetType) {
1172 if (T->isObjCQualifiedIdType())
1173 ResultStr += "id";
1174 else if (T->isFunctionPointerType() ||
1175 T->isBlockPointerType()) {
1176 // needs special handling, since pointer-to-functions have special
1177 // syntax (where a decaration models use).
1178 QualType retType = T;
1179 QualType PointeeTy;
1180 if (const PointerType* PT = retType->getAs<PointerType>())
1181 PointeeTy = PT->getPointeeType();
1182 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1183 PointeeTy = BPT->getPointeeType();
1184 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1185 ResultStr += FPRetType->getResultType().getAsString(
1186 Context->getPrintingPolicy());
1187 ResultStr += "(*";
1188 }
1189 } else
1190 ResultStr += T.getAsString(Context->getPrintingPolicy());
1191}
1192
1193void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1194 ObjCMethodDecl *OMD,
1195 std::string &ResultStr) {
1196 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1197 const FunctionType *FPRetType = 0;
1198 ResultStr += "\nstatic ";
1199 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1200 ResultStr += " ";
1201
1202 // Unique method name
1203 std::string NameStr;
1204
1205 if (OMD->isInstanceMethod())
1206 NameStr += "_I_";
1207 else
1208 NameStr += "_C_";
1209
1210 NameStr += IDecl->getNameAsString();
1211 NameStr += "_";
1212
1213 if (ObjCCategoryImplDecl *CID =
1214 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1215 NameStr += CID->getNameAsString();
1216 NameStr += "_";
1217 }
1218 // Append selector names, replacing ':' with '_'
1219 {
1220 std::string selString = OMD->getSelector().getAsString();
1221 int len = selString.size();
1222 for (int i = 0; i < len; i++)
1223 if (selString[i] == ':')
1224 selString[i] = '_';
1225 NameStr += selString;
1226 }
1227 // Remember this name for metadata emission
1228 MethodInternalNames[OMD] = NameStr;
1229 ResultStr += NameStr;
1230
1231 // Rewrite arguments
1232 ResultStr += "(";
1233
1234 // invisible arguments
1235 if (OMD->isInstanceMethod()) {
1236 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1237 selfTy = Context->getPointerType(selfTy);
1238 if (!LangOpts.MicrosoftExt) {
1239 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1240 ResultStr += "struct ";
1241 }
1242 // When rewriting for Microsoft, explicitly omit the structure name.
1243 ResultStr += IDecl->getNameAsString();
1244 ResultStr += " *";
1245 }
1246 else
1247 ResultStr += Context->getObjCClassType().getAsString(
1248 Context->getPrintingPolicy());
1249
1250 ResultStr += " self, ";
1251 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1252 ResultStr += " _cmd";
1253
1254 // Method arguments.
1255 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1256 E = OMD->param_end(); PI != E; ++PI) {
1257 ParmVarDecl *PDecl = *PI;
1258 ResultStr += ", ";
1259 if (PDecl->getType()->isObjCQualifiedIdType()) {
1260 ResultStr += "id ";
1261 ResultStr += PDecl->getNameAsString();
1262 } else {
1263 std::string Name = PDecl->getNameAsString();
1264 QualType QT = PDecl->getType();
1265 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian2610f902012-03-27 16:42:20 +00001266 (void)convertBlockPointerToFunctionPointer(QT);
1267 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001268 ResultStr += Name;
1269 }
1270 }
1271 if (OMD->isVariadic())
1272 ResultStr += ", ...";
1273 ResultStr += ") ";
1274
1275 if (FPRetType) {
1276 ResultStr += ")"; // close the precedence "scope" for "*".
1277
1278 // Now, emit the argument types (if any).
1279 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1280 ResultStr += "(";
1281 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1282 if (i) ResultStr += ", ";
1283 std::string ParamStr = FT->getArgType(i).getAsString(
1284 Context->getPrintingPolicy());
1285 ResultStr += ParamStr;
1286 }
1287 if (FT->isVariadic()) {
1288 if (FT->getNumArgs()) ResultStr += ", ";
1289 ResultStr += "...";
1290 }
1291 ResultStr += ")";
1292 } else {
1293 ResultStr += "()";
1294 }
1295 }
1296}
1297void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1298 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1299 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1300
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001301 if (IMD) {
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001302 if (IMD->getIvarRBraceLoc().isValid()) {
1303 ReplaceText(IMD->getLocStart(), 1, "/** ");
1304 ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001305 }
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001306 else {
1307 InsertText(IMD->getLocStart(), "// ");
1308 }
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001309 }
1310 else
1311 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001312
1313 for (ObjCCategoryImplDecl::instmeth_iterator
1314 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1315 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1316 I != E; ++I) {
1317 std::string ResultStr;
1318 ObjCMethodDecl *OMD = *I;
1319 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1320 SourceLocation LocStart = OMD->getLocStart();
1321 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1322
1323 const char *startBuf = SM->getCharacterData(LocStart);
1324 const char *endBuf = SM->getCharacterData(LocEnd);
1325 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1326 }
1327
1328 for (ObjCCategoryImplDecl::classmeth_iterator
1329 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1330 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1331 I != E; ++I) {
1332 std::string ResultStr;
1333 ObjCMethodDecl *OMD = *I;
1334 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1335 SourceLocation LocStart = OMD->getLocStart();
1336 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1337
1338 const char *startBuf = SM->getCharacterData(LocStart);
1339 const char *endBuf = SM->getCharacterData(LocEnd);
1340 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1341 }
1342 for (ObjCCategoryImplDecl::propimpl_iterator
1343 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1344 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1345 I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001346 RewritePropertyImplDecl(*I, IMD, CID);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001347 }
1348
1349 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1350}
1351
1352void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00001353 // Do not synthesize more than once.
1354 if (ObjCSynthesizedStructs.count(ClassDecl))
1355 return;
1356 // Make sure super class's are written before current class is written.
1357 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1358 while (SuperClass) {
1359 RewriteInterfaceDecl(SuperClass);
1360 SuperClass = SuperClass->getSuperClass();
1361 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001362 std::string ResultStr;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001363 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001364 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001365 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00001366 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1367
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001368 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001369 // Mark this typedef as having been written into its c++ equivalent.
1370 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001371
1372 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001373 E = ClassDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001374 RewriteProperty(*I);
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001375 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001376 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001377 I != E; ++I)
1378 RewriteMethodDeclaration(*I);
1379 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001380 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001381 I != E; ++I)
1382 RewriteMethodDeclaration(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001383
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001384 // Lastly, comment out the @end.
1385 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1386 "/* @end */");
1387 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001388}
1389
1390Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1391 SourceRange OldRange = PseudoOp->getSourceRange();
1392
1393 // We just magically know some things about the structure of this
1394 // expression.
1395 ObjCMessageExpr *OldMsg =
1396 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1397 PseudoOp->getNumSemanticExprs() - 1));
1398
1399 // Because the rewriter doesn't allow us to rewrite rewritten code,
1400 // we need to suppress rewriting the sub-statements.
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001401 Expr *Base;
1402 SmallVector<Expr*, 2> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001403 {
1404 DisableReplaceStmtScope S(*this);
1405
1406 // Rebuild the base expression if we have one.
1407 Base = 0;
1408 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1409 Base = OldMsg->getInstanceReceiver();
1410 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1411 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1412 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001413
1414 unsigned numArgs = OldMsg->getNumArgs();
1415 for (unsigned i = 0; i < numArgs; i++) {
1416 Expr *Arg = OldMsg->getArg(i);
1417 if (isa<OpaqueValueExpr>(Arg))
1418 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1419 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1420 Args.push_back(Arg);
1421 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001422 }
1423
1424 // TODO: avoid this copy.
1425 SmallVector<SourceLocation, 1> SelLocs;
1426 OldMsg->getSelectorLocs(SelLocs);
1427
1428 ObjCMessageExpr *NewMsg = 0;
1429 switch (OldMsg->getReceiverKind()) {
1430 case ObjCMessageExpr::Class:
1431 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1432 OldMsg->getValueKind(),
1433 OldMsg->getLeftLoc(),
1434 OldMsg->getClassReceiverTypeInfo(),
1435 OldMsg->getSelector(),
1436 SelLocs,
1437 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001438 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001439 OldMsg->getRightLoc(),
1440 OldMsg->isImplicit());
1441 break;
1442
1443 case ObjCMessageExpr::Instance:
1444 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1445 OldMsg->getValueKind(),
1446 OldMsg->getLeftLoc(),
1447 Base,
1448 OldMsg->getSelector(),
1449 SelLocs,
1450 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001451 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001452 OldMsg->getRightLoc(),
1453 OldMsg->isImplicit());
1454 break;
1455
1456 case ObjCMessageExpr::SuperClass:
1457 case ObjCMessageExpr::SuperInstance:
1458 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1459 OldMsg->getValueKind(),
1460 OldMsg->getLeftLoc(),
1461 OldMsg->getSuperLoc(),
1462 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1463 OldMsg->getSuperType(),
1464 OldMsg->getSelector(),
1465 SelLocs,
1466 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001467 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001468 OldMsg->getRightLoc(),
1469 OldMsg->isImplicit());
1470 break;
1471 }
1472
1473 Stmt *Replacement = SynthMessageExpr(NewMsg);
1474 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1475 return Replacement;
1476}
1477
1478Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1479 SourceRange OldRange = PseudoOp->getSourceRange();
1480
1481 // We just magically know some things about the structure of this
1482 // expression.
1483 ObjCMessageExpr *OldMsg =
1484 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1485
1486 // Because the rewriter doesn't allow us to rewrite rewritten code,
1487 // we need to suppress rewriting the sub-statements.
1488 Expr *Base = 0;
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001489 SmallVector<Expr*, 1> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001490 {
1491 DisableReplaceStmtScope S(*this);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001492 // Rebuild the base expression if we have one.
1493 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1494 Base = OldMsg->getInstanceReceiver();
1495 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1496 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1497 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001498 unsigned numArgs = OldMsg->getNumArgs();
1499 for (unsigned i = 0; i < numArgs; i++) {
1500 Expr *Arg = OldMsg->getArg(i);
1501 if (isa<OpaqueValueExpr>(Arg))
1502 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1503 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1504 Args.push_back(Arg);
1505 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001506 }
1507
1508 // Intentionally empty.
1509 SmallVector<SourceLocation, 1> SelLocs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001510
1511 ObjCMessageExpr *NewMsg = 0;
1512 switch (OldMsg->getReceiverKind()) {
1513 case ObjCMessageExpr::Class:
1514 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1515 OldMsg->getValueKind(),
1516 OldMsg->getLeftLoc(),
1517 OldMsg->getClassReceiverTypeInfo(),
1518 OldMsg->getSelector(),
1519 SelLocs,
1520 OldMsg->getMethodDecl(),
1521 Args,
1522 OldMsg->getRightLoc(),
1523 OldMsg->isImplicit());
1524 break;
1525
1526 case ObjCMessageExpr::Instance:
1527 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1528 OldMsg->getValueKind(),
1529 OldMsg->getLeftLoc(),
1530 Base,
1531 OldMsg->getSelector(),
1532 SelLocs,
1533 OldMsg->getMethodDecl(),
1534 Args,
1535 OldMsg->getRightLoc(),
1536 OldMsg->isImplicit());
1537 break;
1538
1539 case ObjCMessageExpr::SuperClass:
1540 case ObjCMessageExpr::SuperInstance:
1541 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1542 OldMsg->getValueKind(),
1543 OldMsg->getLeftLoc(),
1544 OldMsg->getSuperLoc(),
1545 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1546 OldMsg->getSuperType(),
1547 OldMsg->getSelector(),
1548 SelLocs,
1549 OldMsg->getMethodDecl(),
1550 Args,
1551 OldMsg->getRightLoc(),
1552 OldMsg->isImplicit());
1553 break;
1554 }
1555
1556 Stmt *Replacement = SynthMessageExpr(NewMsg);
1557 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1558 return Replacement;
1559}
1560
1561/// SynthCountByEnumWithState - To print:
1562/// ((unsigned int (*)
1563/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1564/// (void *)objc_msgSend)((id)l_collection,
1565/// sel_registerName(
1566/// "countByEnumeratingWithState:objects:count:"),
1567/// &enumState,
1568/// (id *)__rw_items, (unsigned int)16)
1569///
1570void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1571 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1572 "id *, unsigned int))(void *)objc_msgSend)";
1573 buf += "\n\t\t";
1574 buf += "((id)l_collection,\n\t\t";
1575 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1576 buf += "\n\t\t";
1577 buf += "&enumState, "
1578 "(id *)__rw_items, (unsigned int)16)";
1579}
1580
1581/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1582/// statement to exit to its outer synthesized loop.
1583///
1584Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1585 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1586 return S;
1587 // replace break with goto __break_label
1588 std::string buf;
1589
1590 SourceLocation startLoc = S->getLocStart();
1591 buf = "goto __break_label_";
1592 buf += utostr(ObjCBcLabelNo.back());
1593 ReplaceText(startLoc, strlen("break"), buf);
1594
1595 return 0;
1596}
1597
1598/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1599/// statement to continue with its inner synthesized loop.
1600///
1601Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1602 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1603 return S;
1604 // replace continue with goto __continue_label
1605 std::string buf;
1606
1607 SourceLocation startLoc = S->getLocStart();
1608 buf = "goto __continue_label_";
1609 buf += utostr(ObjCBcLabelNo.back());
1610 ReplaceText(startLoc, strlen("continue"), buf);
1611
1612 return 0;
1613}
1614
1615/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1616/// It rewrites:
1617/// for ( type elem in collection) { stmts; }
1618
1619/// Into:
1620/// {
1621/// type elem;
1622/// struct __objcFastEnumerationState enumState = { 0 };
1623/// id __rw_items[16];
1624/// id l_collection = (id)collection;
1625/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1626/// objects:__rw_items count:16];
1627/// if (limit) {
1628/// unsigned long startMutations = *enumState.mutationsPtr;
1629/// do {
1630/// unsigned long counter = 0;
1631/// do {
1632/// if (startMutations != *enumState.mutationsPtr)
1633/// objc_enumerationMutation(l_collection);
1634/// elem = (type)enumState.itemsPtr[counter++];
1635/// stmts;
1636/// __continue_label: ;
1637/// } while (counter < limit);
1638/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1639/// objects:__rw_items count:16]);
1640/// elem = nil;
1641/// __break_label: ;
1642/// }
1643/// else
1644/// elem = nil;
1645/// }
1646///
1647Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1648 SourceLocation OrigEnd) {
1649 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1650 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1651 "ObjCForCollectionStmt Statement stack mismatch");
1652 assert(!ObjCBcLabelNo.empty() &&
1653 "ObjCForCollectionStmt - Label No stack empty");
1654
1655 SourceLocation startLoc = S->getLocStart();
1656 const char *startBuf = SM->getCharacterData(startLoc);
1657 StringRef elementName;
1658 std::string elementTypeAsString;
1659 std::string buf;
1660 buf = "\n{\n\t";
1661 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1662 // type elem;
1663 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1664 QualType ElementType = cast<ValueDecl>(D)->getType();
1665 if (ElementType->isObjCQualifiedIdType() ||
1666 ElementType->isObjCQualifiedInterfaceType())
1667 // Simply use 'id' for all qualified types.
1668 elementTypeAsString = "id";
1669 else
1670 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1671 buf += elementTypeAsString;
1672 buf += " ";
1673 elementName = D->getName();
1674 buf += elementName;
1675 buf += ";\n\t";
1676 }
1677 else {
1678 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1679 elementName = DR->getDecl()->getName();
1680 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1681 if (VD->getType()->isObjCQualifiedIdType() ||
1682 VD->getType()->isObjCQualifiedInterfaceType())
1683 // Simply use 'id' for all qualified types.
1684 elementTypeAsString = "id";
1685 else
1686 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1687 }
1688
1689 // struct __objcFastEnumerationState enumState = { 0 };
1690 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1691 // id __rw_items[16];
1692 buf += "id __rw_items[16];\n\t";
1693 // id l_collection = (id)
1694 buf += "id l_collection = (id)";
1695 // Find start location of 'collection' the hard way!
1696 const char *startCollectionBuf = startBuf;
1697 startCollectionBuf += 3; // skip 'for'
1698 startCollectionBuf = strchr(startCollectionBuf, '(');
1699 startCollectionBuf++; // skip '('
1700 // find 'in' and skip it.
1701 while (*startCollectionBuf != ' ' ||
1702 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1703 (*(startCollectionBuf+3) != ' ' &&
1704 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1705 startCollectionBuf++;
1706 startCollectionBuf += 3;
1707
1708 // Replace: "for (type element in" with string constructed thus far.
1709 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1710 // Replace ')' in for '(' type elem in collection ')' with ';'
1711 SourceLocation rightParenLoc = S->getRParenLoc();
1712 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1713 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1714 buf = ";\n\t";
1715
1716 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1717 // objects:__rw_items count:16];
1718 // which is synthesized into:
1719 // unsigned int limit =
1720 // ((unsigned int (*)
1721 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1722 // (void *)objc_msgSend)((id)l_collection,
1723 // sel_registerName(
1724 // "countByEnumeratingWithState:objects:count:"),
1725 // (struct __objcFastEnumerationState *)&state,
1726 // (id *)__rw_items, (unsigned int)16);
1727 buf += "unsigned long limit =\n\t\t";
1728 SynthCountByEnumWithState(buf);
1729 buf += ";\n\t";
1730 /// if (limit) {
1731 /// unsigned long startMutations = *enumState.mutationsPtr;
1732 /// do {
1733 /// unsigned long counter = 0;
1734 /// do {
1735 /// if (startMutations != *enumState.mutationsPtr)
1736 /// objc_enumerationMutation(l_collection);
1737 /// elem = (type)enumState.itemsPtr[counter++];
1738 buf += "if (limit) {\n\t";
1739 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1740 buf += "do {\n\t\t";
1741 buf += "unsigned long counter = 0;\n\t\t";
1742 buf += "do {\n\t\t\t";
1743 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1744 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1745 buf += elementName;
1746 buf += " = (";
1747 buf += elementTypeAsString;
1748 buf += ")enumState.itemsPtr[counter++];";
1749 // Replace ')' in for '(' type elem in collection ')' with all of these.
1750 ReplaceText(lparenLoc, 1, buf);
1751
1752 /// __continue_label: ;
1753 /// } while (counter < limit);
1754 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1755 /// objects:__rw_items count:16]);
1756 /// elem = nil;
1757 /// __break_label: ;
1758 /// }
1759 /// else
1760 /// elem = nil;
1761 /// }
1762 ///
1763 buf = ";\n\t";
1764 buf += "__continue_label_";
1765 buf += utostr(ObjCBcLabelNo.back());
1766 buf += ": ;";
1767 buf += "\n\t\t";
1768 buf += "} while (counter < limit);\n\t";
1769 buf += "} while (limit = ";
1770 SynthCountByEnumWithState(buf);
1771 buf += ");\n\t";
1772 buf += elementName;
1773 buf += " = ((";
1774 buf += elementTypeAsString;
1775 buf += ")0);\n\t";
1776 buf += "__break_label_";
1777 buf += utostr(ObjCBcLabelNo.back());
1778 buf += ": ;\n\t";
1779 buf += "}\n\t";
1780 buf += "else\n\t\t";
1781 buf += elementName;
1782 buf += " = ((";
1783 buf += elementTypeAsString;
1784 buf += ")0);\n\t";
1785 buf += "}\n";
1786
1787 // Insert all these *after* the statement body.
1788 // FIXME: If this should support Obj-C++, support CXXTryStmt
1789 if (isa<CompoundStmt>(S->getBody())) {
1790 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1791 InsertText(endBodyLoc, buf);
1792 } else {
1793 /* Need to treat single statements specially. For example:
1794 *
1795 * for (A *a in b) if (stuff()) break;
1796 * for (A *a in b) xxxyy;
1797 *
1798 * The following code simply scans ahead to the semi to find the actual end.
1799 */
1800 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1801 const char *semiBuf = strchr(stmtBuf, ';');
1802 assert(semiBuf && "Can't find ';'");
1803 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1804 InsertText(endBodyLoc, buf);
1805 }
1806 Stmts.pop_back();
1807 ObjCBcLabelNo.pop_back();
1808 return 0;
1809}
1810
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001811static void Write_RethrowObject(std::string &buf) {
1812 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1813 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1814 buf += "\tid rethrow;\n";
1815 buf += "\t} _fin_force_rethow(_rethrow);";
1816}
1817
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001818/// RewriteObjCSynchronizedStmt -
1819/// This routine rewrites @synchronized(expr) stmt;
1820/// into:
1821/// objc_sync_enter(expr);
1822/// @try stmt @finally { objc_sync_exit(expr); }
1823///
1824Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1825 // Get the start location and compute the semi location.
1826 SourceLocation startLoc = S->getLocStart();
1827 const char *startBuf = SM->getCharacterData(startLoc);
1828
1829 assert((*startBuf == '@') && "bogus @synchronized location");
1830
1831 std::string buf;
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001832 buf = "{ id _rethrow = 0; id _sync_obj = ";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001833
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001834 const char *lparenBuf = startBuf;
1835 while (*lparenBuf != '(') lparenBuf++;
1836 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001837
1838 buf = "; objc_sync_enter(_sync_obj);\n";
1839 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1840 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1841 buf += "\n\tid sync_exit;";
1842 buf += "\n\t} _sync_exit(_sync_obj);\n";
1843
1844 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1845 // the sync expression is typically a message expression that's already
1846 // been rewritten! (which implies the SourceLocation's are invalid).
1847 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1848 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1849 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1850 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1851
1852 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1853 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1854 assert (*LBraceLocBuf == '{');
1855 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001856
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001857 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay9ab511c2012-03-16 22:20:39 +00001858 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1859 "bogus @synchronized block");
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001860
1861 buf = "} catch (id e) {_rethrow = e;}\n";
1862 Write_RethrowObject(buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001863 buf += "}\n";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001864 buf += "}\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001865
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001866 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001867
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001868 return 0;
1869}
1870
1871void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1872{
1873 // Perform a bottom up traversal of all children.
1874 for (Stmt::child_range CI = S->children(); CI; ++CI)
1875 if (*CI)
1876 WarnAboutReturnGotoStmts(*CI);
1877
1878 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1879 Diags.Report(Context->getFullLoc(S->getLocStart()),
1880 TryFinallyContainsReturnDiag);
1881 }
1882 return;
1883}
1884
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00001885Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
1886 SourceLocation startLoc = S->getAtLoc();
1887 ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
Fariborz Jahanianc9b72b62012-05-24 22:59:56 +00001888 ReplaceText(S->getSubStmt()->getLocStart(), 1,
1889 "{ __AtAutoreleasePool __autoreleasepool; ");
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00001890
1891 return 0;
1892}
1893
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001894Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001895 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001896 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001897 std::string buf;
1898
1899 if (finalStmt) {
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001900 if (noCatch)
1901 buf = "{ id volatile _rethrow = 0;\n";
1902 else {
1903 buf = "{ id volatile _rethrow = 0;\ntry {\n";
1904 }
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001905 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001906 // Get the start location and compute the semi location.
1907 SourceLocation startLoc = S->getLocStart();
1908 const char *startBuf = SM->getCharacterData(startLoc);
1909
1910 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001911 if (finalStmt)
1912 ReplaceText(startLoc, 1, buf);
1913 else
1914 // @try -> try
1915 ReplaceText(startLoc, 1, "");
1916
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001917 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1918 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001919 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001920
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001921 startLoc = Catch->getLocStart();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001922 bool AtRemoved = false;
1923 if (catchDecl) {
1924 QualType t = catchDecl->getType();
1925 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1926 // Should be a pointer to a class.
1927 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1928 if (IDecl) {
1929 std::string Result;
1930 startBuf = SM->getCharacterData(startLoc);
1931 assert((*startBuf == '@') && "bogus @catch location");
1932 SourceLocation rParenLoc = Catch->getRParenLoc();
1933 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1934
1935 // _objc_exc_Foo *_e as argument to catch.
1936 Result = "catch (_objc_exc_"; Result += IDecl->getNameAsString();
1937 Result += " *_"; Result += catchDecl->getNameAsString();
1938 Result += ")";
1939 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1940 // Foo *e = (Foo *)_e;
1941 Result.clear();
1942 Result = "{ ";
1943 Result += IDecl->getNameAsString();
1944 Result += " *"; Result += catchDecl->getNameAsString();
1945 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1946 Result += "_"; Result += catchDecl->getNameAsString();
1947
1948 Result += "; ";
1949 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
1950 ReplaceText(lBraceLoc, 1, Result);
1951 AtRemoved = true;
1952 }
1953 }
1954 }
1955 if (!AtRemoved)
1956 // @catch -> catch
1957 ReplaceText(startLoc, 1, "");
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001958
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001959 }
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001960 if (finalStmt) {
1961 buf.clear();
1962 if (noCatch)
1963 buf = "catch (id e) {_rethrow = e;}\n";
1964 else
1965 buf = "}\ncatch (id e) {_rethrow = e;}\n";
1966
1967 SourceLocation startFinalLoc = finalStmt->getLocStart();
1968 ReplaceText(startFinalLoc, 8, buf);
1969 Stmt *body = finalStmt->getFinallyBody();
1970 SourceLocation startFinalBodyLoc = body->getLocStart();
1971 buf.clear();
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001972 Write_RethrowObject(buf);
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001973 ReplaceText(startFinalBodyLoc, 1, buf);
1974
1975 SourceLocation endFinalBodyLoc = body->getLocEnd();
1976 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001977 // Now check for any return/continue/go statements within the @try.
1978 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001979 }
1980
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001981 return 0;
1982}
1983
1984// This can't be done with ReplaceStmt(S, ThrowExpr), since
1985// the throw expression is typically a message expression that's already
1986// been rewritten! (which implies the SourceLocation's are invalid).
1987Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
1988 // Get the start location and compute the semi location.
1989 SourceLocation startLoc = S->getLocStart();
1990 const char *startBuf = SM->getCharacterData(startLoc);
1991
1992 assert((*startBuf == '@') && "bogus @throw location");
1993
1994 std::string buf;
1995 /* void objc_exception_throw(id) __attribute__((noreturn)); */
1996 if (S->getThrowExpr())
1997 buf = "objc_exception_throw(";
Fariborz Jahanian40539462012-03-16 16:52:06 +00001998 else
1999 buf = "throw";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002000
2001 // handle "@ throw" correctly.
2002 const char *wBuf = strchr(startBuf, 'w');
2003 assert((*wBuf == 'w') && "@throw: can't find 'w'");
2004 ReplaceText(startLoc, wBuf-startBuf+1, buf);
2005
2006 const char *semiBuf = strchr(startBuf, ';');
2007 assert((*semiBuf == ';') && "@throw: can't find ';'");
2008 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian40539462012-03-16 16:52:06 +00002009 if (S->getThrowExpr())
2010 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002011 return 0;
2012}
2013
2014Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2015 // Create a new string expression.
2016 QualType StrType = Context->getPointerType(Context->CharTy);
2017 std::string StrEncoding;
2018 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
2019 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
2020 StringLiteral::Ascii, false,
2021 StrType, SourceLocation());
2022 ReplaceStmt(Exp, Replacement);
2023
2024 // Replace this subexpr in the parent.
2025 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2026 return Replacement;
2027}
2028
2029Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2030 if (!SelGetUidFunctionDecl)
2031 SynthSelGetUidFunctionDecl();
2032 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2033 // Create a call to sel_registerName("selName").
2034 SmallVector<Expr*, 8> SelExprs;
2035 QualType argType = Context->getPointerType(Context->CharTy);
2036 SelExprs.push_back(StringLiteral::Create(*Context,
2037 Exp->getSelector().getAsString(),
2038 StringLiteral::Ascii, false,
2039 argType, SourceLocation()));
2040 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2041 &SelExprs[0], SelExprs.size());
2042 ReplaceStmt(Exp, SelExp);
2043 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2044 return SelExp;
2045}
2046
2047CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
2048 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2049 SourceLocation EndLoc) {
2050 // Get the type, we will need to reference it in a couple spots.
2051 QualType msgSendType = FD->getType();
2052
2053 // Create a reference to the objc_msgSend() declaration.
2054 DeclRefExpr *DRE =
John McCallf4b88a42012-03-10 09:33:50 +00002055 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002056
2057 // Now, we cast the reference to a pointer to the objc_msgSend type.
2058 QualType pToFunc = Context->getPointerType(msgSendType);
2059 ImplicitCastExpr *ICE =
2060 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2061 DRE, 0, VK_RValue);
2062
2063 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2064
2065 CallExpr *Exp =
2066 new (Context) CallExpr(*Context, ICE, args, nargs,
2067 FT->getCallResultType(*Context),
2068 VK_RValue, EndLoc);
2069 return Exp;
2070}
2071
2072static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2073 const char *&startRef, const char *&endRef) {
2074 while (startBuf < endBuf) {
2075 if (*startBuf == '<')
2076 startRef = startBuf; // mark the start.
2077 if (*startBuf == '>') {
2078 if (startRef && *startRef == '<') {
2079 endRef = startBuf; // mark the end.
2080 return true;
2081 }
2082 return false;
2083 }
2084 startBuf++;
2085 }
2086 return false;
2087}
2088
2089static void scanToNextArgument(const char *&argRef) {
2090 int angle = 0;
2091 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2092 if (*argRef == '<')
2093 angle++;
2094 else if (*argRef == '>')
2095 angle--;
2096 argRef++;
2097 }
2098 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2099}
2100
2101bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2102 if (T->isObjCQualifiedIdType())
2103 return true;
2104 if (const PointerType *PT = T->getAs<PointerType>()) {
2105 if (PT->getPointeeType()->isObjCQualifiedIdType())
2106 return true;
2107 }
2108 if (T->isObjCObjectPointerType()) {
2109 T = T->getPointeeType();
2110 return T->isObjCQualifiedInterfaceType();
2111 }
2112 if (T->isArrayType()) {
2113 QualType ElemTy = Context->getBaseElementType(T);
2114 return needToScanForQualifiers(ElemTy);
2115 }
2116 return false;
2117}
2118
2119void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2120 QualType Type = E->getType();
2121 if (needToScanForQualifiers(Type)) {
2122 SourceLocation Loc, EndLoc;
2123
2124 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2125 Loc = ECE->getLParenLoc();
2126 EndLoc = ECE->getRParenLoc();
2127 } else {
2128 Loc = E->getLocStart();
2129 EndLoc = E->getLocEnd();
2130 }
2131 // This will defend against trying to rewrite synthesized expressions.
2132 if (Loc.isInvalid() || EndLoc.isInvalid())
2133 return;
2134
2135 const char *startBuf = SM->getCharacterData(Loc);
2136 const char *endBuf = SM->getCharacterData(EndLoc);
2137 const char *startRef = 0, *endRef = 0;
2138 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2139 // Get the locations of the startRef, endRef.
2140 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2141 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2142 // Comment out the protocol references.
2143 InsertText(LessLoc, "/*");
2144 InsertText(GreaterLoc, "*/");
2145 }
2146 }
2147}
2148
2149void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2150 SourceLocation Loc;
2151 QualType Type;
2152 const FunctionProtoType *proto = 0;
2153 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2154 Loc = VD->getLocation();
2155 Type = VD->getType();
2156 }
2157 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2158 Loc = FD->getLocation();
2159 // Check for ObjC 'id' and class types that have been adorned with protocol
2160 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2161 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2162 assert(funcType && "missing function type");
2163 proto = dyn_cast<FunctionProtoType>(funcType);
2164 if (!proto)
2165 return;
2166 Type = proto->getResultType();
2167 }
2168 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2169 Loc = FD->getLocation();
2170 Type = FD->getType();
2171 }
2172 else
2173 return;
2174
2175 if (needToScanForQualifiers(Type)) {
2176 // Since types are unique, we need to scan the buffer.
2177
2178 const char *endBuf = SM->getCharacterData(Loc);
2179 const char *startBuf = endBuf;
2180 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2181 startBuf--; // scan backward (from the decl location) for return type.
2182 const char *startRef = 0, *endRef = 0;
2183 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2184 // Get the locations of the startRef, endRef.
2185 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2186 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2187 // Comment out the protocol references.
2188 InsertText(LessLoc, "/*");
2189 InsertText(GreaterLoc, "*/");
2190 }
2191 }
2192 if (!proto)
2193 return; // most likely, was a variable
2194 // Now check arguments.
2195 const char *startBuf = SM->getCharacterData(Loc);
2196 const char *startFuncBuf = startBuf;
2197 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2198 if (needToScanForQualifiers(proto->getArgType(i))) {
2199 // Since types are unique, we need to scan the buffer.
2200
2201 const char *endBuf = startBuf;
2202 // scan forward (from the decl location) for argument types.
2203 scanToNextArgument(endBuf);
2204 const char *startRef = 0, *endRef = 0;
2205 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2206 // Get the locations of the startRef, endRef.
2207 SourceLocation LessLoc =
2208 Loc.getLocWithOffset(startRef-startFuncBuf);
2209 SourceLocation GreaterLoc =
2210 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2211 // Comment out the protocol references.
2212 InsertText(LessLoc, "/*");
2213 InsertText(GreaterLoc, "*/");
2214 }
2215 startBuf = ++endBuf;
2216 }
2217 else {
2218 // If the function name is derived from a macro expansion, then the
2219 // argument buffer will not follow the name. Need to speak with Chris.
2220 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2221 startBuf++; // scan forward (from the decl location) for argument types.
2222 startBuf++;
2223 }
2224 }
2225}
2226
2227void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2228 QualType QT = ND->getType();
2229 const Type* TypePtr = QT->getAs<Type>();
2230 if (!isa<TypeOfExprType>(TypePtr))
2231 return;
2232 while (isa<TypeOfExprType>(TypePtr)) {
2233 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2234 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2235 TypePtr = QT->getAs<Type>();
2236 }
2237 // FIXME. This will not work for multiple declarators; as in:
2238 // __typeof__(a) b,c,d;
2239 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2240 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2241 const char *startBuf = SM->getCharacterData(DeclLoc);
2242 if (ND->getInit()) {
2243 std::string Name(ND->getNameAsString());
2244 TypeAsString += " " + Name + " = ";
2245 Expr *E = ND->getInit();
2246 SourceLocation startLoc;
2247 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2248 startLoc = ECE->getLParenLoc();
2249 else
2250 startLoc = E->getLocStart();
2251 startLoc = SM->getExpansionLoc(startLoc);
2252 const char *endBuf = SM->getCharacterData(startLoc);
2253 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2254 }
2255 else {
2256 SourceLocation X = ND->getLocEnd();
2257 X = SM->getExpansionLoc(X);
2258 const char *endBuf = SM->getCharacterData(X);
2259 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2260 }
2261}
2262
2263// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2264void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2265 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2266 SmallVector<QualType, 16> ArgTys;
2267 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2268 QualType getFuncType =
2269 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
2270 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2271 SourceLocation(),
2272 SourceLocation(),
2273 SelGetUidIdent, getFuncType, 0,
2274 SC_Extern,
2275 SC_None, false);
2276}
2277
2278void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2279 // declared in <objc/objc.h>
2280 if (FD->getIdentifier() &&
2281 FD->getName() == "sel_registerName") {
2282 SelGetUidFunctionDecl = FD;
2283 return;
2284 }
2285 RewriteObjCQualifiedInterfaceTypes(FD);
2286}
2287
2288void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2289 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2290 const char *argPtr = TypeString.c_str();
2291 if (!strchr(argPtr, '^')) {
2292 Str += TypeString;
2293 return;
2294 }
2295 while (*argPtr) {
2296 Str += (*argPtr == '^' ? '*' : *argPtr);
2297 argPtr++;
2298 }
2299}
2300
2301// FIXME. Consolidate this routine with RewriteBlockPointerType.
2302void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2303 ValueDecl *VD) {
2304 QualType Type = VD->getType();
2305 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2306 const char *argPtr = TypeString.c_str();
2307 int paren = 0;
2308 while (*argPtr) {
2309 switch (*argPtr) {
2310 case '(':
2311 Str += *argPtr;
2312 paren++;
2313 break;
2314 case ')':
2315 Str += *argPtr;
2316 paren--;
2317 break;
2318 case '^':
2319 Str += '*';
2320 if (paren == 1)
2321 Str += VD->getNameAsString();
2322 break;
2323 default:
2324 Str += *argPtr;
2325 break;
2326 }
2327 argPtr++;
2328 }
2329}
2330
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002331void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2332 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2333 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2334 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2335 if (!proto)
2336 return;
2337 QualType Type = proto->getResultType();
2338 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2339 FdStr += " ";
2340 FdStr += FD->getName();
2341 FdStr += "(";
2342 unsigned numArgs = proto->getNumArgs();
2343 for (unsigned i = 0; i < numArgs; i++) {
2344 QualType ArgType = proto->getArgType(i);
2345 RewriteBlockPointerType(FdStr, ArgType);
2346 if (i+1 < numArgs)
2347 FdStr += ", ";
2348 }
Fariborz Jahanianb5863da2012-04-19 16:30:28 +00002349 if (FD->isVariadic()) {
2350 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2351 }
2352 else
2353 FdStr += ");\n";
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002354 InsertText(FunLocStart, FdStr);
2355}
2356
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002357// SynthSuperContructorFunctionDecl - id __rw_objc_super(id obj, id super);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002358void RewriteModernObjC::SynthSuperContructorFunctionDecl() {
2359 if (SuperContructorFunctionDecl)
2360 return;
2361 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2362 SmallVector<QualType, 16> ArgTys;
2363 QualType argT = Context->getObjCIdType();
2364 assert(!argT.isNull() && "Can't find 'id' type");
2365 ArgTys.push_back(argT);
2366 ArgTys.push_back(argT);
2367 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2368 &ArgTys[0], ArgTys.size());
2369 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2370 SourceLocation(),
2371 SourceLocation(),
2372 msgSendIdent, msgSendType, 0,
2373 SC_Extern,
2374 SC_None, false);
2375}
2376
2377// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2378void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2379 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2380 SmallVector<QualType, 16> ArgTys;
2381 QualType argT = Context->getObjCIdType();
2382 assert(!argT.isNull() && "Can't find 'id' type");
2383 ArgTys.push_back(argT);
2384 argT = Context->getObjCSelType();
2385 assert(!argT.isNull() && "Can't find 'SEL' type");
2386 ArgTys.push_back(argT);
2387 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2388 &ArgTys[0], ArgTys.size(),
2389 true /*isVariadic*/);
2390 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2391 SourceLocation(),
2392 SourceLocation(),
2393 msgSendIdent, msgSendType, 0,
2394 SC_Extern,
2395 SC_None, false);
2396}
2397
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002398// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002399void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2400 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002401 SmallVector<QualType, 2> ArgTys;
2402 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002403 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002404 &ArgTys[0], 1,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002405 true /*isVariadic*/);
2406 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2407 SourceLocation(),
2408 SourceLocation(),
2409 msgSendIdent, msgSendType, 0,
2410 SC_Extern,
2411 SC_None, false);
2412}
2413
2414// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2415void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2416 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
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 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2428 SourceLocation(),
2429 SourceLocation(),
2430 msgSendIdent, msgSendType, 0,
2431 SC_Extern,
2432 SC_None, false);
2433}
2434
2435// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002436// id objc_msgSendSuper_stret(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002437void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2438 IdentifierInfo *msgSendIdent =
2439 &Context->Idents.get("objc_msgSendSuper_stret");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002440 SmallVector<QualType, 2> ArgTys;
2441 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002442 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002443 &ArgTys[0], 1,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002444 true /*isVariadic*/);
2445 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2446 SourceLocation(),
2447 SourceLocation(),
2448 msgSendIdent, msgSendType, 0,
2449 SC_Extern,
2450 SC_None, false);
2451}
2452
2453// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2454void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2455 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2456 SmallVector<QualType, 16> ArgTys;
2457 QualType argT = Context->getObjCIdType();
2458 assert(!argT.isNull() && "Can't find 'id' type");
2459 ArgTys.push_back(argT);
2460 argT = Context->getObjCSelType();
2461 assert(!argT.isNull() && "Can't find 'SEL' type");
2462 ArgTys.push_back(argT);
2463 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2464 &ArgTys[0], ArgTys.size(),
2465 true /*isVariadic*/);
2466 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2467 SourceLocation(),
2468 SourceLocation(),
2469 msgSendIdent, msgSendType, 0,
2470 SC_Extern,
2471 SC_None, false);
2472}
2473
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002474// SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002475void RewriteModernObjC::SynthGetClassFunctionDecl() {
2476 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2477 SmallVector<QualType, 16> ArgTys;
2478 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002479 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002480 &ArgTys[0], ArgTys.size());
2481 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2482 SourceLocation(),
2483 SourceLocation(),
2484 getClassIdent, getClassType, 0,
2485 SC_Extern,
2486 SC_None, false);
2487}
2488
2489// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2490void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2491 IdentifierInfo *getSuperClassIdent =
2492 &Context->Idents.get("class_getSuperclass");
2493 SmallVector<QualType, 16> ArgTys;
2494 ArgTys.push_back(Context->getObjCClassType());
2495 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2496 &ArgTys[0], ArgTys.size());
2497 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2498 SourceLocation(),
2499 SourceLocation(),
2500 getSuperClassIdent,
2501 getClassType, 0,
2502 SC_Extern,
2503 SC_None,
2504 false);
2505}
2506
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002507// SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002508void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2509 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2510 SmallVector<QualType, 16> ArgTys;
2511 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002512 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002513 &ArgTys[0], ArgTys.size());
2514 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2515 SourceLocation(),
2516 SourceLocation(),
2517 getClassIdent, getClassType, 0,
2518 SC_Extern,
2519 SC_None, false);
2520}
2521
2522Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2523 QualType strType = getConstantStringStructType();
2524
2525 std::string S = "__NSConstantStringImpl_";
2526
2527 std::string tmpName = InFileName;
2528 unsigned i;
2529 for (i=0; i < tmpName.length(); i++) {
2530 char c = tmpName.at(i);
2531 // replace any non alphanumeric characters with '_'.
2532 if (!isalpha(c) && (c < '0' || c > '9'))
2533 tmpName[i] = '_';
2534 }
2535 S += tmpName;
2536 S += "_";
2537 S += utostr(NumObjCStringLiterals++);
2538
2539 Preamble += "static __NSConstantStringImpl " + S;
2540 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2541 Preamble += "0x000007c8,"; // utf8_str
2542 // The pretty printer for StringLiteral handles escape characters properly.
2543 std::string prettyBufS;
2544 llvm::raw_string_ostream prettyBuf(prettyBufS);
2545 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2546 PrintingPolicy(LangOpts));
2547 Preamble += prettyBuf.str();
2548 Preamble += ",";
2549 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2550
2551 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2552 SourceLocation(), &Context->Idents.get(S),
2553 strType, 0, SC_Static, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002554 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002555 SourceLocation());
2556 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2557 Context->getPointerType(DRE->getType()),
2558 VK_RValue, OK_Ordinary,
2559 SourceLocation());
2560 // cast to NSConstantString *
2561 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2562 CK_CPointerToObjCPointerCast, Unop);
2563 ReplaceStmt(Exp, cast);
2564 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2565 return cast;
2566}
2567
Fariborz Jahanian55947042012-03-27 20:17:30 +00002568Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2569 unsigned IntSize =
2570 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2571
2572 Expr *FlagExp = IntegerLiteral::Create(*Context,
2573 llvm::APInt(IntSize, Exp->getValue()),
2574 Context->IntTy, Exp->getLocation());
2575 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2576 CK_BitCast, FlagExp);
2577 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2578 cast);
2579 ReplaceStmt(Exp, PE);
2580 return PE;
2581}
2582
Patrick Beardeb382ec2012-04-19 00:25:12 +00002583Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002584 // synthesize declaration of helper functions needed in this routine.
2585 if (!SelGetUidFunctionDecl)
2586 SynthSelGetUidFunctionDecl();
2587 // use objc_msgSend() for all.
2588 if (!MsgSendFunctionDecl)
2589 SynthMsgSendFunctionDecl();
2590 if (!GetClassFunctionDecl)
2591 SynthGetClassFunctionDecl();
2592
2593 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2594 SourceLocation StartLoc = Exp->getLocStart();
2595 SourceLocation EndLoc = Exp->getLocEnd();
2596
2597 // Synthesize a call to objc_msgSend().
2598 SmallVector<Expr*, 4> MsgExprs;
2599 SmallVector<Expr*, 4> ClsExprs;
2600 QualType argType = Context->getPointerType(Context->CharTy);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002601
Patrick Beardeb382ec2012-04-19 00:25:12 +00002602 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2603 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2604 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002605
Patrick Beardeb382ec2012-04-19 00:25:12 +00002606 IdentifierInfo *clsName = BoxingClass->getIdentifier();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002607 ClsExprs.push_back(StringLiteral::Create(*Context,
2608 clsName->getName(),
2609 StringLiteral::Ascii, false,
2610 argType, SourceLocation()));
2611 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2612 &ClsExprs[0],
2613 ClsExprs.size(),
2614 StartLoc, EndLoc);
2615 MsgExprs.push_back(Cls);
2616
Patrick Beardeb382ec2012-04-19 00:25:12 +00002617 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002618 // it will be the 2nd argument.
2619 SmallVector<Expr*, 4> SelExprs;
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002620 SelExprs.push_back(StringLiteral::Create(*Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002621 BoxingMethod->getSelector().getAsString(),
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002622 StringLiteral::Ascii, false,
2623 argType, SourceLocation()));
2624 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2625 &SelExprs[0], SelExprs.size(),
2626 StartLoc, EndLoc);
2627 MsgExprs.push_back(SelExp);
2628
Patrick Beardeb382ec2012-04-19 00:25:12 +00002629 // User provided sub-expression is the 3rd, and last, argument.
2630 Expr *subExpr = Exp->getSubExpr();
2631 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002632 QualType type = ICE->getType();
2633 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2634 CastKind CK = CK_BitCast;
2635 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2636 CK = CK_IntegralToBoolean;
Patrick Beardeb382ec2012-04-19 00:25:12 +00002637 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002638 }
Patrick Beardeb382ec2012-04-19 00:25:12 +00002639 MsgExprs.push_back(subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002640
2641 SmallVector<QualType, 4> ArgTypes;
2642 ArgTypes.push_back(Context->getObjCIdType());
2643 ArgTypes.push_back(Context->getObjCSelType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002644 for (ObjCMethodDecl::param_iterator PI = BoxingMethod->param_begin(),
2645 E = BoxingMethod->param_end(); PI != E; ++PI)
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002646 ArgTypes.push_back((*PI)->getType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002647
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002648 QualType returnType = Exp->getType();
2649 // Get the type, we will need to reference it in a couple spots.
2650 QualType msgSendType = MsgSendFlavor->getType();
2651
2652 // Create a reference to the objc_msgSend() declaration.
2653 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2654 VK_LValue, SourceLocation());
2655
2656 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002657 Context->getPointerType(Context->VoidTy),
2658 CK_BitCast, DRE);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002659
2660 // Now do the "normal" pointer to function cast.
2661 QualType castType =
Patrick Beardeb382ec2012-04-19 00:25:12 +00002662 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2663 BoxingMethod->isVariadic());
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002664 castType = Context->getPointerType(castType);
2665 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2666 cast);
2667
2668 // Don't forget the parens to enforce the proper binding.
2669 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2670
2671 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2672 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2673 MsgExprs.size(),
2674 FT->getResultType(), VK_RValue,
2675 EndLoc);
2676 ReplaceStmt(Exp, CE);
2677 return CE;
2678}
2679
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002680Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2681 // synthesize declaration of helper functions needed in this routine.
2682 if (!SelGetUidFunctionDecl)
2683 SynthSelGetUidFunctionDecl();
2684 // use objc_msgSend() for all.
2685 if (!MsgSendFunctionDecl)
2686 SynthMsgSendFunctionDecl();
2687 if (!GetClassFunctionDecl)
2688 SynthGetClassFunctionDecl();
2689
2690 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2691 SourceLocation StartLoc = Exp->getLocStart();
2692 SourceLocation EndLoc = Exp->getLocEnd();
2693
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002694 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002695 QualType IntQT = Context->IntTy;
2696 QualType NSArrayFType =
2697 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002698 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002699 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2700 DeclRefExpr *NSArrayDRE =
2701 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2702 SourceLocation());
2703
2704 SmallVector<Expr*, 16> InitExprs;
2705 unsigned NumElements = Exp->getNumElements();
2706 unsigned UnsignedIntSize =
2707 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2708 Expr *count = IntegerLiteral::Create(*Context,
2709 llvm::APInt(UnsignedIntSize, NumElements),
2710 Context->UnsignedIntTy, SourceLocation());
2711 InitExprs.push_back(count);
2712 for (unsigned i = 0; i < NumElements; i++)
2713 InitExprs.push_back(Exp->getElement(i));
2714 Expr *NSArrayCallExpr =
2715 new (Context) CallExpr(*Context, NSArrayDRE, &InitExprs[0], InitExprs.size(),
2716 NSArrayFType, VK_LValue, SourceLocation());
2717
2718 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2719 SourceLocation(),
2720 &Context->Idents.get("arr"),
2721 Context->getPointerType(Context->VoidPtrTy), 0,
2722 /*BitWidth=*/0, /*Mutable=*/true,
2723 /*HasInit=*/false);
2724 MemberExpr *ArrayLiteralME =
2725 new (Context) MemberExpr(NSArrayCallExpr, false, ARRFD,
2726 SourceLocation(),
2727 ARRFD->getType(), VK_LValue,
2728 OK_Ordinary);
2729 QualType ConstIdT = Context->getObjCIdType().withConst();
2730 CStyleCastExpr * ArrayLiteralObjects =
2731 NoTypeInfoCStyleCastExpr(Context,
2732 Context->getPointerType(ConstIdT),
2733 CK_BitCast,
2734 ArrayLiteralME);
2735
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002736 // Synthesize a call to objc_msgSend().
2737 SmallVector<Expr*, 32> MsgExprs;
2738 SmallVector<Expr*, 4> ClsExprs;
2739 QualType argType = Context->getPointerType(Context->CharTy);
2740 QualType expType = Exp->getType();
2741
2742 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2743 ObjCInterfaceDecl *Class =
2744 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2745
2746 IdentifierInfo *clsName = Class->getIdentifier();
2747 ClsExprs.push_back(StringLiteral::Create(*Context,
2748 clsName->getName(),
2749 StringLiteral::Ascii, false,
2750 argType, SourceLocation()));
2751 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2752 &ClsExprs[0],
2753 ClsExprs.size(),
2754 StartLoc, EndLoc);
2755 MsgExprs.push_back(Cls);
2756
2757 // Create a call to sel_registerName("arrayWithObjects:count:").
2758 // it will be the 2nd argument.
2759 SmallVector<Expr*, 4> SelExprs;
2760 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
2761 SelExprs.push_back(StringLiteral::Create(*Context,
2762 ArrayMethod->getSelector().getAsString(),
2763 StringLiteral::Ascii, false,
2764 argType, SourceLocation()));
2765 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2766 &SelExprs[0], SelExprs.size(),
2767 StartLoc, EndLoc);
2768 MsgExprs.push_back(SelExp);
2769
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002770 // (const id [])objects
2771 MsgExprs.push_back(ArrayLiteralObjects);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002772
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002773 // (NSUInteger)cnt
2774 Expr *cnt = IntegerLiteral::Create(*Context,
2775 llvm::APInt(UnsignedIntSize, NumElements),
2776 Context->UnsignedIntTy, SourceLocation());
2777 MsgExprs.push_back(cnt);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002778
2779
2780 SmallVector<QualType, 4> ArgTypes;
2781 ArgTypes.push_back(Context->getObjCIdType());
2782 ArgTypes.push_back(Context->getObjCSelType());
2783 for (ObjCMethodDecl::param_iterator PI = ArrayMethod->param_begin(),
2784 E = ArrayMethod->param_end(); PI != E; ++PI)
2785 ArgTypes.push_back((*PI)->getType());
2786
2787 QualType returnType = Exp->getType();
2788 // Get the type, we will need to reference it in a couple spots.
2789 QualType msgSendType = MsgSendFlavor->getType();
2790
2791 // Create a reference to the objc_msgSend() declaration.
2792 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2793 VK_LValue, SourceLocation());
2794
2795 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2796 Context->getPointerType(Context->VoidTy),
2797 CK_BitCast, DRE);
2798
2799 // Now do the "normal" pointer to function cast.
2800 QualType castType =
2801 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2802 ArrayMethod->isVariadic());
2803 castType = Context->getPointerType(castType);
2804 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2805 cast);
2806
2807 // Don't forget the parens to enforce the proper binding.
2808 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2809
2810 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2811 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2812 MsgExprs.size(),
2813 FT->getResultType(), VK_RValue,
2814 EndLoc);
2815 ReplaceStmt(Exp, CE);
2816 return CE;
2817}
2818
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002819Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2820 // synthesize declaration of helper functions needed in this routine.
2821 if (!SelGetUidFunctionDecl)
2822 SynthSelGetUidFunctionDecl();
2823 // use objc_msgSend() for all.
2824 if (!MsgSendFunctionDecl)
2825 SynthMsgSendFunctionDecl();
2826 if (!GetClassFunctionDecl)
2827 SynthGetClassFunctionDecl();
2828
2829 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2830 SourceLocation StartLoc = Exp->getLocStart();
2831 SourceLocation EndLoc = Exp->getLocEnd();
2832
2833 // Build the expression: __NSContainer_literal(int, ...).arr
2834 QualType IntQT = Context->IntTy;
2835 QualType NSDictFType =
2836 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
2837 std::string NSDictFName("__NSContainer_literal");
2838 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2839 DeclRefExpr *NSDictDRE =
2840 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2841 SourceLocation());
2842
2843 SmallVector<Expr*, 16> KeyExprs;
2844 SmallVector<Expr*, 16> ValueExprs;
2845
2846 unsigned NumElements = Exp->getNumElements();
2847 unsigned UnsignedIntSize =
2848 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2849 Expr *count = IntegerLiteral::Create(*Context,
2850 llvm::APInt(UnsignedIntSize, NumElements),
2851 Context->UnsignedIntTy, SourceLocation());
2852 KeyExprs.push_back(count);
2853 ValueExprs.push_back(count);
2854 for (unsigned i = 0; i < NumElements; i++) {
2855 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2856 KeyExprs.push_back(Element.Key);
2857 ValueExprs.push_back(Element.Value);
2858 }
2859
2860 // (const id [])objects
2861 Expr *NSValueCallExpr =
2862 new (Context) CallExpr(*Context, NSDictDRE, &ValueExprs[0], ValueExprs.size(),
2863 NSDictFType, VK_LValue, SourceLocation());
2864
2865 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2866 SourceLocation(),
2867 &Context->Idents.get("arr"),
2868 Context->getPointerType(Context->VoidPtrTy), 0,
2869 /*BitWidth=*/0, /*Mutable=*/true,
2870 /*HasInit=*/false);
2871 MemberExpr *DictLiteralValueME =
2872 new (Context) MemberExpr(NSValueCallExpr, false, ARRFD,
2873 SourceLocation(),
2874 ARRFD->getType(), VK_LValue,
2875 OK_Ordinary);
2876 QualType ConstIdT = Context->getObjCIdType().withConst();
2877 CStyleCastExpr * DictValueObjects =
2878 NoTypeInfoCStyleCastExpr(Context,
2879 Context->getPointerType(ConstIdT),
2880 CK_BitCast,
2881 DictLiteralValueME);
2882 // (const id <NSCopying> [])keys
2883 Expr *NSKeyCallExpr =
2884 new (Context) CallExpr(*Context, NSDictDRE, &KeyExprs[0], KeyExprs.size(),
2885 NSDictFType, VK_LValue, SourceLocation());
2886
2887 MemberExpr *DictLiteralKeyME =
2888 new (Context) MemberExpr(NSKeyCallExpr, false, ARRFD,
2889 SourceLocation(),
2890 ARRFD->getType(), VK_LValue,
2891 OK_Ordinary);
2892
2893 CStyleCastExpr * DictKeyObjects =
2894 NoTypeInfoCStyleCastExpr(Context,
2895 Context->getPointerType(ConstIdT),
2896 CK_BitCast,
2897 DictLiteralKeyME);
2898
2899
2900
2901 // Synthesize a call to objc_msgSend().
2902 SmallVector<Expr*, 32> MsgExprs;
2903 SmallVector<Expr*, 4> ClsExprs;
2904 QualType argType = Context->getPointerType(Context->CharTy);
2905 QualType expType = Exp->getType();
2906
2907 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2908 ObjCInterfaceDecl *Class =
2909 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2910
2911 IdentifierInfo *clsName = Class->getIdentifier();
2912 ClsExprs.push_back(StringLiteral::Create(*Context,
2913 clsName->getName(),
2914 StringLiteral::Ascii, false,
2915 argType, SourceLocation()));
2916 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2917 &ClsExprs[0],
2918 ClsExprs.size(),
2919 StartLoc, EndLoc);
2920 MsgExprs.push_back(Cls);
2921
2922 // Create a call to sel_registerName("arrayWithObjects:count:").
2923 // it will be the 2nd argument.
2924 SmallVector<Expr*, 4> SelExprs;
2925 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
2926 SelExprs.push_back(StringLiteral::Create(*Context,
2927 DictMethod->getSelector().getAsString(),
2928 StringLiteral::Ascii, false,
2929 argType, SourceLocation()));
2930 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2931 &SelExprs[0], SelExprs.size(),
2932 StartLoc, EndLoc);
2933 MsgExprs.push_back(SelExp);
2934
2935 // (const id [])objects
2936 MsgExprs.push_back(DictValueObjects);
2937
2938 // (const id <NSCopying> [])keys
2939 MsgExprs.push_back(DictKeyObjects);
2940
2941 // (NSUInteger)cnt
2942 Expr *cnt = IntegerLiteral::Create(*Context,
2943 llvm::APInt(UnsignedIntSize, NumElements),
2944 Context->UnsignedIntTy, SourceLocation());
2945 MsgExprs.push_back(cnt);
2946
2947
2948 SmallVector<QualType, 8> ArgTypes;
2949 ArgTypes.push_back(Context->getObjCIdType());
2950 ArgTypes.push_back(Context->getObjCSelType());
2951 for (ObjCMethodDecl::param_iterator PI = DictMethod->param_begin(),
2952 E = DictMethod->param_end(); PI != E; ++PI) {
2953 QualType T = (*PI)->getType();
2954 if (const PointerType* PT = T->getAs<PointerType>()) {
2955 QualType PointeeTy = PT->getPointeeType();
2956 convertToUnqualifiedObjCType(PointeeTy);
2957 T = Context->getPointerType(PointeeTy);
2958 }
2959 ArgTypes.push_back(T);
2960 }
2961
2962 QualType returnType = Exp->getType();
2963 // Get the type, we will need to reference it in a couple spots.
2964 QualType msgSendType = MsgSendFlavor->getType();
2965
2966 // Create a reference to the objc_msgSend() declaration.
2967 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2968 VK_LValue, SourceLocation());
2969
2970 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2971 Context->getPointerType(Context->VoidTy),
2972 CK_BitCast, DRE);
2973
2974 // Now do the "normal" pointer to function cast.
2975 QualType castType =
2976 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2977 DictMethod->isVariadic());
2978 castType = Context->getPointerType(castType);
2979 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2980 cast);
2981
2982 // Don't forget the parens to enforce the proper binding.
2983 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2984
2985 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2986 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2987 MsgExprs.size(),
2988 FT->getResultType(), VK_RValue,
2989 EndLoc);
2990 ReplaceStmt(Exp, CE);
2991 return CE;
2992}
2993
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002994// struct __rw_objc_super {
2995// struct objc_object *object; struct objc_object *superClass;
2996// };
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002997QualType RewriteModernObjC::getSuperStructType() {
2998 if (!SuperStructDecl) {
2999 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3000 SourceLocation(), SourceLocation(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003001 &Context->Idents.get("__rw_objc_super"));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003002 QualType FieldTypes[2];
3003
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003004 // struct objc_object *object;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003005 FieldTypes[0] = Context->getObjCIdType();
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003006 // struct objc_object *superClass;
3007 FieldTypes[1] = Context->getObjCIdType();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003008
3009 // Create fields
3010 for (unsigned i = 0; i < 2; ++i) {
3011 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
3012 SourceLocation(),
3013 SourceLocation(), 0,
3014 FieldTypes[i], 0,
3015 /*BitWidth=*/0,
3016 /*Mutable=*/false,
3017 /*HasInit=*/false));
3018 }
3019
3020 SuperStructDecl->completeDefinition();
3021 }
3022 return Context->getTagDeclType(SuperStructDecl);
3023}
3024
3025QualType RewriteModernObjC::getConstantStringStructType() {
3026 if (!ConstantStringDecl) {
3027 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3028 SourceLocation(), SourceLocation(),
3029 &Context->Idents.get("__NSConstantStringImpl"));
3030 QualType FieldTypes[4];
3031
3032 // struct objc_object *receiver;
3033 FieldTypes[0] = Context->getObjCIdType();
3034 // int flags;
3035 FieldTypes[1] = Context->IntTy;
3036 // char *str;
3037 FieldTypes[2] = Context->getPointerType(Context->CharTy);
3038 // long length;
3039 FieldTypes[3] = Context->LongTy;
3040
3041 // Create fields
3042 for (unsigned i = 0; i < 4; ++i) {
3043 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3044 ConstantStringDecl,
3045 SourceLocation(),
3046 SourceLocation(), 0,
3047 FieldTypes[i], 0,
3048 /*BitWidth=*/0,
3049 /*Mutable=*/true,
3050 /*HasInit=*/false));
3051 }
3052
3053 ConstantStringDecl->completeDefinition();
3054 }
3055 return Context->getTagDeclType(ConstantStringDecl);
3056}
3057
3058Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3059 SourceLocation StartLoc,
3060 SourceLocation EndLoc) {
3061 if (!SelGetUidFunctionDecl)
3062 SynthSelGetUidFunctionDecl();
3063 if (!MsgSendFunctionDecl)
3064 SynthMsgSendFunctionDecl();
3065 if (!MsgSendSuperFunctionDecl)
3066 SynthMsgSendSuperFunctionDecl();
3067 if (!MsgSendStretFunctionDecl)
3068 SynthMsgSendStretFunctionDecl();
3069 if (!MsgSendSuperStretFunctionDecl)
3070 SynthMsgSendSuperStretFunctionDecl();
3071 if (!MsgSendFpretFunctionDecl)
3072 SynthMsgSendFpretFunctionDecl();
3073 if (!GetClassFunctionDecl)
3074 SynthGetClassFunctionDecl();
3075 if (!GetSuperClassFunctionDecl)
3076 SynthGetSuperClassFunctionDecl();
3077 if (!GetMetaClassFunctionDecl)
3078 SynthGetMetaClassFunctionDecl();
3079
3080 // default to objc_msgSend().
3081 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3082 // May need to use objc_msgSend_stret() as well.
3083 FunctionDecl *MsgSendStretFlavor = 0;
3084 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
3085 QualType resultType = mDecl->getResultType();
3086 if (resultType->isRecordType())
3087 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3088 else if (resultType->isRealFloatingType())
3089 MsgSendFlavor = MsgSendFpretFunctionDecl;
3090 }
3091
3092 // Synthesize a call to objc_msgSend().
3093 SmallVector<Expr*, 8> MsgExprs;
3094 switch (Exp->getReceiverKind()) {
3095 case ObjCMessageExpr::SuperClass: {
3096 MsgSendFlavor = MsgSendSuperFunctionDecl;
3097 if (MsgSendStretFlavor)
3098 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3099 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3100
3101 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3102
3103 SmallVector<Expr*, 4> InitExprs;
3104
3105 // set the receiver to self, the first argument to all methods.
3106 InitExprs.push_back(
3107 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3108 CK_BitCast,
3109 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003110 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003111 Context->getObjCIdType(),
3112 VK_RValue,
3113 SourceLocation()))
3114 ); // set the 'receiver'.
3115
3116 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3117 SmallVector<Expr*, 8> ClsExprs;
3118 QualType argType = Context->getPointerType(Context->CharTy);
3119 ClsExprs.push_back(StringLiteral::Create(*Context,
3120 ClassDecl->getIdentifier()->getName(),
3121 StringLiteral::Ascii, false,
3122 argType, SourceLocation()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003123 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003124 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3125 &ClsExprs[0],
3126 ClsExprs.size(),
3127 StartLoc,
3128 EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003129 ClsExprs.clear();
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003130 ClsExprs.push_back(Cls);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003131 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3132 &ClsExprs[0], ClsExprs.size(),
3133 StartLoc, EndLoc);
3134
3135 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3136 // To turn off a warning, type-cast to 'id'
3137 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3138 NoTypeInfoCStyleCastExpr(Context,
3139 Context->getObjCIdType(),
3140 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003141 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003142 QualType superType = getSuperStructType();
3143 Expr *SuperRep;
3144
3145 if (LangOpts.MicrosoftExt) {
3146 SynthSuperContructorFunctionDecl();
3147 // Simulate a contructor call...
3148 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003149 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003150 SourceLocation());
3151 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
3152 InitExprs.size(),
3153 superType, VK_LValue,
3154 SourceLocation());
3155 // The code for super is a little tricky to prevent collision with
3156 // the structure definition in the header. The rewriter has it's own
3157 // internal definition (__rw_objc_super) that is uses. This is why
3158 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003159 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003160 //
3161 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3162 Context->getPointerType(SuperRep->getType()),
3163 VK_RValue, OK_Ordinary,
3164 SourceLocation());
3165 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3166 Context->getPointerType(superType),
3167 CK_BitCast, SuperRep);
3168 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003169 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003170 InitListExpr *ILE =
3171 new (Context) InitListExpr(*Context, SourceLocation(),
3172 &InitExprs[0], InitExprs.size(),
3173 SourceLocation());
3174 TypeSourceInfo *superTInfo
3175 = Context->getTrivialTypeSourceInfo(superType);
3176 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3177 superType, VK_LValue,
3178 ILE, false);
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003179 // struct __rw_objc_super *
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003180 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3181 Context->getPointerType(SuperRep->getType()),
3182 VK_RValue, OK_Ordinary,
3183 SourceLocation());
3184 }
3185 MsgExprs.push_back(SuperRep);
3186 break;
3187 }
3188
3189 case ObjCMessageExpr::Class: {
3190 SmallVector<Expr*, 8> ClsExprs;
3191 QualType argType = Context->getPointerType(Context->CharTy);
3192 ObjCInterfaceDecl *Class
3193 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3194 IdentifierInfo *clsName = Class->getIdentifier();
3195 ClsExprs.push_back(StringLiteral::Create(*Context,
3196 clsName->getName(),
3197 StringLiteral::Ascii, false,
3198 argType, SourceLocation()));
3199 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3200 &ClsExprs[0],
3201 ClsExprs.size(),
3202 StartLoc, EndLoc);
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003203 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3204 Context->getObjCIdType(),
3205 CK_BitCast, Cls);
3206 MsgExprs.push_back(ArgExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003207 break;
3208 }
3209
3210 case ObjCMessageExpr::SuperInstance:{
3211 MsgSendFlavor = MsgSendSuperFunctionDecl;
3212 if (MsgSendStretFlavor)
3213 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3214 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3215 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3216 SmallVector<Expr*, 4> InitExprs;
3217
3218 InitExprs.push_back(
3219 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3220 CK_BitCast,
3221 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003222 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003223 Context->getObjCIdType(),
3224 VK_RValue, SourceLocation()))
3225 ); // set the 'receiver'.
3226
3227 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3228 SmallVector<Expr*, 8> ClsExprs;
3229 QualType argType = Context->getPointerType(Context->CharTy);
3230 ClsExprs.push_back(StringLiteral::Create(*Context,
3231 ClassDecl->getIdentifier()->getName(),
3232 StringLiteral::Ascii, false, argType,
3233 SourceLocation()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003234 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003235 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3236 &ClsExprs[0],
3237 ClsExprs.size(),
3238 StartLoc, EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003239 ClsExprs.clear();
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003240 ClsExprs.push_back(Cls);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003241 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3242 &ClsExprs[0], ClsExprs.size(),
3243 StartLoc, EndLoc);
3244
3245 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3246 // To turn off a warning, type-cast to 'id'
3247 InitExprs.push_back(
3248 // set 'super class', using class_getSuperclass().
3249 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3250 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003251 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003252 QualType superType = getSuperStructType();
3253 Expr *SuperRep;
3254
3255 if (LangOpts.MicrosoftExt) {
3256 SynthSuperContructorFunctionDecl();
3257 // Simulate a contructor call...
3258 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003259 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003260 SourceLocation());
3261 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
3262 InitExprs.size(),
3263 superType, VK_LValue, SourceLocation());
3264 // The code for super is a little tricky to prevent collision with
3265 // the structure definition in the header. The rewriter has it's own
3266 // internal definition (__rw_objc_super) that is uses. This is why
3267 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003268 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003269 //
3270 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3271 Context->getPointerType(SuperRep->getType()),
3272 VK_RValue, OK_Ordinary,
3273 SourceLocation());
3274 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3275 Context->getPointerType(superType),
3276 CK_BitCast, SuperRep);
3277 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003278 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003279 InitListExpr *ILE =
3280 new (Context) InitListExpr(*Context, SourceLocation(),
3281 &InitExprs[0], InitExprs.size(),
3282 SourceLocation());
3283 TypeSourceInfo *superTInfo
3284 = Context->getTrivialTypeSourceInfo(superType);
3285 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3286 superType, VK_RValue, ILE,
3287 false);
3288 }
3289 MsgExprs.push_back(SuperRep);
3290 break;
3291 }
3292
3293 case ObjCMessageExpr::Instance: {
3294 // Remove all type-casts because it may contain objc-style types; e.g.
3295 // Foo<Proto> *.
3296 Expr *recExpr = Exp->getInstanceReceiver();
3297 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3298 recExpr = CE->getSubExpr();
3299 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3300 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3301 ? CK_BlockPointerToObjCPointerCast
3302 : CK_CPointerToObjCPointerCast;
3303
3304 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3305 CK, recExpr);
3306 MsgExprs.push_back(recExpr);
3307 break;
3308 }
3309 }
3310
3311 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3312 SmallVector<Expr*, 8> SelExprs;
3313 QualType argType = Context->getPointerType(Context->CharTy);
3314 SelExprs.push_back(StringLiteral::Create(*Context,
3315 Exp->getSelector().getAsString(),
3316 StringLiteral::Ascii, false,
3317 argType, SourceLocation()));
3318 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3319 &SelExprs[0], SelExprs.size(),
3320 StartLoc,
3321 EndLoc);
3322 MsgExprs.push_back(SelExp);
3323
3324 // Now push any user supplied arguments.
3325 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3326 Expr *userExpr = Exp->getArg(i);
3327 // Make all implicit casts explicit...ICE comes in handy:-)
3328 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3329 // Reuse the ICE type, it is exactly what the doctor ordered.
3330 QualType type = ICE->getType();
3331 if (needToScanForQualifiers(type))
3332 type = Context->getObjCIdType();
3333 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3334 (void)convertBlockPointerToFunctionPointer(type);
3335 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3336 CastKind CK;
3337 if (SubExpr->getType()->isIntegralType(*Context) &&
3338 type->isBooleanType()) {
3339 CK = CK_IntegralToBoolean;
3340 } else if (type->isObjCObjectPointerType()) {
3341 if (SubExpr->getType()->isBlockPointerType()) {
3342 CK = CK_BlockPointerToObjCPointerCast;
3343 } else if (SubExpr->getType()->isPointerType()) {
3344 CK = CK_CPointerToObjCPointerCast;
3345 } else {
3346 CK = CK_BitCast;
3347 }
3348 } else {
3349 CK = CK_BitCast;
3350 }
3351
3352 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3353 }
3354 // Make id<P...> cast into an 'id' cast.
3355 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3356 if (CE->getType()->isObjCQualifiedIdType()) {
3357 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3358 userExpr = CE->getSubExpr();
3359 CastKind CK;
3360 if (userExpr->getType()->isIntegralType(*Context)) {
3361 CK = CK_IntegralToPointer;
3362 } else if (userExpr->getType()->isBlockPointerType()) {
3363 CK = CK_BlockPointerToObjCPointerCast;
3364 } else if (userExpr->getType()->isPointerType()) {
3365 CK = CK_CPointerToObjCPointerCast;
3366 } else {
3367 CK = CK_BitCast;
3368 }
3369 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3370 CK, userExpr);
3371 }
3372 }
3373 MsgExprs.push_back(userExpr);
3374 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3375 // out the argument in the original expression (since we aren't deleting
3376 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3377 //Exp->setArg(i, 0);
3378 }
3379 // Generate the funky cast.
3380 CastExpr *cast;
3381 SmallVector<QualType, 8> ArgTypes;
3382 QualType returnType;
3383
3384 // Push 'id' and 'SEL', the 2 implicit arguments.
3385 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3386 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3387 else
3388 ArgTypes.push_back(Context->getObjCIdType());
3389 ArgTypes.push_back(Context->getObjCSelType());
3390 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3391 // Push any user argument types.
3392 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3393 E = OMD->param_end(); PI != E; ++PI) {
3394 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
3395 ? Context->getObjCIdType()
3396 : (*PI)->getType();
3397 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3398 (void)convertBlockPointerToFunctionPointer(t);
3399 ArgTypes.push_back(t);
3400 }
3401 returnType = Exp->getType();
3402 convertToUnqualifiedObjCType(returnType);
3403 (void)convertBlockPointerToFunctionPointer(returnType);
3404 } else {
3405 returnType = Context->getObjCIdType();
3406 }
3407 // Get the type, we will need to reference it in a couple spots.
3408 QualType msgSendType = MsgSendFlavor->getType();
3409
3410 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003411 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003412 VK_LValue, SourceLocation());
3413
3414 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3415 // If we don't do this cast, we get the following bizarre warning/note:
3416 // xx.m:13: warning: function called through a non-compatible type
3417 // xx.m:13: note: if this code is reached, the program will abort
3418 cast = NoTypeInfoCStyleCastExpr(Context,
3419 Context->getPointerType(Context->VoidTy),
3420 CK_BitCast, DRE);
3421
3422 // Now do the "normal" pointer to function cast.
3423 QualType castType =
3424 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3425 // If we don't have a method decl, force a variadic cast.
3426 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
3427 castType = Context->getPointerType(castType);
3428 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3429 cast);
3430
3431 // Don't forget the parens to enforce the proper binding.
3432 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3433
3434 const FunctionType *FT = msgSendType->getAs<FunctionType>();
3435 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
3436 MsgExprs.size(),
3437 FT->getResultType(), VK_RValue,
3438 EndLoc);
3439 Stmt *ReplacingStmt = CE;
3440 if (MsgSendStretFlavor) {
3441 // We have the method which returns a struct/union. Must also generate
3442 // call to objc_msgSend_stret and hang both varieties on a conditional
3443 // expression which dictate which one to envoke depending on size of
3444 // method's return type.
3445
3446 // Create a reference to the objc_msgSend_stret() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003447 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
3448 false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003449 VK_LValue, SourceLocation());
3450 // Need to cast objc_msgSend_stret to "void *" (see above comment).
3451 cast = NoTypeInfoCStyleCastExpr(Context,
3452 Context->getPointerType(Context->VoidTy),
3453 CK_BitCast, STDRE);
3454 // Now do the "normal" pointer to function cast.
3455 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3456 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
3457 castType = Context->getPointerType(castType);
3458 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3459 cast);
3460
3461 // Don't forget the parens to enforce the proper binding.
3462 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
3463
3464 FT = msgSendType->getAs<FunctionType>();
3465 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
3466 MsgExprs.size(),
3467 FT->getResultType(), VK_RValue,
3468 SourceLocation());
3469
3470 // Build sizeof(returnType)
3471 UnaryExprOrTypeTraitExpr *sizeofExpr =
3472 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3473 Context->getTrivialTypeSourceInfo(returnType),
3474 Context->getSizeType(), SourceLocation(),
3475 SourceLocation());
3476 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3477 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3478 // For X86 it is more complicated and some kind of target specific routine
3479 // is needed to decide what to do.
3480 unsigned IntSize =
3481 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
3482 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3483 llvm::APInt(IntSize, 8),
3484 Context->IntTy,
3485 SourceLocation());
3486 BinaryOperator *lessThanExpr =
3487 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3488 VK_RValue, OK_Ordinary, SourceLocation());
3489 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3490 ConditionalOperator *CondExpr =
3491 new (Context) ConditionalOperator(lessThanExpr,
3492 SourceLocation(), CE,
3493 SourceLocation(), STCE,
3494 returnType, VK_RValue, OK_Ordinary);
3495 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3496 CondExpr);
3497 }
3498 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3499 return ReplacingStmt;
3500}
3501
3502Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3503 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3504 Exp->getLocEnd());
3505
3506 // Now do the actual rewrite.
3507 ReplaceStmt(Exp, ReplacingStmt);
3508
3509 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3510 return ReplacingStmt;
3511}
3512
3513// typedef struct objc_object Protocol;
3514QualType RewriteModernObjC::getProtocolType() {
3515 if (!ProtocolTypeDecl) {
3516 TypeSourceInfo *TInfo
3517 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3518 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3519 SourceLocation(), SourceLocation(),
3520 &Context->Idents.get("Protocol"),
3521 TInfo);
3522 }
3523 return Context->getTypeDeclType(ProtocolTypeDecl);
3524}
3525
3526/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3527/// a synthesized/forward data reference (to the protocol's metadata).
3528/// The forward references (and metadata) are generated in
3529/// RewriteModernObjC::HandleTranslationUnit().
3530Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00003531 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3532 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003533 IdentifierInfo *ID = &Context->Idents.get(Name);
3534 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3535 SourceLocation(), ID, getProtocolType(), 0,
3536 SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00003537 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3538 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003539 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3540 Context->getPointerType(DRE->getType()),
3541 VK_RValue, OK_Ordinary, SourceLocation());
3542 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3543 CK_BitCast,
3544 DerefExpr);
3545 ReplaceStmt(Exp, castExpr);
3546 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3547 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3548 return castExpr;
3549
3550}
3551
3552bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3553 const char *endBuf) {
3554 while (startBuf < endBuf) {
3555 if (*startBuf == '#') {
3556 // Skip whitespace.
3557 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3558 ;
3559 if (!strncmp(startBuf, "if", strlen("if")) ||
3560 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3561 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3562 !strncmp(startBuf, "define", strlen("define")) ||
3563 !strncmp(startBuf, "undef", strlen("undef")) ||
3564 !strncmp(startBuf, "else", strlen("else")) ||
3565 !strncmp(startBuf, "elif", strlen("elif")) ||
3566 !strncmp(startBuf, "endif", strlen("endif")) ||
3567 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3568 !strncmp(startBuf, "include", strlen("include")) ||
3569 !strncmp(startBuf, "import", strlen("import")) ||
3570 !strncmp(startBuf, "include_next", strlen("include_next")))
3571 return true;
3572 }
3573 startBuf++;
3574 }
3575 return false;
3576}
3577
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003578/// IsTagDefinedInsideClass - This routine checks that a named tagged type
3579/// is defined inside an objective-c class. If so, it returns true.
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00003580bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003581 TagDecl *Tag,
3582 bool &IsNamedDefinition) {
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003583 if (!IDecl)
3584 return false;
3585 SourceLocation TagLocation;
3586 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3587 RD = RD->getDefinition();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003588 if (!RD || !RD->getDeclName().getAsIdentifierInfo())
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003589 return false;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003590 IsNamedDefinition = true;
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003591 TagLocation = RD->getLocation();
3592 return Context->getSourceManager().isBeforeInTranslationUnit(
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003593 IDecl->getLocation(), TagLocation);
3594 }
3595 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3596 if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3597 return false;
3598 IsNamedDefinition = true;
3599 TagLocation = ED->getLocation();
3600 return Context->getSourceManager().isBeforeInTranslationUnit(
3601 IDecl->getLocation(), TagLocation);
3602
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003603 }
3604 return false;
3605}
3606
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003607/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003608/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003609bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3610 std::string &Result) {
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00003611 if (isa<TypedefType>(Type)) {
3612 Result += "\t";
3613 return false;
3614 }
3615
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003616 if (Type->isArrayType()) {
3617 QualType ElemTy = Context->getBaseElementType(Type);
3618 return RewriteObjCFieldDeclType(ElemTy, Result);
3619 }
3620 else if (Type->isRecordType()) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003621 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3622 if (RD->isCompleteDefinition()) {
3623 if (RD->isStruct())
3624 Result += "\n\tstruct ";
3625 else if (RD->isUnion())
3626 Result += "\n\tunion ";
3627 else
3628 assert(false && "class not allowed as an ivar type");
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003629
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003630 Result += RD->getName();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003631 if (GlobalDefinedTags.count(RD)) {
3632 // struct/union is defined globally, use it.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003633 Result += " ";
3634 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003635 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003636 Result += " {\n";
3637 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003638 e = RD->field_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00003639 FieldDecl *FD = *i;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003640 RewriteObjCFieldDecl(FD, Result);
3641 }
3642 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003643 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003644 }
3645 }
3646 else if (Type->isEnumeralType()) {
3647 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3648 if (ED->isCompleteDefinition()) {
3649 Result += "\n\tenum ";
3650 Result += ED->getName();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003651 if (GlobalDefinedTags.count(ED)) {
3652 // Enum is globall defined, use it.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003653 Result += " ";
3654 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003655 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003656
3657 Result += " {\n";
3658 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3659 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3660 Result += "\t"; Result += EC->getName(); Result += " = ";
3661 llvm::APSInt Val = EC->getInitVal();
3662 Result += Val.toString(10);
3663 Result += ",\n";
3664 }
3665 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003666 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003667 }
3668 }
3669
3670 Result += "\t";
3671 convertObjCTypeToCStyleType(Type);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003672 return false;
3673}
3674
3675
3676/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3677/// It handles elaborated types, as well as enum types in the process.
3678void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3679 std::string &Result) {
3680 QualType Type = fieldDecl->getType();
3681 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003682
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003683 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3684 if (!EleboratedType)
3685 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003686 Result += Name;
3687 if (fieldDecl->isBitField()) {
3688 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3689 }
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003690 else if (EleboratedType && Type->isArrayType()) {
3691 CanQualType CType = Context->getCanonicalType(Type);
3692 while (isa<ArrayType>(CType)) {
3693 if (const ConstantArrayType *CAT = Context->getAsConstantArrayType(CType)) {
3694 Result += "[";
3695 llvm::APInt Dim = CAT->getSize();
3696 Result += utostr(Dim.getZExtValue());
3697 Result += "]";
3698 }
3699 CType = CType->getAs<ArrayType>()->getElementType();
3700 }
3701 }
3702
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003703 Result += ";\n";
3704}
3705
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003706/// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3707/// named aggregate types into the input buffer.
3708void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3709 std::string &Result) {
3710 QualType Type = fieldDecl->getType();
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00003711 if (isa<TypedefType>(Type))
3712 return;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003713 if (Type->isArrayType())
3714 Type = Context->getBaseElementType(Type);
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00003715 ObjCContainerDecl *IDecl =
3716 dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003717
3718 TagDecl *TD = 0;
3719 if (Type->isRecordType()) {
3720 TD = Type->getAs<RecordType>()->getDecl();
3721 }
3722 else if (Type->isEnumeralType()) {
3723 TD = Type->getAs<EnumType>()->getDecl();
3724 }
3725
3726 if (TD) {
3727 if (GlobalDefinedTags.count(TD))
3728 return;
3729
3730 bool IsNamedDefinition = false;
3731 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3732 RewriteObjCFieldDeclType(Type, Result);
3733 Result += ";";
3734 }
3735 if (IsNamedDefinition)
3736 GlobalDefinedTags.insert(TD);
3737 }
3738
3739}
3740
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003741/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3742/// an objective-c class with ivars.
3743void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3744 std::string &Result) {
3745 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3746 assert(CDecl->getName() != "" &&
3747 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003748 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003749 SmallVector<ObjCIvarDecl *, 8> IVars;
3750 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003751 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003752 IVars.push_back(IVD);
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003753
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003754 SourceLocation LocStart = CDecl->getLocStart();
3755 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003756
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003757 const char *startBuf = SM->getCharacterData(LocStart);
3758 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003759
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003760 // If no ivars and no root or if its root, directly or indirectly,
3761 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003762 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003763 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3764 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3765 ReplaceText(LocStart, endBuf-startBuf, Result);
3766 return;
3767 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003768
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003769 // Insert named struct/union definitions inside class to
3770 // outer scope. This follows semantics of locally defined
3771 // struct/unions in objective-c classes.
3772 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3773 RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
3774
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003775 Result += "\nstruct ";
3776 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003777 Result += "_IMPL {\n";
3778
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003779 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003780 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3781 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3782 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003783 }
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003784
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003785 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3786 RewriteObjCFieldDecl(IVars[i], Result);
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00003787
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003788 Result += "};\n";
3789 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3790 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003791 // Mark this struct as having been generated.
3792 if (!ObjCSynthesizedStructs.insert(CDecl))
3793 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003794}
3795
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003796/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3797/// have been referenced in an ivar access expression.
3798void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3799 std::string &Result) {
3800 // write out ivar offset symbols which have been referenced in an ivar
3801 // access expression.
3802 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3803 if (Ivars.empty())
3804 return;
3805 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
3806 e = Ivars.end(); i != e; i++) {
3807 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003808 Result += "\n";
3809 if (LangOpts.MicrosoftExt)
3810 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003811 Result += "extern \"C\" ";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003812 if (LangOpts.MicrosoftExt &&
3813 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003814 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
3815 Result += "__declspec(dllimport) ";
3816
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00003817 Result += "unsigned long ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003818 WriteInternalIvarName(CDecl, IvarDecl, Result);
3819 Result += ";";
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003820 }
3821}
3822
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003823//===----------------------------------------------------------------------===//
3824// Meta Data Emission
3825//===----------------------------------------------------------------------===//
3826
3827
3828/// RewriteImplementations - This routine rewrites all method implementations
3829/// and emits meta-data.
3830
3831void RewriteModernObjC::RewriteImplementations() {
3832 int ClsDefCount = ClassImplementation.size();
3833 int CatDefCount = CategoryImplementation.size();
3834
3835 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003836 for (int i = 0; i < ClsDefCount; i++) {
3837 ObjCImplementationDecl *OIMP = ClassImplementation[i];
3838 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
3839 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00003840 assert(false &&
3841 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003842 RewriteImplementationDecl(OIMP);
3843 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003844
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003845 for (int i = 0; i < CatDefCount; i++) {
3846 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
3847 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
3848 if (CDecl->isImplicitInterfaceDecl())
3849 assert(false &&
3850 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003851 RewriteImplementationDecl(CIMP);
3852 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003853}
3854
3855void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
3856 const std::string &Name,
3857 ValueDecl *VD, bool def) {
3858 assert(BlockByRefDeclNo.count(VD) &&
3859 "RewriteByRefString: ByRef decl missing");
3860 if (def)
3861 ResultStr += "struct ";
3862 ResultStr += "__Block_byref_" + Name +
3863 "_" + utostr(BlockByRefDeclNo[VD]) ;
3864}
3865
3866static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3867 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3868 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3869 return false;
3870}
3871
3872std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3873 StringRef funcName,
3874 std::string Tag) {
3875 const FunctionType *AFT = CE->getFunctionType();
3876 QualType RT = AFT->getResultType();
3877 std::string StructRef = "struct " + Tag;
3878 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00003879 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003880
3881 BlockDecl *BD = CE->getBlockDecl();
3882
3883 if (isa<FunctionNoProtoType>(AFT)) {
3884 // No user-supplied arguments. Still need to pass in a pointer to the
3885 // block (to reference imported block decl refs).
3886 S += "(" + StructRef + " *__cself)";
3887 } else if (BD->param_empty()) {
3888 S += "(" + StructRef + " *__cself)";
3889 } else {
3890 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
3891 assert(FT && "SynthesizeBlockFunc: No function proto");
3892 S += '(';
3893 // first add the implicit argument.
3894 S += StructRef + " *__cself, ";
3895 std::string ParamStr;
3896 for (BlockDecl::param_iterator AI = BD->param_begin(),
3897 E = BD->param_end(); AI != E; ++AI) {
3898 if (AI != BD->param_begin()) S += ", ";
3899 ParamStr = (*AI)->getNameAsString();
3900 QualType QT = (*AI)->getType();
Fariborz Jahanian2610f902012-03-27 16:42:20 +00003901 (void)convertBlockPointerToFunctionPointer(QT);
3902 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003903 S += ParamStr;
3904 }
3905 if (FT->isVariadic()) {
3906 if (!BD->param_empty()) S += ", ";
3907 S += "...";
3908 }
3909 S += ')';
3910 }
3911 S += " {\n";
3912
3913 // Create local declarations to avoid rewriting all closure decl ref exprs.
3914 // First, emit a declaration for all "by ref" decls.
3915 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3916 E = BlockByRefDecls.end(); I != E; ++I) {
3917 S += " ";
3918 std::string Name = (*I)->getNameAsString();
3919 std::string TypeString;
3920 RewriteByRefString(TypeString, Name, (*I));
3921 TypeString += " *";
3922 Name = TypeString + Name;
3923 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
3924 }
3925 // Next, emit a declaration for all "by copy" declarations.
3926 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3927 E = BlockByCopyDecls.end(); I != E; ++I) {
3928 S += " ";
3929 // Handle nested closure invocation. For example:
3930 //
3931 // void (^myImportedClosure)(void);
3932 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3933 //
3934 // void (^anotherClosure)(void);
3935 // anotherClosure = ^(void) {
3936 // myImportedClosure(); // import and invoke the closure
3937 // };
3938 //
3939 if (isTopLevelBlockPointerType((*I)->getType())) {
3940 RewriteBlockPointerTypeVariable(S, (*I));
3941 S += " = (";
3942 RewriteBlockPointerType(S, (*I)->getType());
3943 S += ")";
3944 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3945 }
3946 else {
3947 std::string Name = (*I)->getNameAsString();
3948 QualType QT = (*I)->getType();
3949 if (HasLocalVariableExternalStorage(*I))
3950 QT = Context->getPointerType(QT);
3951 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
3952 S += Name + " = __cself->" +
3953 (*I)->getNameAsString() + "; // bound by copy\n";
3954 }
3955 }
3956 std::string RewrittenStr = RewrittenBlockExprs[CE];
3957 const char *cstr = RewrittenStr.c_str();
3958 while (*cstr++ != '{') ;
3959 S += cstr;
3960 S += "\n";
3961 return S;
3962}
3963
3964std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3965 StringRef funcName,
3966 std::string Tag) {
3967 std::string StructRef = "struct " + Tag;
3968 std::string S = "static void __";
3969
3970 S += funcName;
3971 S += "_block_copy_" + utostr(i);
3972 S += "(" + StructRef;
3973 S += "*dst, " + StructRef;
3974 S += "*src) {";
3975 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3976 E = ImportedBlockDecls.end(); I != E; ++I) {
3977 ValueDecl *VD = (*I);
3978 S += "_Block_object_assign((void*)&dst->";
3979 S += (*I)->getNameAsString();
3980 S += ", (void*)src->";
3981 S += (*I)->getNameAsString();
3982 if (BlockByRefDeclsPtrSet.count((*I)))
3983 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3984 else if (VD->getType()->isBlockPointerType())
3985 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3986 else
3987 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3988 }
3989 S += "}\n";
3990
3991 S += "\nstatic void __";
3992 S += funcName;
3993 S += "_block_dispose_" + utostr(i);
3994 S += "(" + StructRef;
3995 S += "*src) {";
3996 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3997 E = ImportedBlockDecls.end(); I != E; ++I) {
3998 ValueDecl *VD = (*I);
3999 S += "_Block_object_dispose((void*)src->";
4000 S += (*I)->getNameAsString();
4001 if (BlockByRefDeclsPtrSet.count((*I)))
4002 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4003 else if (VD->getType()->isBlockPointerType())
4004 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4005 else
4006 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4007 }
4008 S += "}\n";
4009 return S;
4010}
4011
4012std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4013 std::string Desc) {
4014 std::string S = "\nstruct " + Tag;
4015 std::string Constructor = " " + Tag;
4016
4017 S += " {\n struct __block_impl impl;\n";
4018 S += " struct " + Desc;
4019 S += "* Desc;\n";
4020
4021 Constructor += "(void *fp, "; // Invoke function pointer.
4022 Constructor += "struct " + Desc; // Descriptor pointer.
4023 Constructor += " *desc";
4024
4025 if (BlockDeclRefs.size()) {
4026 // Output all "by copy" declarations.
4027 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4028 E = BlockByCopyDecls.end(); I != E; ++I) {
4029 S += " ";
4030 std::string FieldName = (*I)->getNameAsString();
4031 std::string ArgName = "_" + FieldName;
4032 // Handle nested closure invocation. For example:
4033 //
4034 // void (^myImportedBlock)(void);
4035 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
4036 //
4037 // void (^anotherBlock)(void);
4038 // anotherBlock = ^(void) {
4039 // myImportedBlock(); // import and invoke the closure
4040 // };
4041 //
4042 if (isTopLevelBlockPointerType((*I)->getType())) {
4043 S += "struct __block_impl *";
4044 Constructor += ", void *" + ArgName;
4045 } else {
4046 QualType QT = (*I)->getType();
4047 if (HasLocalVariableExternalStorage(*I))
4048 QT = Context->getPointerType(QT);
4049 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4050 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4051 Constructor += ", " + ArgName;
4052 }
4053 S += FieldName + ";\n";
4054 }
4055 // Output all "by ref" declarations.
4056 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4057 E = BlockByRefDecls.end(); I != E; ++I) {
4058 S += " ";
4059 std::string FieldName = (*I)->getNameAsString();
4060 std::string ArgName = "_" + FieldName;
4061 {
4062 std::string TypeString;
4063 RewriteByRefString(TypeString, FieldName, (*I));
4064 TypeString += " *";
4065 FieldName = TypeString + FieldName;
4066 ArgName = TypeString + ArgName;
4067 Constructor += ", " + ArgName;
4068 }
4069 S += FieldName + "; // by ref\n";
4070 }
4071 // Finish writing the constructor.
4072 Constructor += ", int flags=0)";
4073 // Initialize all "by copy" arguments.
4074 bool firsTime = true;
4075 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4076 E = BlockByCopyDecls.end(); I != E; ++I) {
4077 std::string Name = (*I)->getNameAsString();
4078 if (firsTime) {
4079 Constructor += " : ";
4080 firsTime = false;
4081 }
4082 else
4083 Constructor += ", ";
4084 if (isTopLevelBlockPointerType((*I)->getType()))
4085 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4086 else
4087 Constructor += Name + "(_" + Name + ")";
4088 }
4089 // Initialize all "by ref" arguments.
4090 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4091 E = BlockByRefDecls.end(); I != E; ++I) {
4092 std::string Name = (*I)->getNameAsString();
4093 if (firsTime) {
4094 Constructor += " : ";
4095 firsTime = false;
4096 }
4097 else
4098 Constructor += ", ";
4099 Constructor += Name + "(_" + Name + "->__forwarding)";
4100 }
4101
4102 Constructor += " {\n";
4103 if (GlobalVarDecl)
4104 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4105 else
4106 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4107 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4108
4109 Constructor += " Desc = desc;\n";
4110 } else {
4111 // Finish writing the constructor.
4112 Constructor += ", int flags=0) {\n";
4113 if (GlobalVarDecl)
4114 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4115 else
4116 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4117 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4118 Constructor += " Desc = desc;\n";
4119 }
4120 Constructor += " ";
4121 Constructor += "}\n";
4122 S += Constructor;
4123 S += "};\n";
4124 return S;
4125}
4126
4127std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4128 std::string ImplTag, int i,
4129 StringRef FunName,
4130 unsigned hasCopy) {
4131 std::string S = "\nstatic struct " + DescTag;
4132
Fariborz Jahanian8b08adb2012-05-03 21:44:12 +00004133 S += " {\n size_t reserved;\n";
4134 S += " size_t Block_size;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004135 if (hasCopy) {
4136 S += " void (*copy)(struct ";
4137 S += ImplTag; S += "*, struct ";
4138 S += ImplTag; S += "*);\n";
4139
4140 S += " void (*dispose)(struct ";
4141 S += ImplTag; S += "*);\n";
4142 }
4143 S += "} ";
4144
4145 S += DescTag + "_DATA = { 0, sizeof(struct ";
4146 S += ImplTag + ")";
4147 if (hasCopy) {
4148 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4149 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4150 }
4151 S += "};\n";
4152 return S;
4153}
4154
Fariborz Jahanian76a98be2012-04-17 18:40:53 +00004155/// getFunctionSourceLocation - returns start location of a function
4156/// definition. Complication arises when function has declared as
4157/// extern "C" or extern "C" {...}
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00004158static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
4159 FunctionDecl *FD) {
Fariborz Jahanianb5863da2012-04-19 16:30:28 +00004160 if (FD->isExternC() && !FD->isMain()) {
4161 const DeclContext *DC = FD->getDeclContext();
4162 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
4163 // if it is extern "C" {...}, return function decl's own location.
4164 if (!LSD->getRBraceLoc().isValid())
4165 return LSD->getExternLoc();
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00004166 }
Fariborz Jahanianb5863da2012-04-19 16:30:28 +00004167 if (FD->getStorageClassAsWritten() != SC_None)
4168 R.RewriteBlockLiteralFunctionDecl(FD);
Fariborz Jahanian76a98be2012-04-17 18:40:53 +00004169 return FD->getTypeSpecStartLoc();
4170}
4171
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004172void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4173 StringRef FunName) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004174 bool RewriteSC = (GlobalVarDecl &&
4175 !Blocks.empty() &&
4176 GlobalVarDecl->getStorageClass() == SC_Static &&
4177 GlobalVarDecl->getType().getCVRQualifiers());
4178 if (RewriteSC) {
4179 std::string SC(" void __");
4180 SC += GlobalVarDecl->getNameAsString();
4181 SC += "() {}";
4182 InsertText(FunLocStart, SC);
4183 }
4184
4185 // Insert closures that were part of the function.
4186 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4187 CollectBlockDeclRefInfo(Blocks[i]);
4188 // Need to copy-in the inner copied-in variables not actually used in this
4189 // block.
4190 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00004191 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004192 ValueDecl *VD = Exp->getDecl();
4193 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00004194 if (!VD->hasAttr<BlocksAttr>()) {
4195 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4196 BlockByCopyDeclsPtrSet.insert(VD);
4197 BlockByCopyDecls.push_back(VD);
4198 }
4199 continue;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004200 }
John McCallf4b88a42012-03-10 09:33:50 +00004201
4202 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004203 BlockByRefDeclsPtrSet.insert(VD);
4204 BlockByRefDecls.push_back(VD);
4205 }
John McCallf4b88a42012-03-10 09:33:50 +00004206
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004207 // imported objects in the inner blocks not used in the outer
4208 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00004209 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004210 VD->getType()->isBlockPointerType())
4211 ImportedBlockDecls.insert(VD);
4212 }
4213
4214 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4215 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4216
4217 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4218
4219 InsertText(FunLocStart, CI);
4220
4221 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4222
4223 InsertText(FunLocStart, CF);
4224
4225 if (ImportedBlockDecls.size()) {
4226 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4227 InsertText(FunLocStart, HF);
4228 }
4229 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4230 ImportedBlockDecls.size() > 0);
4231 InsertText(FunLocStart, BD);
4232
4233 BlockDeclRefs.clear();
4234 BlockByRefDecls.clear();
4235 BlockByRefDeclsPtrSet.clear();
4236 BlockByCopyDecls.clear();
4237 BlockByCopyDeclsPtrSet.clear();
4238 ImportedBlockDecls.clear();
4239 }
4240 if (RewriteSC) {
4241 // Must insert any 'const/volatile/static here. Since it has been
4242 // removed as result of rewriting of block literals.
4243 std::string SC;
4244 if (GlobalVarDecl->getStorageClass() == SC_Static)
4245 SC = "static ";
4246 if (GlobalVarDecl->getType().isConstQualified())
4247 SC += "const ";
4248 if (GlobalVarDecl->getType().isVolatileQualified())
4249 SC += "volatile ";
4250 if (GlobalVarDecl->getType().isRestrictQualified())
4251 SC += "restrict ";
4252 InsertText(FunLocStart, SC);
4253 }
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004254 if (GlobalConstructionExp) {
4255 // extra fancy dance for global literal expression.
4256
4257 // Always the latest block expression on the block stack.
4258 std::string Tag = "__";
4259 Tag += FunName;
4260 Tag += "_block_impl_";
4261 Tag += utostr(Blocks.size()-1);
4262 std::string globalBuf = "static ";
4263 globalBuf += Tag; globalBuf += " ";
4264 std::string SStr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004265
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004266 llvm::raw_string_ostream constructorExprBuf(SStr);
4267 GlobalConstructionExp->printPretty(constructorExprBuf, *Context, 0,
4268 PrintingPolicy(LangOpts));
4269 globalBuf += constructorExprBuf.str();
4270 globalBuf += ";\n";
4271 InsertText(FunLocStart, globalBuf);
4272 GlobalConstructionExp = 0;
4273 }
4274
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004275 Blocks.clear();
4276 InnerDeclRefsCount.clear();
4277 InnerDeclRefs.clear();
4278 RewrittenBlockExprs.clear();
4279}
4280
4281void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Fariborz Jahanian04189532012-04-25 17:56:48 +00004282 SourceLocation FunLocStart =
4283 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4284 : FD->getTypeSpecStartLoc();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004285 StringRef FuncName = FD->getName();
4286
4287 SynthesizeBlockLiterals(FunLocStart, FuncName);
4288}
4289
4290static void BuildUniqueMethodName(std::string &Name,
4291 ObjCMethodDecl *MD) {
4292 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4293 Name = IFace->getName();
4294 Name += "__" + MD->getSelector().getAsString();
4295 // Convert colons to underscores.
4296 std::string::size_type loc = 0;
4297 while ((loc = Name.find(":", loc)) != std::string::npos)
4298 Name.replace(loc, 1, "_");
4299}
4300
4301void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4302 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4303 //SourceLocation FunLocStart = MD->getLocStart();
4304 SourceLocation FunLocStart = MD->getLocStart();
4305 std::string FuncName;
4306 BuildUniqueMethodName(FuncName, MD);
4307 SynthesizeBlockLiterals(FunLocStart, FuncName);
4308}
4309
4310void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4311 for (Stmt::child_range CI = S->children(); CI; ++CI)
4312 if (*CI) {
4313 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4314 GetBlockDeclRefExprs(CBE->getBody());
4315 else
4316 GetBlockDeclRefExprs(*CI);
4317 }
4318 // Handle specific things.
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004319 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4320 if (DRE->refersToEnclosingLocal()) {
4321 // FIXME: Handle enums.
4322 if (!isa<FunctionDecl>(DRE->getDecl()))
4323 BlockDeclRefs.push_back(DRE);
4324 if (HasLocalVariableExternalStorage(DRE->getDecl()))
4325 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004326 }
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004327 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004328
4329 return;
4330}
4331
4332void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +00004333 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004334 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
4335 for (Stmt::child_range CI = S->children(); CI; ++CI)
4336 if (*CI) {
4337 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4338 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4339 GetInnerBlockDeclRefExprs(CBE->getBody(),
4340 InnerBlockDeclRefs,
4341 InnerContexts);
4342 }
4343 else
4344 GetInnerBlockDeclRefExprs(*CI,
4345 InnerBlockDeclRefs,
4346 InnerContexts);
4347
4348 }
4349 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00004350 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4351 if (DRE->refersToEnclosingLocal()) {
4352 if (!isa<FunctionDecl>(DRE->getDecl()) &&
4353 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
4354 InnerBlockDeclRefs.push_back(DRE);
4355 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4356 if (Var->isFunctionOrMethodVarDecl())
4357 ImportedLocalExternalDecls.insert(Var);
4358 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004359 }
4360
4361 return;
4362}
4363
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004364/// convertObjCTypeToCStyleType - This routine converts such objc types
4365/// as qualified objects, and blocks to their closest c/c++ types that
4366/// it can. It returns true if input type was modified.
4367bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4368 QualType oldT = T;
4369 convertBlockPointerToFunctionPointer(T);
4370 if (T->isFunctionPointerType()) {
4371 QualType PointeeTy;
4372 if (const PointerType* PT = T->getAs<PointerType>()) {
4373 PointeeTy = PT->getPointeeType();
4374 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4375 T = convertFunctionTypeOfBlocks(FT);
4376 T = Context->getPointerType(T);
4377 }
4378 }
4379 }
4380
4381 convertToUnqualifiedObjCType(T);
4382 return T != oldT;
4383}
4384
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004385/// convertFunctionTypeOfBlocks - This routine converts a function type
4386/// whose result type may be a block pointer or whose argument type(s)
4387/// might be block pointers to an equivalent function type replacing
4388/// all block pointers to function pointers.
4389QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4390 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4391 // FTP will be null for closures that don't take arguments.
4392 // Generate a funky cast.
4393 SmallVector<QualType, 8> ArgTypes;
4394 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004395 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004396
4397 if (FTP) {
4398 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4399 E = FTP->arg_type_end(); I && (I != E); ++I) {
4400 QualType t = *I;
4401 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004402 if (convertObjCTypeToCStyleType(t))
4403 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004404 ArgTypes.push_back(t);
4405 }
4406 }
4407 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004408 if (modified)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004409 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
4410 else FuncType = QualType(FT, 0);
4411 return FuncType;
4412}
4413
4414Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4415 // Navigate to relevant type information.
4416 const BlockPointerType *CPT = 0;
4417
4418 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4419 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004420 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4421 CPT = MExpr->getType()->getAs<BlockPointerType>();
4422 }
4423 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4424 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4425 }
4426 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4427 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4428 else if (const ConditionalOperator *CEXPR =
4429 dyn_cast<ConditionalOperator>(BlockExp)) {
4430 Expr *LHSExp = CEXPR->getLHS();
4431 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4432 Expr *RHSExp = CEXPR->getRHS();
4433 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4434 Expr *CONDExp = CEXPR->getCond();
4435 ConditionalOperator *CondExpr =
4436 new (Context) ConditionalOperator(CONDExp,
4437 SourceLocation(), cast<Expr>(LHSStmt),
4438 SourceLocation(), cast<Expr>(RHSStmt),
4439 Exp->getType(), VK_RValue, OK_Ordinary);
4440 return CondExpr;
4441 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4442 CPT = IRE->getType()->getAs<BlockPointerType>();
4443 } else if (const PseudoObjectExpr *POE
4444 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4445 CPT = POE->getType()->castAs<BlockPointerType>();
4446 } else {
4447 assert(1 && "RewriteBlockClass: Bad type");
4448 }
4449 assert(CPT && "RewriteBlockClass: Bad type");
4450 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4451 assert(FT && "RewriteBlockClass: Bad type");
4452 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4453 // FTP will be null for closures that don't take arguments.
4454
4455 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4456 SourceLocation(), SourceLocation(),
4457 &Context->Idents.get("__block_impl"));
4458 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4459
4460 // Generate a funky cast.
4461 SmallVector<QualType, 8> ArgTypes;
4462
4463 // Push the block argument type.
4464 ArgTypes.push_back(PtrBlock);
4465 if (FTP) {
4466 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4467 E = FTP->arg_type_end(); I && (I != E); ++I) {
4468 QualType t = *I;
4469 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4470 if (!convertBlockPointerToFunctionPointer(t))
4471 convertToUnqualifiedObjCType(t);
4472 ArgTypes.push_back(t);
4473 }
4474 }
4475 // Now do the pointer to function cast.
4476 QualType PtrToFuncCastType
4477 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
4478
4479 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4480
4481 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4482 CK_BitCast,
4483 const_cast<Expr*>(BlockExp));
4484 // Don't forget the parens to enforce the proper binding.
4485 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4486 BlkCast);
4487 //PE->dump();
4488
4489 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4490 SourceLocation(),
4491 &Context->Idents.get("FuncPtr"),
4492 Context->VoidPtrTy, 0,
4493 /*BitWidth=*/0, /*Mutable=*/true,
4494 /*HasInit=*/false);
4495 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4496 FD->getType(), VK_LValue,
4497 OK_Ordinary);
4498
4499
4500 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4501 CK_BitCast, ME);
4502 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4503
4504 SmallVector<Expr*, 8> BlkExprs;
4505 // Add the implicit argument.
4506 BlkExprs.push_back(BlkCast);
4507 // Add the user arguments.
4508 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4509 E = Exp->arg_end(); I != E; ++I) {
4510 BlkExprs.push_back(*I);
4511 }
4512 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4513 BlkExprs.size(),
4514 Exp->getType(), VK_RValue,
4515 SourceLocation());
4516 return CE;
4517}
4518
4519// We need to return the rewritten expression to handle cases where the
John McCallf4b88a42012-03-10 09:33:50 +00004520// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004521// For example:
4522//
4523// int main() {
4524// __block Foo *f;
4525// __block int i;
4526//
4527// void (^myblock)() = ^() {
John McCallf4b88a42012-03-10 09:33:50 +00004528// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004529// i = 77;
4530// };
4531//}
John McCallf4b88a42012-03-10 09:33:50 +00004532Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004533 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4534 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00004535 ValueDecl *VD = DeclRefExp->getDecl();
4536 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004537
4538 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4539 SourceLocation(),
4540 &Context->Idents.get("__forwarding"),
4541 Context->VoidPtrTy, 0,
4542 /*BitWidth=*/0, /*Mutable=*/true,
4543 /*HasInit=*/false);
4544 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4545 FD, SourceLocation(),
4546 FD->getType(), VK_LValue,
4547 OK_Ordinary);
4548
4549 StringRef Name = VD->getName();
4550 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
4551 &Context->Idents.get(Name),
4552 Context->VoidPtrTy, 0,
4553 /*BitWidth=*/0, /*Mutable=*/true,
4554 /*HasInit=*/false);
4555 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4556 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4557
4558
4559
4560 // Need parens to enforce precedence.
4561 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4562 DeclRefExp->getExprLoc(),
4563 ME);
4564 ReplaceStmt(DeclRefExp, PE);
4565 return PE;
4566}
4567
4568// Rewrites the imported local variable V with external storage
4569// (static, extern, etc.) as *V
4570//
4571Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4572 ValueDecl *VD = DRE->getDecl();
4573 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4574 if (!ImportedLocalExternalDecls.count(Var))
4575 return DRE;
4576 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4577 VK_LValue, OK_Ordinary,
4578 DRE->getLocation());
4579 // Need parens to enforce precedence.
4580 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4581 Exp);
4582 ReplaceStmt(DRE, PE);
4583 return PE;
4584}
4585
4586void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4587 SourceLocation LocStart = CE->getLParenLoc();
4588 SourceLocation LocEnd = CE->getRParenLoc();
4589
4590 // Need to avoid trying to rewrite synthesized casts.
4591 if (LocStart.isInvalid())
4592 return;
4593 // Need to avoid trying to rewrite casts contained in macros.
4594 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4595 return;
4596
4597 const char *startBuf = SM->getCharacterData(LocStart);
4598 const char *endBuf = SM->getCharacterData(LocEnd);
4599 QualType QT = CE->getType();
4600 const Type* TypePtr = QT->getAs<Type>();
4601 if (isa<TypeOfExprType>(TypePtr)) {
4602 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4603 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4604 std::string TypeAsString = "(";
4605 RewriteBlockPointerType(TypeAsString, QT);
4606 TypeAsString += ")";
4607 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4608 return;
4609 }
4610 // advance the location to startArgList.
4611 const char *argPtr = startBuf;
4612
4613 while (*argPtr++ && (argPtr < endBuf)) {
4614 switch (*argPtr) {
4615 case '^':
4616 // Replace the '^' with '*'.
4617 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4618 ReplaceText(LocStart, 1, "*");
4619 break;
4620 }
4621 }
4622 return;
4623}
4624
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004625void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4626 CastKind CastKind = IC->getCastKind();
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004627 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4628 CastKind != CK_AnyPointerToBlockPointerCast)
4629 return;
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004630
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004631 QualType QT = IC->getType();
4632 (void)convertBlockPointerToFunctionPointer(QT);
4633 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4634 std::string Str = "(";
4635 Str += TypeString;
4636 Str += ")";
4637 InsertText(IC->getSubExpr()->getLocStart(), &Str[0], Str.size());
4638
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004639 return;
4640}
4641
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004642void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4643 SourceLocation DeclLoc = FD->getLocation();
4644 unsigned parenCount = 0;
4645
4646 // We have 1 or more arguments that have closure pointers.
4647 const char *startBuf = SM->getCharacterData(DeclLoc);
4648 const char *startArgList = strchr(startBuf, '(');
4649
4650 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4651
4652 parenCount++;
4653 // advance the location to startArgList.
4654 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4655 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4656
4657 const char *argPtr = startArgList;
4658
4659 while (*argPtr++ && parenCount) {
4660 switch (*argPtr) {
4661 case '^':
4662 // Replace the '^' with '*'.
4663 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4664 ReplaceText(DeclLoc, 1, "*");
4665 break;
4666 case '(':
4667 parenCount++;
4668 break;
4669 case ')':
4670 parenCount--;
4671 break;
4672 }
4673 }
4674 return;
4675}
4676
4677bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4678 const FunctionProtoType *FTP;
4679 const PointerType *PT = QT->getAs<PointerType>();
4680 if (PT) {
4681 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4682 } else {
4683 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4684 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4685 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4686 }
4687 if (FTP) {
4688 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4689 E = FTP->arg_type_end(); I != E; ++I)
4690 if (isTopLevelBlockPointerType(*I))
4691 return true;
4692 }
4693 return false;
4694}
4695
4696bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4697 const FunctionProtoType *FTP;
4698 const PointerType *PT = QT->getAs<PointerType>();
4699 if (PT) {
4700 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4701 } else {
4702 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4703 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4704 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4705 }
4706 if (FTP) {
4707 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4708 E = FTP->arg_type_end(); I != E; ++I) {
4709 if ((*I)->isObjCQualifiedIdType())
4710 return true;
4711 if ((*I)->isObjCObjectPointerType() &&
4712 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4713 return true;
4714 }
4715
4716 }
4717 return false;
4718}
4719
4720void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4721 const char *&RParen) {
4722 const char *argPtr = strchr(Name, '(');
4723 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4724
4725 LParen = argPtr; // output the start.
4726 argPtr++; // skip past the left paren.
4727 unsigned parenCount = 1;
4728
4729 while (*argPtr && parenCount) {
4730 switch (*argPtr) {
4731 case '(': parenCount++; break;
4732 case ')': parenCount--; break;
4733 default: break;
4734 }
4735 if (parenCount) argPtr++;
4736 }
4737 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4738 RParen = argPtr; // output the end
4739}
4740
4741void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4742 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4743 RewriteBlockPointerFunctionArgs(FD);
4744 return;
4745 }
4746 // Handle Variables and Typedefs.
4747 SourceLocation DeclLoc = ND->getLocation();
4748 QualType DeclT;
4749 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4750 DeclT = VD->getType();
4751 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4752 DeclT = TDD->getUnderlyingType();
4753 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4754 DeclT = FD->getType();
4755 else
4756 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4757
4758 const char *startBuf = SM->getCharacterData(DeclLoc);
4759 const char *endBuf = startBuf;
4760 // scan backward (from the decl location) for the end of the previous decl.
4761 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4762 startBuf--;
4763 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4764 std::string buf;
4765 unsigned OrigLength=0;
4766 // *startBuf != '^' if we are dealing with a pointer to function that
4767 // may take block argument types (which will be handled below).
4768 if (*startBuf == '^') {
4769 // Replace the '^' with '*', computing a negative offset.
4770 buf = '*';
4771 startBuf++;
4772 OrigLength++;
4773 }
4774 while (*startBuf != ')') {
4775 buf += *startBuf;
4776 startBuf++;
4777 OrigLength++;
4778 }
4779 buf += ')';
4780 OrigLength++;
4781
4782 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4783 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4784 // Replace the '^' with '*' for arguments.
4785 // Replace id<P> with id/*<>*/
4786 DeclLoc = ND->getLocation();
4787 startBuf = SM->getCharacterData(DeclLoc);
4788 const char *argListBegin, *argListEnd;
4789 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4790 while (argListBegin < argListEnd) {
4791 if (*argListBegin == '^')
4792 buf += '*';
4793 else if (*argListBegin == '<') {
4794 buf += "/*";
4795 buf += *argListBegin++;
4796 OrigLength++;;
4797 while (*argListBegin != '>') {
4798 buf += *argListBegin++;
4799 OrigLength++;
4800 }
4801 buf += *argListBegin;
4802 buf += "*/";
4803 }
4804 else
4805 buf += *argListBegin;
4806 argListBegin++;
4807 OrigLength++;
4808 }
4809 buf += ')';
4810 OrigLength++;
4811 }
4812 ReplaceText(Start, OrigLength, buf);
4813
4814 return;
4815}
4816
4817
4818/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4819/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4820/// struct Block_byref_id_object *src) {
4821/// _Block_object_assign (&_dest->object, _src->object,
4822/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4823/// [|BLOCK_FIELD_IS_WEAK]) // object
4824/// _Block_object_assign(&_dest->object, _src->object,
4825/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4826/// [|BLOCK_FIELD_IS_WEAK]) // block
4827/// }
4828/// And:
4829/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4830/// _Block_object_dispose(_src->object,
4831/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4832/// [|BLOCK_FIELD_IS_WEAK]) // object
4833/// _Block_object_dispose(_src->object,
4834/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4835/// [|BLOCK_FIELD_IS_WEAK]) // block
4836/// }
4837
4838std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4839 int flag) {
4840 std::string S;
4841 if (CopyDestroyCache.count(flag))
4842 return S;
4843 CopyDestroyCache.insert(flag);
4844 S = "static void __Block_byref_id_object_copy_";
4845 S += utostr(flag);
4846 S += "(void *dst, void *src) {\n";
4847
4848 // offset into the object pointer is computed as:
4849 // void * + void* + int + int + void* + void *
4850 unsigned IntSize =
4851 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4852 unsigned VoidPtrSize =
4853 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4854
4855 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4856 S += " _Block_object_assign((char*)dst + ";
4857 S += utostr(offset);
4858 S += ", *(void * *) ((char*)src + ";
4859 S += utostr(offset);
4860 S += "), ";
4861 S += utostr(flag);
4862 S += ");\n}\n";
4863
4864 S += "static void __Block_byref_id_object_dispose_";
4865 S += utostr(flag);
4866 S += "(void *src) {\n";
4867 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4868 S += utostr(offset);
4869 S += "), ";
4870 S += utostr(flag);
4871 S += ");\n}\n";
4872 return S;
4873}
4874
4875/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4876/// the declaration into:
4877/// struct __Block_byref_ND {
4878/// void *__isa; // NULL for everything except __weak pointers
4879/// struct __Block_byref_ND *__forwarding;
4880/// int32_t __flags;
4881/// int32_t __size;
4882/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4883/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4884/// typex ND;
4885/// };
4886///
4887/// It then replaces declaration of ND variable with:
4888/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4889/// __size=sizeof(struct __Block_byref_ND),
4890/// ND=initializer-if-any};
4891///
4892///
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00004893void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
4894 bool lastDecl) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004895 int flag = 0;
4896 int isa = 0;
4897 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4898 if (DeclLoc.isInvalid())
4899 // If type location is missing, it is because of missing type (a warning).
4900 // Use variable's location which is good for this case.
4901 DeclLoc = ND->getLocation();
4902 const char *startBuf = SM->getCharacterData(DeclLoc);
4903 SourceLocation X = ND->getLocEnd();
4904 X = SM->getExpansionLoc(X);
4905 const char *endBuf = SM->getCharacterData(X);
4906 std::string Name(ND->getNameAsString());
4907 std::string ByrefType;
4908 RewriteByRefString(ByrefType, Name, ND, true);
4909 ByrefType += " {\n";
4910 ByrefType += " void *__isa;\n";
4911 RewriteByRefString(ByrefType, Name, ND);
4912 ByrefType += " *__forwarding;\n";
4913 ByrefType += " int __flags;\n";
4914 ByrefType += " int __size;\n";
4915 // Add void *__Block_byref_id_object_copy;
4916 // void *__Block_byref_id_object_dispose; if needed.
4917 QualType Ty = ND->getType();
4918 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4919 if (HasCopyAndDispose) {
4920 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4921 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4922 }
4923
4924 QualType T = Ty;
4925 (void)convertBlockPointerToFunctionPointer(T);
4926 T.getAsStringInternal(Name, Context->getPrintingPolicy());
4927
4928 ByrefType += " " + Name + ";\n";
4929 ByrefType += "};\n";
4930 // Insert this type in global scope. It is needed by helper function.
4931 SourceLocation FunLocStart;
4932 if (CurFunctionDef)
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00004933 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004934 else {
4935 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4936 FunLocStart = CurMethodDef->getLocStart();
4937 }
4938 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00004939
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004940 if (Ty.isObjCGCWeak()) {
4941 flag |= BLOCK_FIELD_IS_WEAK;
4942 isa = 1;
4943 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004944 if (HasCopyAndDispose) {
4945 flag = BLOCK_BYREF_CALLER;
4946 QualType Ty = ND->getType();
4947 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4948 if (Ty->isBlockPointerType())
4949 flag |= BLOCK_FIELD_IS_BLOCK;
4950 else
4951 flag |= BLOCK_FIELD_IS_OBJECT;
4952 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
4953 if (!HF.empty())
4954 InsertText(FunLocStart, HF);
4955 }
4956
4957 // struct __Block_byref_ND ND =
4958 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4959 // initializer-if-any};
4960 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanian104dbf92012-04-11 23:57:12 +00004961 // FIXME. rewriter does not support __block c++ objects which
4962 // require construction.
Fariborz Jahanian65a7c682012-04-26 23:20:25 +00004963 if (hasInit)
4964 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
4965 CXXConstructorDecl *CXXDecl = CExp->getConstructor();
4966 if (CXXDecl && CXXDecl->isDefaultConstructor())
4967 hasInit = false;
4968 }
4969
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004970 unsigned flags = 0;
4971 if (HasCopyAndDispose)
4972 flags |= BLOCK_HAS_COPY_DISPOSE;
4973 Name = ND->getNameAsString();
4974 ByrefType.clear();
4975 RewriteByRefString(ByrefType, Name, ND);
4976 std::string ForwardingCastType("(");
4977 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00004978 ByrefType += " " + Name + " = {(void*)";
4979 ByrefType += utostr(isa);
4980 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4981 ByrefType += utostr(flags);
4982 ByrefType += ", ";
4983 ByrefType += "sizeof(";
4984 RewriteByRefString(ByrefType, Name, ND);
4985 ByrefType += ")";
4986 if (HasCopyAndDispose) {
4987 ByrefType += ", __Block_byref_id_object_copy_";
4988 ByrefType += utostr(flag);
4989 ByrefType += ", __Block_byref_id_object_dispose_";
4990 ByrefType += utostr(flag);
4991 }
4992
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00004993 if (!firstDecl) {
4994 // In multiple __block declarations, and for all but 1st declaration,
4995 // find location of the separating comma. This would be start location
4996 // where new text is to be inserted.
4997 DeclLoc = ND->getLocation();
4998 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
4999 const char *commaBuf = startDeclBuf;
5000 while (*commaBuf != ',')
5001 commaBuf--;
5002 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5003 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5004 startBuf = commaBuf;
5005 }
5006
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005007 if (!hasInit) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005008 ByrefType += "};\n";
5009 unsigned nameSize = Name.size();
5010 // for block or function pointer declaration. Name is aleady
5011 // part of the declaration.
5012 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5013 nameSize = 1;
5014 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5015 }
5016 else {
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005017 ByrefType += ", ";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005018 SourceLocation startLoc;
5019 Expr *E = ND->getInit();
5020 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5021 startLoc = ECE->getLParenLoc();
5022 else
5023 startLoc = E->getLocStart();
5024 startLoc = SM->getExpansionLoc(startLoc);
5025 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005026 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005027
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005028 const char separator = lastDecl ? ';' : ',';
5029 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5030 const char *separatorBuf = strchr(startInitializerBuf, separator);
5031 assert((*separatorBuf == separator) &&
5032 "RewriteByRefVar: can't find ';' or ','");
5033 SourceLocation separatorLoc =
5034 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
5035
5036 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005037 }
5038 return;
5039}
5040
5041void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5042 // Add initializers for any closure decl refs.
5043 GetBlockDeclRefExprs(Exp->getBody());
5044 if (BlockDeclRefs.size()) {
5045 // Unique all "by copy" declarations.
5046 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005047 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005048 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5049 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5050 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5051 }
5052 }
5053 // Unique all "by ref" declarations.
5054 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005055 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005056 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5057 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5058 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5059 }
5060 }
5061 // Find any imported blocks...they will need special attention.
5062 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005063 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005064 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5065 BlockDeclRefs[i]->getType()->isBlockPointerType())
5066 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5067 }
5068}
5069
5070FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5071 IdentifierInfo *ID = &Context->Idents.get(name);
5072 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5073 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5074 SourceLocation(), ID, FType, 0, SC_Extern,
5075 SC_None, false, false);
5076}
5077
5078Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +00005079 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00005080
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005081 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00005082
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005083 Blocks.push_back(Exp);
5084
5085 CollectBlockDeclRefInfo(Exp);
5086
5087 // Add inner imported variables now used in current block.
5088 int countOfInnerDecls = 0;
5089 if (!InnerBlockDeclRefs.empty()) {
5090 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00005091 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005092 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00005093 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005094 // We need to save the copied-in variables in nested
5095 // blocks because it is needed at the end for some of the API generations.
5096 // See SynthesizeBlockLiterals routine.
5097 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5098 BlockDeclRefs.push_back(Exp);
5099 BlockByCopyDeclsPtrSet.insert(VD);
5100 BlockByCopyDecls.push_back(VD);
5101 }
John McCallf4b88a42012-03-10 09:33:50 +00005102 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005103 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5104 BlockDeclRefs.push_back(Exp);
5105 BlockByRefDeclsPtrSet.insert(VD);
5106 BlockByRefDecls.push_back(VD);
5107 }
5108 }
5109 // Find any imported blocks...they will need special attention.
5110 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005111 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005112 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5113 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5114 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5115 }
5116 InnerDeclRefsCount.push_back(countOfInnerDecls);
5117
5118 std::string FuncName;
5119
5120 if (CurFunctionDef)
5121 FuncName = CurFunctionDef->getNameAsString();
5122 else if (CurMethodDef)
5123 BuildUniqueMethodName(FuncName, CurMethodDef);
5124 else if (GlobalVarDecl)
5125 FuncName = std::string(GlobalVarDecl->getNameAsString());
5126
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005127 bool GlobalBlockExpr =
5128 block->getDeclContext()->getRedeclContext()->isFileContext();
5129
5130 if (GlobalBlockExpr && !GlobalVarDecl) {
5131 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5132 GlobalBlockExpr = false;
5133 }
5134
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005135 std::string BlockNumber = utostr(Blocks.size()-1);
5136
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005137 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5138
5139 // Get a pointer to the function type so we can cast appropriately.
5140 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5141 QualType FType = Context->getPointerType(BFT);
5142
5143 FunctionDecl *FD;
5144 Expr *NewRep;
5145
5146 // Simulate a contructor call...
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005147 std::string Tag;
5148
5149 if (GlobalBlockExpr)
5150 Tag = "__global_";
5151 else
5152 Tag = "__";
5153 Tag += FuncName + "_block_impl_" + BlockNumber;
5154
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005155 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00005156 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005157 SourceLocation());
5158
5159 SmallVector<Expr*, 4> InitExprs;
5160
5161 // Initialize the block function.
5162 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00005163 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5164 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005165 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5166 CK_BitCast, Arg);
5167 InitExprs.push_back(castExpr);
5168
5169 // Initialize the block descriptor.
5170 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5171
5172 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5173 SourceLocation(), SourceLocation(),
5174 &Context->Idents.get(DescData.c_str()),
5175 Context->VoidPtrTy, 0,
5176 SC_Static, SC_None);
5177 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00005178 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005179 Context->VoidPtrTy,
5180 VK_LValue,
5181 SourceLocation()),
5182 UO_AddrOf,
5183 Context->getPointerType(Context->VoidPtrTy),
5184 VK_RValue, OK_Ordinary,
5185 SourceLocation());
5186 InitExprs.push_back(DescRefExpr);
5187
5188 // Add initializers for any closure decl refs.
5189 if (BlockDeclRefs.size()) {
5190 Expr *Exp;
5191 // Output all "by copy" declarations.
5192 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
5193 E = BlockByCopyDecls.end(); I != E; ++I) {
5194 if (isObjCType((*I)->getType())) {
5195 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5196 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005197 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5198 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005199 if (HasLocalVariableExternalStorage(*I)) {
5200 QualType QT = (*I)->getType();
5201 QT = Context->getPointerType(QT);
5202 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5203 OK_Ordinary, SourceLocation());
5204 }
5205 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5206 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005207 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5208 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005209 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5210 CK_BitCast, Arg);
5211 } else {
5212 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005213 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5214 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005215 if (HasLocalVariableExternalStorage(*I)) {
5216 QualType QT = (*I)->getType();
5217 QT = Context->getPointerType(QT);
5218 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5219 OK_Ordinary, SourceLocation());
5220 }
5221
5222 }
5223 InitExprs.push_back(Exp);
5224 }
5225 // Output all "by ref" declarations.
5226 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
5227 E = BlockByRefDecls.end(); I != E; ++I) {
5228 ValueDecl *ND = (*I);
5229 std::string Name(ND->getNameAsString());
5230 std::string RecName;
5231 RewriteByRefString(RecName, Name, ND, true);
5232 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5233 + sizeof("struct"));
5234 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5235 SourceLocation(), SourceLocation(),
5236 II);
5237 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5238 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5239
5240 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005241 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005242 SourceLocation());
5243 bool isNestedCapturedVar = false;
5244 if (block)
5245 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5246 ce = block->capture_end(); ci != ce; ++ci) {
5247 const VarDecl *variable = ci->getVariable();
5248 if (variable == ND && ci->isNested()) {
5249 assert (ci->isByRef() &&
5250 "SynthBlockInitExpr - captured block variable is not byref");
5251 isNestedCapturedVar = true;
5252 break;
5253 }
5254 }
5255 // captured nested byref variable has its address passed. Do not take
5256 // its address again.
5257 if (!isNestedCapturedVar)
5258 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5259 Context->getPointerType(Exp->getType()),
5260 VK_RValue, OK_Ordinary, SourceLocation());
5261 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5262 InitExprs.push_back(Exp);
5263 }
5264 }
5265 if (ImportedBlockDecls.size()) {
5266 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5267 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5268 unsigned IntSize =
5269 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5270 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5271 Context->IntTy, SourceLocation());
5272 InitExprs.push_back(FlagExp);
5273 }
5274 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
5275 FType, VK_LValue, SourceLocation());
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005276
5277 if (GlobalBlockExpr) {
5278 assert (GlobalConstructionExp == 0 &&
5279 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5280 GlobalConstructionExp = NewRep;
5281 NewRep = DRE;
5282 }
5283
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005284 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5285 Context->getPointerType(NewRep->getType()),
5286 VK_RValue, OK_Ordinary, SourceLocation());
5287 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5288 NewRep);
5289 BlockDeclRefs.clear();
5290 BlockByRefDecls.clear();
5291 BlockByRefDeclsPtrSet.clear();
5292 BlockByCopyDecls.clear();
5293 BlockByCopyDeclsPtrSet.clear();
5294 ImportedBlockDecls.clear();
5295 return NewRep;
5296}
5297
5298bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5299 if (const ObjCForCollectionStmt * CS =
5300 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5301 return CS->getElement() == DS;
5302 return false;
5303}
5304
5305//===----------------------------------------------------------------------===//
5306// Function Body / Expression rewriting
5307//===----------------------------------------------------------------------===//
5308
5309Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5310 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5311 isa<DoStmt>(S) || isa<ForStmt>(S))
5312 Stmts.push_back(S);
5313 else if (isa<ObjCForCollectionStmt>(S)) {
5314 Stmts.push_back(S);
5315 ObjCBcLabelNo.push_back(++BcLabelCount);
5316 }
5317
5318 // Pseudo-object operations and ivar references need special
5319 // treatment because we're going to recursively rewrite them.
5320 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5321 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5322 return RewritePropertyOrImplicitSetter(PseudoOp);
5323 } else {
5324 return RewritePropertyOrImplicitGetter(PseudoOp);
5325 }
5326 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5327 return RewriteObjCIvarRefExpr(IvarRefExpr);
5328 }
5329
5330 SourceRange OrigStmtRange = S->getSourceRange();
5331
5332 // Perform a bottom up rewrite of all children.
5333 for (Stmt::child_range CI = S->children(); CI; ++CI)
5334 if (*CI) {
5335 Stmt *childStmt = (*CI);
5336 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5337 if (newStmt) {
5338 *CI = newStmt;
5339 }
5340 }
5341
5342 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00005343 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005344 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5345 InnerContexts.insert(BE->getBlockDecl());
5346 ImportedLocalExternalDecls.clear();
5347 GetInnerBlockDeclRefExprs(BE->getBody(),
5348 InnerBlockDeclRefs, InnerContexts);
5349 // Rewrite the block body in place.
5350 Stmt *SaveCurrentBody = CurrentBody;
5351 CurrentBody = BE->getBody();
5352 PropParentMap = 0;
5353 // block literal on rhs of a property-dot-sytax assignment
5354 // must be replaced by its synthesize ast so getRewrittenText
5355 // works as expected. In this case, what actually ends up on RHS
5356 // is the blockTranscribed which is the helper function for the
5357 // block literal; as in: self.c = ^() {[ace ARR];};
5358 bool saveDisableReplaceStmt = DisableReplaceStmt;
5359 DisableReplaceStmt = false;
5360 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5361 DisableReplaceStmt = saveDisableReplaceStmt;
5362 CurrentBody = SaveCurrentBody;
5363 PropParentMap = 0;
5364 ImportedLocalExternalDecls.clear();
5365 // Now we snarf the rewritten text and stash it away for later use.
5366 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5367 RewrittenBlockExprs[BE] = Str;
5368
5369 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5370
5371 //blockTranscribed->dump();
5372 ReplaceStmt(S, blockTranscribed);
5373 return blockTranscribed;
5374 }
5375 // Handle specific things.
5376 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5377 return RewriteAtEncode(AtEncode);
5378
5379 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5380 return RewriteAtSelector(AtSelector);
5381
5382 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5383 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian55947042012-03-27 20:17:30 +00005384
5385 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5386 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00005387
Patrick Beardeb382ec2012-04-19 00:25:12 +00005388 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5389 return RewriteObjCBoxedExpr(BoxedExpr);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00005390
5391 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5392 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005393
5394 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5395 dyn_cast<ObjCDictionaryLiteral>(S))
5396 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005397
5398 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5399#if 0
5400 // Before we rewrite it, put the original message expression in a comment.
5401 SourceLocation startLoc = MessExpr->getLocStart();
5402 SourceLocation endLoc = MessExpr->getLocEnd();
5403
5404 const char *startBuf = SM->getCharacterData(startLoc);
5405 const char *endBuf = SM->getCharacterData(endLoc);
5406
5407 std::string messString;
5408 messString += "// ";
5409 messString.append(startBuf, endBuf-startBuf+1);
5410 messString += "\n";
5411
5412 // FIXME: Missing definition of
5413 // InsertText(clang::SourceLocation, char const*, unsigned int).
5414 // InsertText(startLoc, messString.c_str(), messString.size());
5415 // Tried this, but it didn't work either...
5416 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5417#endif
5418 return RewriteMessageExpr(MessExpr);
5419 }
5420
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00005421 if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
5422 dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5423 return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5424 }
5425
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005426 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5427 return RewriteObjCTryStmt(StmtTry);
5428
5429 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5430 return RewriteObjCSynchronizedStmt(StmtTry);
5431
5432 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5433 return RewriteObjCThrowStmt(StmtThrow);
5434
5435 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5436 return RewriteObjCProtocolExpr(ProtocolExp);
5437
5438 if (ObjCForCollectionStmt *StmtForCollection =
5439 dyn_cast<ObjCForCollectionStmt>(S))
5440 return RewriteObjCForCollectionStmt(StmtForCollection,
5441 OrigStmtRange.getEnd());
5442 if (BreakStmt *StmtBreakStmt =
5443 dyn_cast<BreakStmt>(S))
5444 return RewriteBreakStmt(StmtBreakStmt);
5445 if (ContinueStmt *StmtContinueStmt =
5446 dyn_cast<ContinueStmt>(S))
5447 return RewriteContinueStmt(StmtContinueStmt);
5448
5449 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5450 // and cast exprs.
5451 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5452 // FIXME: What we're doing here is modifying the type-specifier that
5453 // precedes the first Decl. In the future the DeclGroup should have
5454 // a separate type-specifier that we can rewrite.
5455 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5456 // the context of an ObjCForCollectionStmt. For example:
5457 // NSArray *someArray;
5458 // for (id <FooProtocol> index in someArray) ;
5459 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5460 // and it depends on the original text locations/positions.
5461 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5462 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5463
5464 // Blocks rewrite rules.
5465 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5466 DI != DE; ++DI) {
5467 Decl *SD = *DI;
5468 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5469 if (isTopLevelBlockPointerType(ND->getType()))
5470 RewriteBlockPointerDecl(ND);
5471 else if (ND->getType()->isFunctionPointerType())
5472 CheckFunctionPointerDecl(ND->getType(), ND);
5473 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5474 if (VD->hasAttr<BlocksAttr>()) {
5475 static unsigned uniqueByrefDeclCount = 0;
5476 assert(!BlockByRefDeclNo.count(ND) &&
5477 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5478 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005479 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005480 }
5481 else
5482 RewriteTypeOfDecl(VD);
5483 }
5484 }
5485 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5486 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5487 RewriteBlockPointerDecl(TD);
5488 else if (TD->getUnderlyingType()->isFunctionPointerType())
5489 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5490 }
5491 }
5492 }
5493
5494 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5495 RewriteObjCQualifiedInterfaceTypes(CE);
5496
5497 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5498 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5499 assert(!Stmts.empty() && "Statement stack is empty");
5500 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5501 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5502 && "Statement stack mismatch");
5503 Stmts.pop_back();
5504 }
5505 // Handle blocks rewriting.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005506 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5507 ValueDecl *VD = DRE->getDecl();
5508 if (VD->hasAttr<BlocksAttr>())
5509 return RewriteBlockDeclRefExpr(DRE);
5510 if (HasLocalVariableExternalStorage(VD))
5511 return RewriteLocalVariableExternalStorage(DRE);
5512 }
5513
5514 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5515 if (CE->getCallee()->getType()->isBlockPointerType()) {
5516 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5517 ReplaceStmt(S, BlockCall);
5518 return BlockCall;
5519 }
5520 }
5521 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5522 RewriteCastExpr(CE);
5523 }
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00005524 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5525 RewriteImplicitCastObjCExpr(ICE);
5526 }
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00005527#if 0
Fariborz Jahanian653b7cf2012-04-13 18:00:54 +00005528
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005529 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5530 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5531 ICE->getSubExpr(),
5532 SourceLocation());
5533 // Get the new text.
5534 std::string SStr;
5535 llvm::raw_string_ostream Buf(SStr);
5536 Replacement->printPretty(Buf, *Context);
5537 const std::string &Str = Buf.str();
5538
5539 printf("CAST = %s\n", &Str[0]);
5540 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5541 delete S;
5542 return Replacement;
5543 }
5544#endif
5545 // Return this stmt unmodified.
5546 return S;
5547}
5548
5549void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5550 for (RecordDecl::field_iterator i = RD->field_begin(),
5551 e = RD->field_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00005552 FieldDecl *FD = *i;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005553 if (isTopLevelBlockPointerType(FD->getType()))
5554 RewriteBlockPointerDecl(FD);
5555 if (FD->getType()->isObjCQualifiedIdType() ||
5556 FD->getType()->isObjCQualifiedInterfaceType())
5557 RewriteObjCQualifiedInterfaceTypes(FD);
5558 }
5559}
5560
5561/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5562/// main file of the input.
5563void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5564 switch (D->getKind()) {
5565 case Decl::Function: {
5566 FunctionDecl *FD = cast<FunctionDecl>(D);
5567 if (FD->isOverloadedOperator())
5568 return;
5569
5570 // Since function prototypes don't have ParmDecl's, we check the function
5571 // prototype. This enables us to rewrite function declarations and
5572 // definitions using the same code.
5573 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5574
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00005575 if (!FD->isThisDeclarationADefinition())
5576 break;
5577
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005578 // FIXME: If this should support Obj-C++, support CXXTryStmt
5579 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5580 CurFunctionDef = FD;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005581 CurrentBody = Body;
5582 Body =
5583 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5584 FD->setBody(Body);
5585 CurrentBody = 0;
5586 if (PropParentMap) {
5587 delete PropParentMap;
5588 PropParentMap = 0;
5589 }
5590 // This synthesizes and inserts the block "impl" struct, invoke function,
5591 // and any copy/dispose helper functions.
5592 InsertBlockLiteralsWithinFunction(FD);
5593 CurFunctionDef = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005594 }
5595 break;
5596 }
5597 case Decl::ObjCMethod: {
5598 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5599 if (CompoundStmt *Body = MD->getCompoundBody()) {
5600 CurMethodDef = MD;
5601 CurrentBody = Body;
5602 Body =
5603 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5604 MD->setBody(Body);
5605 CurrentBody = 0;
5606 if (PropParentMap) {
5607 delete PropParentMap;
5608 PropParentMap = 0;
5609 }
5610 InsertBlockLiteralsWithinMethod(MD);
5611 CurMethodDef = 0;
5612 }
5613 break;
5614 }
5615 case Decl::ObjCImplementation: {
5616 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5617 ClassImplementation.push_back(CI);
5618 break;
5619 }
5620 case Decl::ObjCCategoryImpl: {
5621 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5622 CategoryImplementation.push_back(CI);
5623 break;
5624 }
5625 case Decl::Var: {
5626 VarDecl *VD = cast<VarDecl>(D);
5627 RewriteObjCQualifiedInterfaceTypes(VD);
5628 if (isTopLevelBlockPointerType(VD->getType()))
5629 RewriteBlockPointerDecl(VD);
5630 else if (VD->getType()->isFunctionPointerType()) {
5631 CheckFunctionPointerDecl(VD->getType(), VD);
5632 if (VD->getInit()) {
5633 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5634 RewriteCastExpr(CE);
5635 }
5636 }
5637 } else if (VD->getType()->isRecordType()) {
5638 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5639 if (RD->isCompleteDefinition())
5640 RewriteRecordBody(RD);
5641 }
5642 if (VD->getInit()) {
5643 GlobalVarDecl = VD;
5644 CurrentBody = VD->getInit();
5645 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5646 CurrentBody = 0;
5647 if (PropParentMap) {
5648 delete PropParentMap;
5649 PropParentMap = 0;
5650 }
5651 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5652 GlobalVarDecl = 0;
5653
5654 // This is needed for blocks.
5655 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5656 RewriteCastExpr(CE);
5657 }
5658 }
5659 break;
5660 }
5661 case Decl::TypeAlias:
5662 case Decl::Typedef: {
5663 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5664 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5665 RewriteBlockPointerDecl(TD);
5666 else if (TD->getUnderlyingType()->isFunctionPointerType())
5667 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5668 }
5669 break;
5670 }
5671 case Decl::CXXRecord:
5672 case Decl::Record: {
5673 RecordDecl *RD = cast<RecordDecl>(D);
5674 if (RD->isCompleteDefinition())
5675 RewriteRecordBody(RD);
5676 break;
5677 }
5678 default:
5679 break;
5680 }
5681 // Nothing yet.
5682}
5683
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005684/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5685/// protocol reference symbols in the for of:
5686/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5687static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5688 ObjCProtocolDecl *PDecl,
5689 std::string &Result) {
5690 // Also output .objc_protorefs$B section and its meta-data.
5691 if (Context->getLangOpts().MicrosoftExt)
Fariborz Jahanianbd78cfa2012-04-27 21:39:49 +00005692 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005693 Result += "struct _protocol_t *";
5694 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5695 Result += PDecl->getNameAsString();
5696 Result += " = &";
5697 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5698 Result += ";\n";
5699}
5700
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005701void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5702 if (Diags.hasErrorOccurred())
5703 return;
5704
5705 RewriteInclude();
5706
5707 // Here's a great place to add any extra declarations that may be needed.
5708 // Write out meta data for each @protocol(<expr>).
5709 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005710 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005711 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005712 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
5713 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005714
5715 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +00005716
5717 if (ClassImplementation.size() || CategoryImplementation.size())
5718 RewriteImplementations();
5719
Fariborz Jahanian57317782012-02-21 23:58:41 +00005720 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5721 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5722 // Write struct declaration for the class matching its ivar declarations.
5723 // Note that for modern abi, this is postponed until the end of TU
5724 // because class extensions and the implementation might declare their own
5725 // private ivars.
5726 RewriteInterfaceDecl(CDecl);
5727 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005728
5729 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5730 // we are done.
5731 if (const RewriteBuffer *RewriteBuf =
5732 Rewrite.getRewriteBufferFor(MainFileID)) {
5733 //printf("Changed:\n");
5734 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5735 } else {
5736 llvm::errs() << "No changes\n";
5737 }
5738
5739 if (ClassImplementation.size() || CategoryImplementation.size() ||
5740 ProtocolExprDecls.size()) {
5741 // Rewrite Objective-c meta data*
5742 std::string ResultStr;
5743 RewriteMetaDataIntoBuffer(ResultStr);
5744 // Emit metadata.
5745 *OutFile << ResultStr;
5746 }
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005747 // Emit ImageInfo;
5748 {
5749 std::string ResultStr;
5750 WriteImageInfo(ResultStr);
5751 *OutFile << ResultStr;
5752 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005753 OutFile->flush();
5754}
5755
5756void RewriteModernObjC::Initialize(ASTContext &context) {
5757 InitializeCommon(context);
5758
Fariborz Jahanian6991bc52012-03-10 17:45:38 +00005759 Preamble += "#ifndef __OBJC2__\n";
5760 Preamble += "#define __OBJC2__\n";
5761 Preamble += "#endif\n";
5762
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005763 // declaring objc_selector outside the parameter list removes a silly
5764 // scope related warning...
5765 if (IsHeader)
5766 Preamble = "#pragma once\n";
5767 Preamble += "struct objc_selector; struct objc_class;\n";
Fariborz Jahaniane2d87bc2012-04-12 23:52:52 +00005768 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
5769 Preamble += "\n\tstruct objc_object *superClass; ";
5770 // Add a constructor for creating temporary objects.
5771 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
5772 Preamble += ": object(o), superClass(s) {} ";
5773 Preamble += "\n};\n";
5774
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005775 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005776 // Define all sections using syntax that makes sense.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005777 // These are currently generated.
5778 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005779 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005780 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005781 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5782 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005783 // These are generated but not necessary for functionality.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005784 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005785 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5786 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005787 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005788
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005789 // These need be generated for performance. Currently they are not,
5790 // using API calls instead.
5791 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5792 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5793 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5794
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005795 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005796 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5797 Preamble += "typedef struct objc_object Protocol;\n";
5798 Preamble += "#define _REWRITER_typedef_Protocol\n";
5799 Preamble += "#endif\n";
5800 if (LangOpts.MicrosoftExt) {
5801 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5802 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005803 }
5804 else
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005805 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005806
5807 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
5808 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
5809 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
5810 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
5811 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
5812
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00005813 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005814 Preamble += "(const char *);\n";
5815 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5816 Preamble += "(struct objc_class *);\n";
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00005817 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005818 Preamble += "(const char *);\n";
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005819 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005820 // @synchronized hooks.
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005821 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter( struct objc_object *);\n";
5822 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005823 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5824 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5825 Preamble += "struct __objcFastEnumerationState {\n\t";
5826 Preamble += "unsigned long state;\n\t";
5827 Preamble += "void **itemsPtr;\n\t";
5828 Preamble += "unsigned long *mutationsPtr;\n\t";
5829 Preamble += "unsigned long extra[5];\n};\n";
5830 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5831 Preamble += "#define __FASTENUMERATIONSTATE\n";
5832 Preamble += "#endif\n";
5833 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5834 Preamble += "struct __NSConstantStringImpl {\n";
5835 Preamble += " int *isa;\n";
5836 Preamble += " int flags;\n";
5837 Preamble += " char *str;\n";
5838 Preamble += " long length;\n";
5839 Preamble += "};\n";
5840 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5841 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5842 Preamble += "#else\n";
5843 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5844 Preamble += "#endif\n";
5845 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5846 Preamble += "#endif\n";
5847 // Blocks preamble.
5848 Preamble += "#ifndef BLOCK_IMPL\n";
5849 Preamble += "#define BLOCK_IMPL\n";
5850 Preamble += "struct __block_impl {\n";
5851 Preamble += " void *isa;\n";
5852 Preamble += " int Flags;\n";
5853 Preamble += " int Reserved;\n";
5854 Preamble += " void *FuncPtr;\n";
5855 Preamble += "};\n";
5856 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5857 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5858 Preamble += "extern \"C\" __declspec(dllexport) "
5859 "void _Block_object_assign(void *, const void *, const int);\n";
5860 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5861 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5862 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5863 Preamble += "#else\n";
5864 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5865 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5866 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5867 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5868 Preamble += "#endif\n";
5869 Preamble += "#endif\n";
5870 if (LangOpts.MicrosoftExt) {
5871 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5872 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5873 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5874 Preamble += "#define __attribute__(X)\n";
5875 Preamble += "#endif\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00005876 Preamble += "#ifndef __weak\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005877 Preamble += "#define __weak\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00005878 Preamble += "#endif\n";
5879 Preamble += "#ifndef __block\n";
5880 Preamble += "#define __block\n";
5881 Preamble += "#endif\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005882 }
5883 else {
5884 Preamble += "#define __block\n";
5885 Preamble += "#define __weak\n";
5886 }
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005887
5888 // Declarations required for modern objective-c array and dictionary literals.
5889 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005890 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005891 Preamble += " void * *arr;\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005892 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005893 Preamble += "\tva_list marker;\n";
5894 Preamble += "\tva_start(marker, count);\n";
5895 Preamble += "\tarr = new void *[count];\n";
5896 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
5897 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
5898 Preamble += "\tva_end( marker );\n";
5899 Preamble += " };\n";
Fariborz Jahanian13a9c022012-05-02 23:53:46 +00005900 Preamble += " ~__NSContainer_literal() {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005901 Preamble += "\tdelete[] arr;\n";
5902 Preamble += " }\n";
5903 Preamble += "};\n";
5904
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00005905 // Declaration required for implementation of @autoreleasepool statement.
5906 Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
5907 Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
5908 Preamble += "struct __AtAutoreleasePool {\n";
5909 Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
5910 Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
5911 Preamble += " void * atautoreleasepoolobj;\n";
5912 Preamble += "};\n";
5913
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005914 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5915 // as this avoids warning in any 64bit/32bit compilation model.
5916 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5917}
5918
5919/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5920/// ivar offset.
5921void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5922 std::string &Result) {
5923 if (ivar->isBitField()) {
5924 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5925 // place all bitfields at offset 0.
5926 Result += "0";
5927 } else {
5928 Result += "__OFFSETOFIVAR__(struct ";
5929 Result += ivar->getContainingInterface()->getNameAsString();
5930 if (LangOpts.MicrosoftExt)
5931 Result += "_IMPL";
5932 Result += ", ";
5933 Result += ivar->getNameAsString();
5934 Result += ")";
5935 }
5936}
5937
5938/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
5939/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005940/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005941/// char *attributes;
5942/// }
5943
5944/// struct _prop_list_t {
5945/// uint32_t entsize; // sizeof(struct _prop_t)
5946/// uint32_t count_of_properties;
5947/// struct _prop_t prop_list[count_of_properties];
5948/// }
5949
5950/// struct _protocol_t;
5951
5952/// struct _protocol_list_t {
5953/// long protocol_count; // Note, this is 32/64 bit
5954/// struct _protocol_t * protocol_list[protocol_count];
5955/// }
5956
5957/// struct _objc_method {
5958/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005959/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005960/// char *_imp;
5961/// }
5962
5963/// struct _method_list_t {
5964/// uint32_t entsize; // sizeof(struct _objc_method)
5965/// uint32_t method_count;
5966/// struct _objc_method method_list[method_count];
5967/// }
5968
5969/// struct _protocol_t {
5970/// id isa; // NULL
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005971/// const char *protocol_name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005972/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005973/// const struct method_list_t *instance_methods;
5974/// const struct method_list_t *class_methods;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005975/// const struct method_list_t *optionalInstanceMethods;
5976/// const struct method_list_t *optionalClassMethods;
5977/// const struct _prop_list_t * properties;
5978/// const uint32_t size; // sizeof(struct _protocol_t)
5979/// const uint32_t flags; // = 0
5980/// const char ** extendedMethodTypes;
5981/// }
5982
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005983/// struct _ivar_t {
5984/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00005985/// const char *name;
5986/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005987/// uint32_t alignment;
5988/// uint32_t size;
5989/// }
5990
5991/// struct _ivar_list_t {
5992/// uint32 entsize; // sizeof(struct _ivar_t)
5993/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00005994/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005995/// }
5996
5997/// struct _class_ro_t {
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005998/// uint32_t flags;
5999/// uint32_t instanceStart;
6000/// uint32_t instanceSize;
6001/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006002/// const uint8_t *ivarLayout;
6003/// const char *name;
6004/// const struct _method_list_t *baseMethods;
6005/// const struct _protocol_list_t *baseProtocols;
6006/// const struct _ivar_list_t *ivars;
6007/// const uint8_t *weakIvarLayout;
6008/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006009/// }
6010
6011/// struct _class_t {
6012/// struct _class_t *isa;
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00006013/// struct _class_t *superclass;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006014/// void *cache;
6015/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006016/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006017/// }
6018
6019/// struct _category_t {
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006020/// const char *name;
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006021/// struct _class_t *cls;
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006022/// const struct _method_list_t *instance_methods;
6023/// const struct _method_list_t *class_methods;
6024/// const struct _protocol_list_t *protocols;
6025/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006026/// }
6027
6028/// MessageRefTy - LLVM for:
6029/// struct _message_ref_t {
6030/// IMP messenger;
6031/// SEL name;
6032/// };
6033
6034/// SuperMessageRefTy - LLVM for:
6035/// struct _super_message_ref_t {
6036/// SUPER_IMP messenger;
6037/// SEL name;
6038/// };
6039
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006040static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006041 static bool meta_data_declared = false;
6042 if (meta_data_declared)
6043 return;
6044
6045 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006046 Result += "\tconst char *name;\n";
6047 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006048 Result += "};\n";
6049
6050 Result += "\nstruct _protocol_t;\n";
6051
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006052 Result += "\nstruct _objc_method {\n";
6053 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006054 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006055 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006056 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006057
6058 Result += "\nstruct _protocol_t {\n";
6059 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006060 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006061 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006062 Result += "\tconst struct method_list_t *instance_methods;\n";
6063 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006064 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6065 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6066 Result += "\tconst struct _prop_list_t * properties;\n";
6067 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
6068 Result += "\tconst unsigned int flags; // = 0\n";
6069 Result += "\tconst char ** extendedMethodTypes;\n";
6070 Result += "};\n";
6071
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006072 Result += "\nstruct _ivar_t {\n";
6073 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00006074 Result += "\tconst char *name;\n";
6075 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006076 Result += "\tunsigned int alignment;\n";
6077 Result += "\tunsigned int size;\n";
6078 Result += "};\n";
6079
6080 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006081 Result += "\tunsigned int flags;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006082 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006083 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006084 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6085 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006086 Result += "\tunsigned int reserved;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006087 Result += "\tconst unsigned char *ivarLayout;\n";
6088 Result += "\tconst char *name;\n";
6089 Result += "\tconst struct _method_list_t *baseMethods;\n";
6090 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6091 Result += "\tconst struct _ivar_list_t *ivars;\n";
6092 Result += "\tconst unsigned char *weakIvarLayout;\n";
6093 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006094 Result += "};\n";
6095
6096 Result += "\nstruct _class_t {\n";
6097 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00006098 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006099 Result += "\tvoid *cache;\n";
6100 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006101 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006102 Result += "};\n";
6103
6104 Result += "\nstruct _category_t {\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006105 Result += "\tconst char *name;\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006106 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006107 Result += "\tconst struct _method_list_t *instance_methods;\n";
6108 Result += "\tconst struct _method_list_t *class_methods;\n";
6109 Result += "\tconst struct _protocol_list_t *protocols;\n";
6110 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006111 Result += "};\n";
6112
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006113 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006114 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006115 meta_data_declared = true;
6116}
6117
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006118static void Write_protocol_list_t_TypeDecl(std::string &Result,
6119 long super_protocol_count) {
6120 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6121 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6122 Result += "\tstruct _protocol_t *super_protocols[";
6123 Result += utostr(super_protocol_count); Result += "];\n";
6124 Result += "}";
6125}
6126
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006127static void Write_method_list_t_TypeDecl(std::string &Result,
6128 unsigned int method_count) {
6129 Result += "struct /*_method_list_t*/"; Result += " {\n";
6130 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6131 Result += "\tunsigned int method_count;\n";
6132 Result += "\tstruct _objc_method method_list[";
6133 Result += utostr(method_count); Result += "];\n";
6134 Result += "}";
6135}
6136
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006137static void Write__prop_list_t_TypeDecl(std::string &Result,
6138 unsigned int property_count) {
6139 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6140 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6141 Result += "\tunsigned int count_of_properties;\n";
6142 Result += "\tstruct _prop_t prop_list[";
6143 Result += utostr(property_count); Result += "];\n";
6144 Result += "}";
6145}
6146
Fariborz Jahanianae932952012-02-10 20:47:10 +00006147static void Write__ivar_list_t_TypeDecl(std::string &Result,
6148 unsigned int ivar_count) {
6149 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6150 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6151 Result += "\tunsigned int count;\n";
6152 Result += "\tstruct _ivar_t ivar_list[";
6153 Result += utostr(ivar_count); Result += "];\n";
6154 Result += "}";
6155}
6156
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006157static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6158 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6159 StringRef VarName,
6160 StringRef ProtocolName) {
6161 if (SuperProtocols.size() > 0) {
6162 Result += "\nstatic ";
6163 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6164 Result += " "; Result += VarName;
6165 Result += ProtocolName;
6166 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6167 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6168 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6169 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6170 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6171 Result += SuperPD->getNameAsString();
6172 if (i == e-1)
6173 Result += "\n};\n";
6174 else
6175 Result += ",\n";
6176 }
6177 }
6178}
6179
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006180static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6181 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006182 ArrayRef<ObjCMethodDecl *> Methods,
6183 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006184 StringRef TopLevelDeclName,
6185 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006186 if (Methods.size() > 0) {
6187 Result += "\nstatic ";
6188 Write_method_list_t_TypeDecl(Result, Methods.size());
6189 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006190 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006191 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6192 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6193 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6194 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6195 ObjCMethodDecl *MD = Methods[i];
6196 if (i == 0)
6197 Result += "\t{{(struct objc_selector *)\"";
6198 else
6199 Result += "\t{(struct objc_selector *)\"";
6200 Result += (MD)->getSelector().getAsString(); Result += "\"";
6201 Result += ", ";
6202 std::string MethodTypeString;
6203 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6204 Result += "\""; Result += MethodTypeString; Result += "\"";
6205 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006206 if (!MethodImpl)
6207 Result += "0";
6208 else {
6209 Result += "(void *)";
6210 Result += RewriteObj.MethodInternalNames[MD];
6211 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006212 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006213 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006214 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006215 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006216 }
6217 Result += "};\n";
6218 }
6219}
6220
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006221static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006222 ASTContext *Context, std::string &Result,
6223 ArrayRef<ObjCPropertyDecl *> Properties,
6224 const Decl *Container,
6225 StringRef VarName,
6226 StringRef ProtocolName) {
6227 if (Properties.size() > 0) {
6228 Result += "\nstatic ";
6229 Write__prop_list_t_TypeDecl(Result, Properties.size());
6230 Result += " "; Result += VarName;
6231 Result += ProtocolName;
6232 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6233 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6234 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6235 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6236 ObjCPropertyDecl *PropDecl = Properties[i];
6237 if (i == 0)
6238 Result += "\t{{\"";
6239 else
6240 Result += "\t{\"";
6241 Result += PropDecl->getName(); Result += "\",";
6242 std::string PropertyTypeString, QuotePropertyTypeString;
6243 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6244 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6245 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6246 if (i == e-1)
6247 Result += "}}\n";
6248 else
6249 Result += "},\n";
6250 }
6251 Result += "};\n";
6252 }
6253}
6254
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006255// Metadata flags
6256enum MetaDataDlags {
6257 CLS = 0x0,
6258 CLS_META = 0x1,
6259 CLS_ROOT = 0x2,
6260 OBJC2_CLS_HIDDEN = 0x10,
6261 CLS_EXCEPTION = 0x20,
6262
6263 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6264 CLS_HAS_IVAR_RELEASER = 0x40,
6265 /// class was compiled with -fobjc-arr
6266 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6267};
6268
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006269static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6270 unsigned int flags,
6271 const std::string &InstanceStart,
6272 const std::string &InstanceSize,
6273 ArrayRef<ObjCMethodDecl *>baseMethods,
6274 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6275 ArrayRef<ObjCIvarDecl *>ivars,
6276 ArrayRef<ObjCPropertyDecl *>Properties,
6277 StringRef VarName,
6278 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006279 Result += "\nstatic struct _class_ro_t ";
6280 Result += VarName; Result += ClassName;
6281 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6282 Result += "\t";
6283 Result += llvm::utostr(flags); Result += ", ";
6284 Result += InstanceStart; Result += ", ";
6285 Result += InstanceSize; Result += ", \n";
6286 Result += "\t";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006287 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6288 if (Triple.getArch() == llvm::Triple::x86_64)
6289 // uint32_t const reserved; // only when building for 64bit targets
6290 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006291 // const uint8_t * const ivarLayout;
6292 Result += "0, \n\t";
6293 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006294 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006295 if (baseMethods.size() > 0) {
6296 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006297 if (metaclass)
6298 Result += "_OBJC_$_CLASS_METHODS_";
6299 else
6300 Result += "_OBJC_$_INSTANCE_METHODS_";
6301 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006302 Result += ",\n\t";
6303 }
6304 else
6305 Result += "0, \n\t";
6306
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006307 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006308 Result += "(const struct _objc_protocol_list *)&";
6309 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6310 Result += ",\n\t";
6311 }
6312 else
6313 Result += "0, \n\t";
6314
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006315 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006316 Result += "(const struct _ivar_list_t *)&";
6317 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6318 Result += ",\n\t";
6319 }
6320 else
6321 Result += "0, \n\t";
6322
6323 // weakIvarLayout
6324 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006325 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006326 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006327 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006328 Result += ",\n";
6329 }
6330 else
6331 Result += "0, \n";
6332
6333 Result += "};\n";
6334}
6335
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006336static void Write_class_t(ASTContext *Context, std::string &Result,
6337 StringRef VarName,
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006338 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6339 bool rootClass = (!CDecl->getSuperClass());
6340 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006341
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006342 if (!rootClass) {
6343 // Find the Root class
6344 RootClass = CDecl->getSuperClass();
6345 while (RootClass->getSuperClass()) {
6346 RootClass = RootClass->getSuperClass();
6347 }
6348 }
6349
6350 if (metaclass && rootClass) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006351 // Need to handle a case of use of forward declaration.
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006352 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006353 Result += "extern \"C\" ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006354 if (CDecl->getImplementation())
6355 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006356 else
6357 Result += "__declspec(dllimport) ";
6358
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006359 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006360 Result += CDecl->getNameAsString();
6361 Result += ";\n";
6362 }
6363 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006364 if (!rootClass) {
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006365 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006366 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006367 Result += "extern \"C\" ";
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006368 if (SuperClass->getImplementation())
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006369 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006370 else
6371 Result += "__declspec(dllimport) ";
6372
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006373 Result += "struct _class_t ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006374 Result += VarName;
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006375 Result += SuperClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006376 Result += ";\n";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006377
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006378 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006379 Result += "extern \"C\" ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006380 if (RootClass->getImplementation())
6381 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006382 else
6383 Result += "__declspec(dllimport) ";
6384
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006385 Result += "struct _class_t ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006386 Result += VarName;
6387 Result += RootClass->getNameAsString();
6388 Result += ";\n";
6389 }
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006390 }
6391
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006392 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6393 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006394 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6395 Result += "\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006396 if (metaclass) {
6397 if (!rootClass) {
6398 Result += "0, // &"; Result += VarName;
6399 Result += RootClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006400 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006401 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006402 Result += CDecl->getSuperClass()->getNameAsString();
6403 Result += ",\n\t";
6404 }
6405 else {
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006406 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006407 Result += CDecl->getNameAsString();
6408 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006409 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006410 Result += ",\n\t";
6411 }
6412 }
6413 else {
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006414 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006415 Result += CDecl->getNameAsString();
6416 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006417 if (!rootClass) {
6418 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006419 Result += CDecl->getSuperClass()->getNameAsString();
6420 Result += ",\n\t";
6421 }
6422 else
6423 Result += "0,\n\t";
6424 }
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006425 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6426 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6427 if (metaclass)
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006428 Result += "&_OBJC_METACLASS_RO_$_";
6429 else
6430 Result += "&_OBJC_CLASS_RO_$_";
6431 Result += CDecl->getNameAsString();
6432 Result += ",\n};\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006433
6434 // Add static function to initialize some of the meta-data fields.
6435 // avoid doing it twice.
6436 if (metaclass)
6437 return;
6438
6439 const ObjCInterfaceDecl *SuperClass =
6440 rootClass ? CDecl : CDecl->getSuperClass();
6441
6442 Result += "static void OBJC_CLASS_SETUP_$_";
6443 Result += CDecl->getNameAsString();
6444 Result += "(void ) {\n";
6445 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6446 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006447 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006448
6449 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006450 Result += ".superclass = ";
6451 if (rootClass)
6452 Result += "&OBJC_CLASS_$_";
6453 else
6454 Result += "&OBJC_METACLASS_$_";
6455
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006456 Result += SuperClass->getNameAsString(); Result += ";\n";
6457
6458 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6459 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6460
6461 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6462 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6463 Result += CDecl->getNameAsString(); Result += ";\n";
6464
6465 if (!rootClass) {
6466 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6467 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6468 Result += SuperClass->getNameAsString(); Result += ";\n";
6469 }
6470
6471 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6472 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6473 Result += "}\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006474}
6475
Fariborz Jahanian61186122012-02-17 18:40:41 +00006476static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6477 std::string &Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006478 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006479 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006480 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6481 ArrayRef<ObjCMethodDecl *> ClassMethods,
6482 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6483 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006484 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi20f89392012-03-21 03:21:46 +00006485 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006486 // must declare an extern class object in case this class is not implemented
6487 // in this TU.
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006488 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006489 Result += "extern \"C\" ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006490 if (ClassDecl->getImplementation())
6491 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006492 else
6493 Result += "__declspec(dllimport) ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006494
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006495 Result += "struct _class_t ";
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006496 Result += "OBJC_CLASS_$_"; Result += ClassName;
6497 Result += ";\n";
6498
Fariborz Jahanian61186122012-02-17 18:40:41 +00006499 Result += "\nstatic struct _category_t ";
6500 Result += "_OBJC_$_CATEGORY_";
6501 Result += ClassName; Result += "_$_"; Result += CatName;
6502 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6503 Result += "{\n";
6504 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006505 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanian61186122012-02-17 18:40:41 +00006506 Result += ",\n";
6507 if (InstanceMethods.size() > 0) {
6508 Result += "\t(const struct _method_list_t *)&";
6509 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6510 Result += ClassName; Result += "_$_"; Result += CatName;
6511 Result += ",\n";
6512 }
6513 else
6514 Result += "\t0,\n";
6515
6516 if (ClassMethods.size() > 0) {
6517 Result += "\t(const struct _method_list_t *)&";
6518 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6519 Result += ClassName; Result += "_$_"; Result += CatName;
6520 Result += ",\n";
6521 }
6522 else
6523 Result += "\t0,\n";
6524
6525 if (RefedProtocols.size() > 0) {
6526 Result += "\t(const struct _protocol_list_t *)&";
6527 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6528 Result += ClassName; Result += "_$_"; Result += CatName;
6529 Result += ",\n";
6530 }
6531 else
6532 Result += "\t0,\n";
6533
6534 if (ClassProperties.size() > 0) {
6535 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6536 Result += ClassName; Result += "_$_"; Result += CatName;
6537 Result += ",\n";
6538 }
6539 else
6540 Result += "\t0,\n";
6541
6542 Result += "};\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006543
6544 // Add static function to initialize the class pointer in the category structure.
6545 Result += "static void OBJC_CATEGORY_SETUP_$_";
6546 Result += ClassDecl->getNameAsString();
6547 Result += "_$_";
6548 Result += CatName;
6549 Result += "(void ) {\n";
6550 Result += "\t_OBJC_$_CATEGORY_";
6551 Result += ClassDecl->getNameAsString();
6552 Result += "_$_";
6553 Result += CatName;
6554 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6555 Result += ";\n}\n";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006556}
6557
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006558static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6559 ASTContext *Context, std::string &Result,
6560 ArrayRef<ObjCMethodDecl *> Methods,
6561 StringRef VarName,
6562 StringRef ProtocolName) {
6563 if (Methods.size() == 0)
6564 return;
6565
6566 Result += "\nstatic const char *";
6567 Result += VarName; Result += ProtocolName;
6568 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6569 Result += "{\n";
6570 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6571 ObjCMethodDecl *MD = Methods[i];
6572 std::string MethodTypeString, QuoteMethodTypeString;
6573 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6574 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6575 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6576 if (i == e-1)
6577 Result += "\n};\n";
6578 else {
6579 Result += ",\n";
6580 }
6581 }
6582}
6583
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006584static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6585 ASTContext *Context,
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006586 std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006587 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006588 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006589 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6590 // this is what happens:
6591 /**
6592 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6593 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6594 Class->getVisibility() == HiddenVisibility)
6595 Visibility shoud be: HiddenVisibility;
6596 else
6597 Visibility shoud be: DefaultVisibility;
6598 */
6599
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006600 Result += "\n";
6601 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6602 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006603 if (Context->getLangOpts().MicrosoftExt)
6604 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6605
6606 if (!Context->getLangOpts().MicrosoftExt ||
6607 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanian117591f2012-03-10 01:34:42 +00006608 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006609 Result += "extern \"C\" unsigned long int ";
Fariborz Jahaniand1c84d32012-03-10 00:53:02 +00006610 else
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006611 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006612 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006613 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6614 Result += " = ";
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006615 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6616 Result += ";\n";
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006617 }
6618}
6619
Fariborz Jahanianae932952012-02-10 20:47:10 +00006620static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6621 ASTContext *Context, std::string &Result,
6622 ArrayRef<ObjCIvarDecl *> Ivars,
6623 StringRef VarName,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006624 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanianae932952012-02-10 20:47:10 +00006625 if (Ivars.size() > 0) {
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006626 Write_IvarOffsetVar(RewriteObj, Context, Result, Ivars, CDecl);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006627
Fariborz Jahanianae932952012-02-10 20:47:10 +00006628 Result += "\nstatic ";
6629 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6630 Result += " "; Result += VarName;
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006631 Result += CDecl->getNameAsString();
Fariborz Jahanianae932952012-02-10 20:47:10 +00006632 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6633 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6634 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6635 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6636 ObjCIvarDecl *IvarDecl = Ivars[i];
6637 if (i == 0)
6638 Result += "\t{{";
6639 else
6640 Result += "\t {";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006641 Result += "(unsigned long int *)&";
6642 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006643 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00006644
6645 Result += "\""; Result += IvarDecl->getName(); Result += "\", ";
6646 std::string IvarTypeString, QuoteIvarTypeString;
6647 Context->getObjCEncodingForType(IvarDecl->getType(), IvarTypeString,
6648 IvarDecl);
6649 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6650 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6651
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006652 // FIXME. this alignment represents the host alignment and need be changed to
6653 // represent the target alignment.
6654 unsigned Align = Context->getTypeAlign(IvarDecl->getType())/8;
6655 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006656 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00006657 CharUnits Size = Context->getTypeSizeInChars(IvarDecl->getType());
6658 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00006659 if (i == e-1)
6660 Result += "}}\n";
6661 else
6662 Result += "},\n";
6663 }
6664 Result += "};\n";
6665 }
6666}
6667
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006668/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006669void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
6670 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006671
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006672 // Do not synthesize the protocol more than once.
6673 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6674 return;
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006675 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006676
6677 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6678 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006679 // Must write out all protocol definitions in current qualifier list,
6680 // and in their nested qualifiers before writing out current definition.
6681 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6682 E = PDecl->protocol_end(); I != E; ++I)
6683 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006684
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006685 // Construct method lists.
6686 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6687 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
6688 for (ObjCProtocolDecl::instmeth_iterator
6689 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
6690 I != E; ++I) {
6691 ObjCMethodDecl *MD = *I;
6692 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6693 OptInstanceMethods.push_back(MD);
6694 } else {
6695 InstanceMethods.push_back(MD);
6696 }
6697 }
6698
6699 for (ObjCProtocolDecl::classmeth_iterator
6700 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
6701 I != E; ++I) {
6702 ObjCMethodDecl *MD = *I;
6703 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6704 OptClassMethods.push_back(MD);
6705 } else {
6706 ClassMethods.push_back(MD);
6707 }
6708 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006709 std::vector<ObjCMethodDecl *> AllMethods;
6710 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6711 AllMethods.push_back(InstanceMethods[i]);
6712 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6713 AllMethods.push_back(ClassMethods[i]);
6714 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6715 AllMethods.push_back(OptInstanceMethods[i]);
6716 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6717 AllMethods.push_back(OptClassMethods[i]);
6718
6719 Write__extendedMethodTypes_initializer(*this, Context, Result,
6720 AllMethods,
6721 "_OBJC_PROTOCOL_METHOD_TYPES_",
6722 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006723 // Protocol's super protocol list
6724 std::vector<ObjCProtocolDecl *> SuperProtocols;
6725 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6726 E = PDecl->protocol_end(); I != E; ++I)
6727 SuperProtocols.push_back(*I);
6728
6729 Write_protocol_list_initializer(Context, Result, SuperProtocols,
6730 "_OBJC_PROTOCOL_REFS_",
6731 PDecl->getNameAsString());
6732
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006733 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006734 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006735 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006736
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006737 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006738 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006739 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006740
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006741 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006742 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006743 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006744
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006745 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006746 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006747 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006748
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006749 // Protocol's property metadata.
6750 std::vector<ObjCPropertyDecl *> ProtocolProperties;
6751 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
6752 E = PDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00006753 ProtocolProperties.push_back(*I);
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006754
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006755 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006756 /* Container */0,
6757 "_OBJC_PROTOCOL_PROPERTIES_",
6758 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006759
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006760 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006761 Result += "\n";
6762 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00006763 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006764 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006765 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006766 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
6767 Result += "\t0,\n"; // id is; is null
6768 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006769 if (SuperProtocols.size() > 0) {
6770 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6771 Result += PDecl->getNameAsString(); Result += ",\n";
6772 }
6773 else
6774 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006775 if (InstanceMethods.size() > 0) {
6776 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
6777 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006778 }
6779 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006780 Result += "\t0,\n";
6781
6782 if (ClassMethods.size() > 0) {
6783 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
6784 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006785 }
6786 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006787 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006788
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006789 if (OptInstanceMethods.size() > 0) {
6790 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
6791 Result += PDecl->getNameAsString(); Result += ",\n";
6792 }
6793 else
6794 Result += "\t0,\n";
6795
6796 if (OptClassMethods.size() > 0) {
6797 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
6798 Result += PDecl->getNameAsString(); Result += ",\n";
6799 }
6800 else
6801 Result += "\t0,\n";
6802
6803 if (ProtocolProperties.size() > 0) {
6804 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
6805 Result += PDecl->getNameAsString(); Result += ",\n";
6806 }
6807 else
6808 Result += "\t0,\n";
6809
6810 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6811 Result += "\t0,\n";
6812
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006813 if (AllMethods.size() > 0) {
6814 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6815 Result += PDecl->getNameAsString();
6816 Result += "\n};\n";
6817 }
6818 else
6819 Result += "\t0\n};\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006820
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006821 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00006822 Result += "static ";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006823 Result += "struct _protocol_t *";
6824 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6825 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6826 Result += ";\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006827
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006828 // Mark this protocol as having been generated.
6829 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
6830 llvm_unreachable("protocol already synthesized");
6831
6832}
6833
6834void RewriteModernObjC::RewriteObjCProtocolListMetaData(
6835 const ObjCList<ObjCProtocolDecl> &Protocols,
6836 StringRef prefix, StringRef ClassName,
6837 std::string &Result) {
6838 if (Protocols.empty()) return;
6839
6840 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006841 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006842
6843 // Output the top lovel protocol meta-data for the class.
6844 /* struct _objc_protocol_list {
6845 struct _objc_protocol_list *next;
6846 int protocol_count;
6847 struct _objc_protocol *class_protocols[];
6848 }
6849 */
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006850 Result += "\n";
6851 if (LangOpts.MicrosoftExt)
6852 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
6853 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006854 Result += "\tstruct _objc_protocol_list *next;\n";
6855 Result += "\tint protocol_count;\n";
6856 Result += "\tstruct _objc_protocol *class_protocols[";
6857 Result += utostr(Protocols.size());
6858 Result += "];\n} _OBJC_";
6859 Result += prefix;
6860 Result += "_PROTOCOLS_";
6861 Result += ClassName;
6862 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
6863 "{\n\t0, ";
6864 Result += utostr(Protocols.size());
6865 Result += "\n";
6866
6867 Result += "\t,{&_OBJC_PROTOCOL_";
6868 Result += Protocols[0]->getNameAsString();
6869 Result += " \n";
6870
6871 for (unsigned i = 1; i != Protocols.size(); i++) {
6872 Result += "\t ,&_OBJC_PROTOCOL_";
6873 Result += Protocols[i]->getNameAsString();
6874 Result += "\n";
6875 }
6876 Result += "\t }\n};\n";
6877}
6878
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006879/// hasObjCExceptionAttribute - Return true if this class or any super
6880/// class has the __objc_exception__ attribute.
6881/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
6882static bool hasObjCExceptionAttribute(ASTContext &Context,
6883 const ObjCInterfaceDecl *OID) {
6884 if (OID->hasAttr<ObjCExceptionAttr>())
6885 return true;
6886 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
6887 return hasObjCExceptionAttribute(Context, Super);
6888 return false;
6889}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006890
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006891void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
6892 std::string &Result) {
6893 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6894
6895 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00006896 if (CDecl->isImplicitInterfaceDecl())
6897 assert(false &&
6898 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006899
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006900 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006901 SmallVector<ObjCIvarDecl *, 8> IVars;
6902
6903 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6904 IVD; IVD = IVD->getNextIvar()) {
6905 // Ignore unnamed bit-fields.
6906 if (!IVD->getDeclName())
6907 continue;
6908 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006909 }
6910
Fariborz Jahanianae932952012-02-10 20:47:10 +00006911 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006912 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006913 CDecl);
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006914
6915 // Build _objc_method_list for class's instance methods if needed
6916 SmallVector<ObjCMethodDecl *, 32>
6917 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6918
6919 // If any of our property implementations have associated getters or
6920 // setters, produce metadata for them as well.
6921 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6922 PropEnd = IDecl->propimpl_end();
6923 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00006924 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006925 continue;
David Blaikie262bc182012-04-30 02:36:29 +00006926 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006927 continue;
David Blaikie262bc182012-04-30 02:36:29 +00006928 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006929 if (!PD)
6930 continue;
6931 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00006932 if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006933 InstanceMethods.push_back(Getter);
6934 if (PD->isReadOnly())
6935 continue;
6936 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00006937 if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006938 InstanceMethods.push_back(Setter);
6939 }
6940
6941 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6942 "_OBJC_$_INSTANCE_METHODS_",
6943 IDecl->getNameAsString(), true);
6944
6945 SmallVector<ObjCMethodDecl *, 32>
6946 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6947
6948 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6949 "_OBJC_$_CLASS_METHODS_",
6950 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00006951
6952 // Protocols referenced in class declaration?
6953 // Protocol's super protocol list
6954 std::vector<ObjCProtocolDecl *> RefedProtocols;
6955 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
6956 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6957 E = Protocols.end();
6958 I != E; ++I) {
6959 RefedProtocols.push_back(*I);
6960 // Must write out all protocol definitions in current qualifier list,
6961 // and in their nested qualifiers before writing out current definition.
6962 RewriteObjCProtocolMetaData(*I, Result);
6963 }
6964
6965 Write_protocol_list_initializer(Context, Result,
6966 RefedProtocols,
6967 "_OBJC_CLASS_PROTOCOLS_$_",
6968 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006969
6970 // Protocol's property metadata.
6971 std::vector<ObjCPropertyDecl *> ClassProperties;
6972 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6973 E = CDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00006974 ClassProperties.push_back(*I);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006975
6976 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanian2df089d2012-03-22 17:39:35 +00006977 /* Container */IDecl,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006978 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006979 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006980
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006981
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006982 // Data for initializing _class_ro_t metaclass meta-data
6983 uint32_t flags = CLS_META;
6984 std::string InstanceSize;
6985 std::string InstanceStart;
6986
6987
6988 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
6989 if (classIsHidden)
6990 flags |= OBJC2_CLS_HIDDEN;
6991
6992 if (!CDecl->getSuperClass())
6993 // class is root
6994 flags |= CLS_ROOT;
6995 InstanceSize = "sizeof(struct _class_t)";
6996 InstanceStart = InstanceSize;
6997 Write__class_ro_t_initializer(Context, Result, flags,
6998 InstanceStart, InstanceSize,
6999 ClassMethods,
7000 0,
7001 0,
7002 0,
7003 "_OBJC_METACLASS_RO_$_",
7004 CDecl->getNameAsString());
7005
7006
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007007 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007008 flags = CLS;
7009 if (classIsHidden)
7010 flags |= OBJC2_CLS_HIDDEN;
7011
7012 if (hasObjCExceptionAttribute(*Context, CDecl))
7013 flags |= CLS_EXCEPTION;
7014
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007015 if (!CDecl->getSuperClass())
7016 // class is root
7017 flags |= CLS_ROOT;
7018
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007019 InstanceSize.clear();
7020 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007021 if (!ObjCSynthesizedStructs.count(CDecl)) {
7022 InstanceSize = "0";
7023 InstanceStart = "0";
7024 }
7025 else {
7026 InstanceSize = "sizeof(struct ";
7027 InstanceSize += CDecl->getNameAsString();
7028 InstanceSize += "_IMPL)";
7029
7030 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7031 if (IVD) {
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00007032 RewriteIvarOffsetComputation(IVD, InstanceStart);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007033 }
7034 else
7035 InstanceStart = InstanceSize;
7036 }
7037 Write__class_ro_t_initializer(Context, Result, flags,
7038 InstanceStart, InstanceSize,
7039 InstanceMethods,
7040 RefedProtocols,
7041 IVars,
7042 ClassProperties,
7043 "_OBJC_CLASS_RO_$_",
7044 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00007045
7046 Write_class_t(Context, Result,
7047 "OBJC_METACLASS_$_",
7048 CDecl, /*metaclass*/true);
7049
7050 Write_class_t(Context, Result,
7051 "OBJC_CLASS_$_",
7052 CDecl, /*metaclass*/false);
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007053
7054 if (ImplementationIsNonLazy(IDecl))
7055 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00007056
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007057}
7058
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007059void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7060 int ClsDefCount = ClassImplementation.size();
7061 if (!ClsDefCount)
7062 return;
7063 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7064 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7065 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7066 for (int i = 0; i < ClsDefCount; i++) {
7067 ObjCImplementationDecl *IDecl = ClassImplementation[i];
7068 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7069 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7070 Result += CDecl->getName(); Result += ",\n";
7071 }
7072 Result += "};\n";
7073}
7074
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007075void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7076 int ClsDefCount = ClassImplementation.size();
7077 int CatDefCount = CategoryImplementation.size();
7078
7079 // For each implemented class, write out all its meta data.
7080 for (int i = 0; i < ClsDefCount; i++)
7081 RewriteObjCClassMetaData(ClassImplementation[i], Result);
7082
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007083 RewriteClassSetupInitHook(Result);
7084
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007085 // For each implemented category, write out all its meta data.
7086 for (int i = 0; i < CatDefCount; i++)
7087 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7088
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007089 RewriteCategorySetupInitHook(Result);
7090
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007091 if (ClsDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007092 if (LangOpts.MicrosoftExt)
7093 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007094 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7095 Result += llvm::utostr(ClsDefCount); Result += "]";
7096 Result +=
7097 " __attribute__((used, section (\"__DATA, __objc_classlist,"
7098 "regular,no_dead_strip\")))= {\n";
7099 for (int i = 0; i < ClsDefCount; i++) {
7100 Result += "\t&OBJC_CLASS_$_";
7101 Result += ClassImplementation[i]->getNameAsString();
7102 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007103 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007104 Result += "};\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007105
7106 if (!DefinedNonLazyClasses.empty()) {
7107 if (LangOpts.MicrosoftExt)
7108 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7109 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7110 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7111 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7112 Result += ",\n";
7113 }
7114 Result += "};\n";
7115 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007116 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00007117
7118 if (CatDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007119 if (LangOpts.MicrosoftExt)
7120 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanian61186122012-02-17 18:40:41 +00007121 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7122 Result += llvm::utostr(CatDefCount); Result += "]";
7123 Result +=
7124 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7125 "regular,no_dead_strip\")))= {\n";
7126 for (int i = 0; i < CatDefCount; i++) {
7127 Result += "\t&_OBJC_$_CATEGORY_";
7128 Result +=
7129 CategoryImplementation[i]->getClassInterface()->getNameAsString();
7130 Result += "_$_";
7131 Result += CategoryImplementation[i]->getNameAsString();
7132 Result += ",\n";
7133 }
7134 Result += "};\n";
7135 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007136
7137 if (!DefinedNonLazyCategories.empty()) {
7138 if (LangOpts.MicrosoftExt)
7139 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7140 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7141 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7142 Result += "\t&_OBJC_$_CATEGORY_";
7143 Result +=
7144 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7145 Result += "_$_";
7146 Result += DefinedNonLazyCategories[i]->getNameAsString();
7147 Result += ",\n";
7148 }
7149 Result += "};\n";
7150 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007151}
7152
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007153void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7154 if (LangOpts.MicrosoftExt)
7155 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7156
7157 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7158 // version 0, ObjCABI is 2
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00007159 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007160}
7161
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007162/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7163/// implementation.
7164void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7165 std::string &Result) {
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00007166 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007167 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7168 // Find category declaration for this implementation.
Fariborz Jahanian61186122012-02-17 18:40:41 +00007169 ObjCCategoryDecl *CDecl=0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007170 for (CDecl = ClassDecl->getCategoryList(); CDecl;
7171 CDecl = CDecl->getNextClassCategory())
7172 if (CDecl->getIdentifier() == IDecl->getIdentifier())
7173 break;
7174
7175 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00007176 FullCategoryName += "_$_";
7177 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007178
7179 // Build _objc_method_list for class's instance methods if needed
7180 SmallVector<ObjCMethodDecl *, 32>
7181 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7182
7183 // If any of our property implementations have associated getters or
7184 // setters, produce metadata for them as well.
7185 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7186 PropEnd = IDecl->propimpl_end();
7187 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00007188 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007189 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007190 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007191 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007192 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007193 if (!PD)
7194 continue;
7195 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7196 InstanceMethods.push_back(Getter);
7197 if (PD->isReadOnly())
7198 continue;
7199 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7200 InstanceMethods.push_back(Setter);
7201 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007202
Fariborz Jahanian61186122012-02-17 18:40:41 +00007203 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7204 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7205 FullCategoryName, true);
7206
7207 SmallVector<ObjCMethodDecl *, 32>
7208 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7209
7210 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7211 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7212 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007213
7214 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00007215 // Protocol's super protocol list
7216 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00007217 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
7218 E = CDecl->protocol_end();
7219
7220 I != E; ++I) {
Fariborz Jahanian61186122012-02-17 18:40:41 +00007221 RefedProtocols.push_back(*I);
7222 // Must write out all protocol definitions in current qualifier list,
7223 // and in their nested qualifiers before writing out current definition.
7224 RewriteObjCProtocolMetaData(*I, Result);
7225 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007226
Fariborz Jahanian61186122012-02-17 18:40:41 +00007227 Write_protocol_list_initializer(Context, Result,
7228 RefedProtocols,
7229 "_OBJC_CATEGORY_PROTOCOLS_$_",
7230 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007231
Fariborz Jahanian61186122012-02-17 18:40:41 +00007232 // Protocol's property metadata.
7233 std::vector<ObjCPropertyDecl *> ClassProperties;
7234 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7235 E = CDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00007236 ClassProperties.push_back(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007237
Fariborz Jahanian61186122012-02-17 18:40:41 +00007238 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanianebfa2722012-05-03 23:19:33 +00007239 /* Container */IDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007240 "_OBJC_$_PROP_LIST_",
7241 FullCategoryName);
7242
7243 Write_category_t(*this, Context, Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007244 CDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007245 ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007246 InstanceMethods,
7247 ClassMethods,
7248 RefedProtocols,
7249 ClassProperties);
7250
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007251 // Determine if this category is also "non-lazy".
7252 if (ImplementationIsNonLazy(IDecl))
7253 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007254
7255}
7256
7257void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7258 int CatDefCount = CategoryImplementation.size();
7259 if (!CatDefCount)
7260 return;
7261 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7262 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7263 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7264 for (int i = 0; i < CatDefCount; i++) {
7265 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7266 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7267 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7268 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7269 Result += ClassDecl->getName();
7270 Result += "_$_";
7271 Result += CatDecl->getName();
7272 Result += ",\n";
7273 }
7274 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007275}
7276
7277// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7278/// class methods.
7279template<typename MethodIterator>
7280void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7281 MethodIterator MethodEnd,
7282 bool IsInstanceMethod,
7283 StringRef prefix,
7284 StringRef ClassName,
7285 std::string &Result) {
7286 if (MethodBegin == MethodEnd) return;
7287
7288 if (!objc_impl_method) {
7289 /* struct _objc_method {
7290 SEL _cmd;
7291 char *method_types;
7292 void *_imp;
7293 }
7294 */
7295 Result += "\nstruct _objc_method {\n";
7296 Result += "\tSEL _cmd;\n";
7297 Result += "\tchar *method_types;\n";
7298 Result += "\tvoid *_imp;\n";
7299 Result += "};\n";
7300
7301 objc_impl_method = true;
7302 }
7303
7304 // Build _objc_method_list for class's methods if needed
7305
7306 /* struct {
7307 struct _objc_method_list *next_method;
7308 int method_count;
7309 struct _objc_method method_list[];
7310 }
7311 */
7312 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007313 Result += "\n";
7314 if (LangOpts.MicrosoftExt) {
7315 if (IsInstanceMethod)
7316 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7317 else
7318 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7319 }
7320 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007321 Result += "\tstruct _objc_method_list *next_method;\n";
7322 Result += "\tint method_count;\n";
7323 Result += "\tstruct _objc_method method_list[";
7324 Result += utostr(NumMethods);
7325 Result += "];\n} _OBJC_";
7326 Result += prefix;
7327 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7328 Result += "_METHODS_";
7329 Result += ClassName;
7330 Result += " __attribute__ ((used, section (\"__OBJC, __";
7331 Result += IsInstanceMethod ? "inst" : "cls";
7332 Result += "_meth\")))= ";
7333 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7334
7335 Result += "\t,{{(SEL)\"";
7336 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7337 std::string MethodTypeString;
7338 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7339 Result += "\", \"";
7340 Result += MethodTypeString;
7341 Result += "\", (void *)";
7342 Result += MethodInternalNames[*MethodBegin];
7343 Result += "}\n";
7344 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7345 Result += "\t ,{(SEL)\"";
7346 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7347 std::string MethodTypeString;
7348 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7349 Result += "\", \"";
7350 Result += MethodTypeString;
7351 Result += "\", (void *)";
7352 Result += MethodInternalNames[*MethodBegin];
7353 Result += "}\n";
7354 }
7355 Result += "\t }\n};\n";
7356}
7357
7358Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7359 SourceRange OldRange = IV->getSourceRange();
7360 Expr *BaseExpr = IV->getBase();
7361
7362 // Rewrite the base, but without actually doing replaces.
7363 {
7364 DisableReplaceStmtScope S(*this);
7365 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7366 IV->setBase(BaseExpr);
7367 }
7368
7369 ObjCIvarDecl *D = IV->getDecl();
7370
7371 Expr *Replacement = IV;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007372
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007373 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7374 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +00007375 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007376 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7377 // lookup which class implements the instance variable.
7378 ObjCInterfaceDecl *clsDeclared = 0;
7379 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7380 clsDeclared);
7381 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7382
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007383 // Build name of symbol holding ivar offset.
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007384 std::string IvarOffsetName;
7385 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
7386
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00007387 ReferencedIvars[clsDeclared].insert(D);
7388
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007389 // cast offset to "char *".
7390 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7391 Context->getPointerType(Context->CharTy),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007392 CK_BitCast,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007393 BaseExpr);
7394 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7395 SourceLocation(), &Context->Idents.get(IvarOffsetName),
7396 Context->UnsignedLongTy, 0, SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00007397 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7398 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007399 SourceLocation());
7400 BinaryOperator *addExpr =
7401 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7402 Context->getPointerType(Context->CharTy),
7403 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007404 // Don't forget the parens to enforce the proper binding.
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007405 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7406 SourceLocation(),
7407 addExpr);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007408 QualType IvarT = D->getType();
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007409
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00007410 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007411 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00007412 RD = RD->getDefinition();
7413 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007414 // decltype(((Foo_IMPL*)0)->bar) *
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00007415 ObjCContainerDecl *CDecl =
7416 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7417 // ivar in class extensions requires special treatment.
7418 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7419 CDecl = CatDecl->getClassInterface();
7420 std::string RecName = CDecl->getName();
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007421 RecName += "_IMPL";
7422 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
7423 SourceLocation(), SourceLocation(),
7424 &Context->Idents.get(RecName.c_str()));
7425 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7426 unsigned UnsignedIntSize =
7427 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7428 Expr *Zero = IntegerLiteral::Create(*Context,
7429 llvm::APInt(UnsignedIntSize, 0),
7430 Context->UnsignedIntTy, SourceLocation());
7431 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7432 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7433 Zero);
7434 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7435 SourceLocation(),
7436 &Context->Idents.get(D->getNameAsString()),
7437 IvarT, 0,
7438 /*BitWidth=*/0, /*Mutable=*/true,
7439 /*HasInit=*/false);
7440 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
7441 FD->getType(), VK_LValue,
7442 OK_Ordinary);
7443 IvarT = Context->getDecltypeType(ME, ME->getType());
7444 }
7445 }
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007446 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007447 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007448
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007449 castExpr = NoTypeInfoCStyleCastExpr(Context,
7450 castT,
7451 CK_BitCast,
7452 PE);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007453
7454
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007455 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007456 VK_LValue, OK_Ordinary,
7457 SourceLocation());
7458 PE = new (Context) ParenExpr(OldRange.getBegin(),
7459 OldRange.getEnd(),
7460 Exp);
7461
7462 Replacement = PE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007463 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007464
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007465 ReplaceStmtWithRange(IV, Replacement, OldRange);
7466 return Replacement;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007467}