blob: c4b0e5e48ebd4baf3108e1e128720472dd37f783 [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;
76 unsigned RewriteFailedDiag;
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +000077 unsigned GlobalBlockRewriteFailedDiag;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000078 // ObjC string constant support.
79 unsigned NumObjCStringLiterals;
80 VarDecl *ConstantStringClassReference;
81 RecordDecl *NSStringRecord;
82
83 // ObjC foreach break/continue generation support.
84 int BcLabelCount;
85
86 unsigned TryFinallyContainsReturnDiag;
87 // Needed for super.
88 ObjCMethodDecl *CurMethodDef;
89 RecordDecl *SuperStructDecl;
90 RecordDecl *ConstantStringDecl;
91
92 FunctionDecl *MsgSendFunctionDecl;
93 FunctionDecl *MsgSendSuperFunctionDecl;
94 FunctionDecl *MsgSendStretFunctionDecl;
95 FunctionDecl *MsgSendSuperStretFunctionDecl;
96 FunctionDecl *MsgSendFpretFunctionDecl;
97 FunctionDecl *GetClassFunctionDecl;
98 FunctionDecl *GetMetaClassFunctionDecl;
99 FunctionDecl *GetSuperClassFunctionDecl;
100 FunctionDecl *SelGetUidFunctionDecl;
101 FunctionDecl *CFStringFunctionDecl;
102 FunctionDecl *SuperContructorFunctionDecl;
103 FunctionDecl *CurFunctionDef;
104 FunctionDecl *CurFunctionDeclToDeclareForBlock;
105
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 Jahanian15f87772012-02-28 22:45:07 +0000112 llvm::SmallPtrSet<TagDecl*, 8> TagsDefinedInIvarDecls;
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);
306 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
307 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
308 void RewriteTypeOfDecl(VarDecl *VD);
309 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
310
311 // Expression Rewriting.
312 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
313 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
314 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
315 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
316 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
317 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
318 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
319 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000320 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
321 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
322 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
323 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
324 SourceLocation OrigEnd);
325 Stmt *RewriteBreakStmt(BreakStmt *S);
326 Stmt *RewriteContinueStmt(ContinueStmt *S);
327 void RewriteCastExpr(CStyleCastExpr *CE);
328
329 // Block rewriting.
330 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
331
332 // Block specific rewrite rules.
333 void RewriteBlockPointerDecl(NamedDecl *VD);
334 void RewriteByRefVar(VarDecl *VD);
John McCallf4b88a42012-03-10 09:33:50 +0000335 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000336 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
337 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
338
339 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
340 std::string &Result);
341
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000342 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
343
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +0000344 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
345
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000346 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
347 std::string &Result);
348
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000349 virtual void Initialize(ASTContext &context);
350
351 // Misc. AST transformation routines. Somtimes they end up calling
352 // rewriting routines on the new ASTs.
353 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
354 Expr **args, unsigned nargs,
355 SourceLocation StartLoc=SourceLocation(),
356 SourceLocation EndLoc=SourceLocation());
357
358 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
359 SourceLocation StartLoc=SourceLocation(),
360 SourceLocation EndLoc=SourceLocation());
361
362 void SynthCountByEnumWithState(std::string &buf);
363 void SynthMsgSendFunctionDecl();
364 void SynthMsgSendSuperFunctionDecl();
365 void SynthMsgSendStretFunctionDecl();
366 void SynthMsgSendFpretFunctionDecl();
367 void SynthMsgSendSuperStretFunctionDecl();
368 void SynthGetClassFunctionDecl();
369 void SynthGetMetaClassFunctionDecl();
370 void SynthGetSuperClassFunctionDecl();
371 void SynthSelGetUidFunctionDecl();
372 void SynthSuperContructorFunctionDecl();
373
374 // Rewriting metadata
375 template<typename MethodIterator>
376 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
377 MethodIterator MethodEnd,
378 bool IsInstanceMethod,
379 StringRef prefix,
380 StringRef ClassName,
381 std::string &Result);
Fariborz Jahanianda9624a2012-02-08 19:53:58 +0000382 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
383 std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000384 virtual void RewriteObjCProtocolListMetaData(
385 const ObjCList<ObjCProtocolDecl> &Prots,
386 StringRef prefix, StringRef ClassName, std::string &Result);
387 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
388 std::string &Result);
389 virtual void RewriteMetaDataIntoBuffer(std::string &Result);
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +0000390 virtual void WriteImageInfo(std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000391 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
392 std::string &Result);
393
394 // Rewriting ivar
395 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
396 std::string &Result);
397 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
398
399
400 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
401 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
402 StringRef funcName, std::string Tag);
403 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
404 StringRef funcName, std::string Tag);
405 std::string SynthesizeBlockImpl(BlockExpr *CE,
406 std::string Tag, std::string Desc);
407 std::string SynthesizeBlockDescriptor(std::string DescTag,
408 std::string ImplTag,
409 int i, StringRef funcName,
410 unsigned hasCopy);
411 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
412 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
413 StringRef FunName);
414 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
415 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +0000416 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000417
418 // Misc. helper routines.
419 QualType getProtocolType();
420 void WarnAboutReturnGotoStmts(Stmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000421 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
422 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
423 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
424
425 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
426 void CollectBlockDeclRefInfo(BlockExpr *Exp);
427 void GetBlockDeclRefExprs(Stmt *S);
428 void GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +0000429 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000430 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
431
432 // We avoid calling Type::isBlockPointerType(), since it operates on the
433 // canonical type. We only care if the top-level type is a closure pointer.
434 bool isTopLevelBlockPointerType(QualType T) {
435 return isa<BlockPointerType>(T);
436 }
437
438 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
439 /// to a function pointer type and upon success, returns true; false
440 /// otherwise.
441 bool convertBlockPointerToFunctionPointer(QualType &T) {
442 if (isTopLevelBlockPointerType(T)) {
443 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
444 T = Context->getPointerType(BPT->getPointeeType());
445 return true;
446 }
447 return false;
448 }
449
Fariborz Jahanian164d6f82012-02-13 18:57:49 +0000450 bool convertObjCTypeToCStyleType(QualType &T);
451
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000452 bool needToScanForQualifiers(QualType T);
453 QualType getSuperStructType();
454 QualType getConstantStringStructType();
455 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
456 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
457
458 void convertToUnqualifiedObjCType(QualType &T) {
459 if (T->isObjCQualifiedIdType())
460 T = Context->getObjCIdType();
461 else if (T->isObjCQualifiedClassType())
462 T = Context->getObjCClassType();
463 else if (T->isObjCObjectPointerType() &&
464 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
465 if (const ObjCObjectPointerType * OBJPT =
466 T->getAsObjCInterfacePointerType()) {
467 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
468 T = QualType(IFaceT, 0);
469 T = Context->getPointerType(T);
470 }
471 }
472 }
473
474 // FIXME: This predicate seems like it would be useful to add to ASTContext.
475 bool isObjCType(QualType T) {
476 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
477 return false;
478
479 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
480
481 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
482 OCT == Context->getCanonicalType(Context->getObjCClassType()))
483 return true;
484
485 if (const PointerType *PT = OCT->getAs<PointerType>()) {
486 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
487 PT->getPointeeType()->isObjCQualifiedIdType())
488 return true;
489 }
490 return false;
491 }
492 bool PointerTypeTakesAnyBlockArguments(QualType QT);
493 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
494 void GetExtentOfArgList(const char *Name, const char *&LParen,
495 const char *&RParen);
496
497 void QuoteDoublequotes(std::string &From, std::string &To) {
498 for (unsigned i = 0; i < From.length(); i++) {
499 if (From[i] == '"')
500 To += "\\\"";
501 else
502 To += From[i];
503 }
504 }
505
506 QualType getSimpleFunctionType(QualType result,
507 const QualType *args,
508 unsigned numArgs,
509 bool variadic = false) {
510 if (result == Context->getObjCInstanceType())
511 result = Context->getObjCIdType();
512 FunctionProtoType::ExtProtoInfo fpi;
513 fpi.Variadic = variadic;
514 return Context->getFunctionType(result, args, numArgs, fpi);
515 }
516
517 // Helper function: create a CStyleCastExpr with trivial type source info.
518 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
519 CastKind Kind, Expr *E) {
520 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
521 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
522 SourceLocation(), SourceLocation());
523 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000524
525 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
526 IdentifierInfo* II = &Context->Idents.get("load");
527 Selector LoadSel = Context->Selectors.getSelector(0, &II);
528 return OD->getClassMethod(LoadSel) != 0;
529 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000530 };
531
532}
533
534void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
535 NamedDecl *D) {
536 if (const FunctionProtoType *fproto
537 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
538 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
539 E = fproto->arg_type_end(); I && (I != E); ++I)
540 if (isTopLevelBlockPointerType(*I)) {
541 // All the args are checked/rewritten. Don't call twice!
542 RewriteBlockPointerDecl(D);
543 break;
544 }
545 }
546}
547
548void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
549 const PointerType *PT = funcType->getAs<PointerType>();
550 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
551 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
552}
553
554static bool IsHeaderFile(const std::string &Filename) {
555 std::string::size_type DotPos = Filename.rfind('.');
556
557 if (DotPos == std::string::npos) {
558 // no file extension
559 return false;
560 }
561
562 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
563 // C header: .h
564 // C++ header: .hh or .H;
565 return Ext == "h" || Ext == "hh" || Ext == "H";
566}
567
568RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
569 DiagnosticsEngine &D, const LangOptions &LOpts,
570 bool silenceMacroWarn)
571 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
572 SilenceRewriteMacroWarning(silenceMacroWarn) {
573 IsHeader = IsHeaderFile(inFile);
574 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
575 "rewriting sub-expression within a macro (may not be correct)");
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +0000576 // FIXME. This should be an error. But if block is not called, it is OK. And it
577 // may break including some headers.
578 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
579 "rewriting block literal declared in global scope is not implemented");
580
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000581 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
582 DiagnosticsEngine::Warning,
583 "rewriter doesn't support user-specified control flow semantics "
584 "for @try/@finally (code may not execute properly)");
585}
586
587ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
588 raw_ostream* OS,
589 DiagnosticsEngine &Diags,
590 const LangOptions &LOpts,
591 bool SilenceRewriteMacroWarning) {
592 return new RewriteModernObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
593}
594
595void RewriteModernObjC::InitializeCommon(ASTContext &context) {
596 Context = &context;
597 SM = &Context->getSourceManager();
598 TUDecl = Context->getTranslationUnitDecl();
599 MsgSendFunctionDecl = 0;
600 MsgSendSuperFunctionDecl = 0;
601 MsgSendStretFunctionDecl = 0;
602 MsgSendSuperStretFunctionDecl = 0;
603 MsgSendFpretFunctionDecl = 0;
604 GetClassFunctionDecl = 0;
605 GetMetaClassFunctionDecl = 0;
606 GetSuperClassFunctionDecl = 0;
607 SelGetUidFunctionDecl = 0;
608 CFStringFunctionDecl = 0;
609 ConstantStringClassReference = 0;
610 NSStringRecord = 0;
611 CurMethodDef = 0;
612 CurFunctionDef = 0;
613 CurFunctionDeclToDeclareForBlock = 0;
614 GlobalVarDecl = 0;
615 SuperStructDecl = 0;
616 ProtocolTypeDecl = 0;
617 ConstantStringDecl = 0;
618 BcLabelCount = 0;
619 SuperContructorFunctionDecl = 0;
620 NumObjCStringLiterals = 0;
621 PropParentMap = 0;
622 CurrentBody = 0;
623 DisableReplaceStmt = false;
624 objc_impl_method = false;
625
626 // Get the ID and start/end of the main file.
627 MainFileID = SM->getMainFileID();
628 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
629 MainFileStart = MainBuf->getBufferStart();
630 MainFileEnd = MainBuf->getBufferEnd();
631
David Blaikie4e4d0842012-03-11 07:00:24 +0000632 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000633}
634
635//===----------------------------------------------------------------------===//
636// Top Level Driver Code
637//===----------------------------------------------------------------------===//
638
639void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
640 if (Diags.hasErrorOccurred())
641 return;
642
643 // Two cases: either the decl could be in the main file, or it could be in a
644 // #included file. If the former, rewrite it now. If the later, check to see
645 // if we rewrote the #include/#import.
646 SourceLocation Loc = D->getLocation();
647 Loc = SM->getExpansionLoc(Loc);
648
649 // If this is for a builtin, ignore it.
650 if (Loc.isInvalid()) return;
651
652 // Look for built-in declarations that we need to refer during the rewrite.
653 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
654 RewriteFunctionDecl(FD);
655 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
656 // declared in <Foundation/NSString.h>
657 if (FVD->getName() == "_NSConstantStringClassReference") {
658 ConstantStringClassReference = FVD;
659 return;
660 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000661 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
662 RewriteCategoryDecl(CD);
663 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
664 if (PD->isThisDeclarationADefinition())
665 RewriteProtocolDecl(PD);
666 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
667 // Recurse into linkage specifications
668 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
669 DIEnd = LSD->decls_end();
670 DI != DIEnd; ) {
671 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
672 if (!IFace->isThisDeclarationADefinition()) {
673 SmallVector<Decl *, 8> DG;
674 SourceLocation StartLoc = IFace->getLocStart();
675 do {
676 if (isa<ObjCInterfaceDecl>(*DI) &&
677 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
678 StartLoc == (*DI)->getLocStart())
679 DG.push_back(*DI);
680 else
681 break;
682
683 ++DI;
684 } while (DI != DIEnd);
685 RewriteForwardClassDecl(DG);
686 continue;
687 }
688 }
689
690 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
691 if (!Proto->isThisDeclarationADefinition()) {
692 SmallVector<Decl *, 8> DG;
693 SourceLocation StartLoc = Proto->getLocStart();
694 do {
695 if (isa<ObjCProtocolDecl>(*DI) &&
696 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
697 StartLoc == (*DI)->getLocStart())
698 DG.push_back(*DI);
699 else
700 break;
701
702 ++DI;
703 } while (DI != DIEnd);
704 RewriteForwardProtocolDecl(DG);
705 continue;
706 }
707 }
708
709 HandleTopLevelSingleDecl(*DI);
710 ++DI;
711 }
712 }
713 // If we have a decl in the main file, see if we should rewrite it.
714 if (SM->isFromMainFile(Loc))
715 return HandleDeclInMainFile(D);
716}
717
718//===----------------------------------------------------------------------===//
719// Syntactic (non-AST) Rewriting Code
720//===----------------------------------------------------------------------===//
721
722void RewriteModernObjC::RewriteInclude() {
723 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
724 StringRef MainBuf = SM->getBufferData(MainFileID);
725 const char *MainBufStart = MainBuf.begin();
726 const char *MainBufEnd = MainBuf.end();
727 size_t ImportLen = strlen("import");
728
729 // Loop over the whole file, looking for includes.
730 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
731 if (*BufPtr == '#') {
732 if (++BufPtr == MainBufEnd)
733 return;
734 while (*BufPtr == ' ' || *BufPtr == '\t')
735 if (++BufPtr == MainBufEnd)
736 return;
737 if (!strncmp(BufPtr, "import", ImportLen)) {
738 // replace import with include
739 SourceLocation ImportLoc =
740 LocStart.getLocWithOffset(BufPtr-MainBufStart);
741 ReplaceText(ImportLoc, ImportLen, "include");
742 BufPtr += ImportLen;
743 }
744 }
745 }
746}
747
748static std::string getIvarAccessString(ObjCIvarDecl *OID) {
749 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
750 std::string S;
751 S = "((struct ";
752 S += ClassDecl->getIdentifier()->getName();
753 S += "_IMPL *)self)->";
754 S += OID->getName();
755 return S;
756}
757
758void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
759 ObjCImplementationDecl *IMD,
760 ObjCCategoryImplDecl *CID) {
761 static bool objcGetPropertyDefined = false;
762 static bool objcSetPropertyDefined = false;
763 SourceLocation startLoc = PID->getLocStart();
764 InsertText(startLoc, "// ");
765 const char *startBuf = SM->getCharacterData(startLoc);
766 assert((*startBuf == '@') && "bogus @synthesize location");
767 const char *semiBuf = strchr(startBuf, ';');
768 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
769 SourceLocation onePastSemiLoc =
770 startLoc.getLocWithOffset(semiBuf-startBuf+1);
771
772 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
773 return; // FIXME: is this correct?
774
775 // Generate the 'getter' function.
776 ObjCPropertyDecl *PD = PID->getPropertyDecl();
777 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
778
779 if (!OID)
780 return;
781 unsigned Attributes = PD->getPropertyAttributes();
782 if (!PD->getGetterMethodDecl()->isDefined()) {
783 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
784 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
785 ObjCPropertyDecl::OBJC_PR_copy));
786 std::string Getr;
787 if (GenGetProperty && !objcGetPropertyDefined) {
788 objcGetPropertyDefined = true;
789 // FIXME. Is this attribute correct in all cases?
790 Getr = "\nextern \"C\" __declspec(dllimport) "
791 "id objc_getProperty(id, SEL, long, bool);\n";
792 }
793 RewriteObjCMethodDecl(OID->getContainingInterface(),
794 PD->getGetterMethodDecl(), Getr);
795 Getr += "{ ";
796 // Synthesize an explicit cast to gain access to the ivar.
797 // See objc-act.c:objc_synthesize_new_getter() for details.
798 if (GenGetProperty) {
799 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
800 Getr += "typedef ";
801 const FunctionType *FPRetType = 0;
802 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
803 FPRetType);
804 Getr += " _TYPE";
805 if (FPRetType) {
806 Getr += ")"; // close the precedence "scope" for "*".
807
808 // Now, emit the argument types (if any).
809 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
810 Getr += "(";
811 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
812 if (i) Getr += ", ";
813 std::string ParamStr = FT->getArgType(i).getAsString(
814 Context->getPrintingPolicy());
815 Getr += ParamStr;
816 }
817 if (FT->isVariadic()) {
818 if (FT->getNumArgs()) Getr += ", ";
819 Getr += "...";
820 }
821 Getr += ")";
822 } else
823 Getr += "()";
824 }
825 Getr += ";\n";
826 Getr += "return (_TYPE)";
827 Getr += "objc_getProperty(self, _cmd, ";
828 RewriteIvarOffsetComputation(OID, Getr);
829 Getr += ", 1)";
830 }
831 else
832 Getr += "return " + getIvarAccessString(OID);
833 Getr += "; }";
834 InsertText(onePastSemiLoc, Getr);
835 }
836
837 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
838 return;
839
840 // Generate the 'setter' function.
841 std::string Setr;
842 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
843 ObjCPropertyDecl::OBJC_PR_copy);
844 if (GenSetProperty && !objcSetPropertyDefined) {
845 objcSetPropertyDefined = true;
846 // FIXME. Is this attribute correct in all cases?
847 Setr = "\nextern \"C\" __declspec(dllimport) "
848 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
849 }
850
851 RewriteObjCMethodDecl(OID->getContainingInterface(),
852 PD->getSetterMethodDecl(), Setr);
853 Setr += "{ ";
854 // Synthesize an explicit cast to initialize the ivar.
855 // See objc-act.c:objc_synthesize_new_setter() for details.
856 if (GenSetProperty) {
857 Setr += "objc_setProperty (self, _cmd, ";
858 RewriteIvarOffsetComputation(OID, Setr);
859 Setr += ", (id)";
860 Setr += PD->getName();
861 Setr += ", ";
862 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
863 Setr += "0, ";
864 else
865 Setr += "1, ";
866 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
867 Setr += "1)";
868 else
869 Setr += "0)";
870 }
871 else {
872 Setr += getIvarAccessString(OID) + " = ";
873 Setr += PD->getName();
874 }
875 Setr += "; }";
876 InsertText(onePastSemiLoc, Setr);
877}
878
879static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
880 std::string &typedefString) {
881 typedefString += "#ifndef _REWRITER_typedef_";
882 typedefString += ForwardDecl->getNameAsString();
883 typedefString += "\n";
884 typedefString += "#define _REWRITER_typedef_";
885 typedefString += ForwardDecl->getNameAsString();
886 typedefString += "\n";
887 typedefString += "typedef struct objc_object ";
888 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +0000889 // typedef struct { } _objc_exc_Classname;
890 typedefString += ";\ntypedef struct {} _objc_exc_";
891 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000892 typedefString += ";\n#endif\n";
893}
894
895void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
896 const std::string &typedefString) {
897 SourceLocation startLoc = ClassDecl->getLocStart();
898 const char *startBuf = SM->getCharacterData(startLoc);
899 const char *semiPtr = strchr(startBuf, ';');
900 // Replace the @class with typedefs corresponding to the classes.
901 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
902}
903
904void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
905 std::string typedefString;
906 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
907 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
908 if (I == D.begin()) {
909 // Translate to typedef's that forward reference structs with the same name
910 // as the class. As a convenience, we include the original declaration
911 // as a comment.
912 typedefString += "// @class ";
913 typedefString += ForwardDecl->getNameAsString();
914 typedefString += ";\n";
915 }
916 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
917 }
918 DeclGroupRef::iterator I = D.begin();
919 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
920}
921
922void RewriteModernObjC::RewriteForwardClassDecl(
923 const llvm::SmallVector<Decl*, 8> &D) {
924 std::string typedefString;
925 for (unsigned i = 0; i < D.size(); i++) {
926 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
927 if (i == 0) {
928 typedefString += "// @class ";
929 typedefString += ForwardDecl->getNameAsString();
930 typedefString += ";\n";
931 }
932 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
933 }
934 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
935}
936
937void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
938 // When method is a synthesized one, such as a getter/setter there is
939 // nothing to rewrite.
940 if (Method->isImplicit())
941 return;
942 SourceLocation LocStart = Method->getLocStart();
943 SourceLocation LocEnd = Method->getLocEnd();
944
945 if (SM->getExpansionLineNumber(LocEnd) >
946 SM->getExpansionLineNumber(LocStart)) {
947 InsertText(LocStart, "#if 0\n");
948 ReplaceText(LocEnd, 1, ";\n#endif\n");
949 } else {
950 InsertText(LocStart, "// ");
951 }
952}
953
954void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
955 SourceLocation Loc = prop->getAtLoc();
956
957 ReplaceText(Loc, 0, "// ");
958 // FIXME: handle properties that are declared across multiple lines.
959}
960
961void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
962 SourceLocation LocStart = CatDecl->getLocStart();
963
964 // FIXME: handle category headers that are declared across multiple lines.
965 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianaf300292012-02-20 20:09:20 +0000966 if (CatDecl->getIvarLBraceLoc().isValid())
967 InsertText(CatDecl->getIvarLBraceLoc(), "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +0000968 for (ObjCCategoryDecl::ivar_iterator
969 I = CatDecl->ivar_begin(), E = CatDecl->ivar_end(); I != E; ++I) {
970 ObjCIvarDecl *Ivar = (*I);
971 SourceLocation LocStart = Ivar->getLocStart();
972 ReplaceText(LocStart, 0, "// ");
973 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +0000974 if (CatDecl->getIvarRBraceLoc().isValid())
975 InsertText(CatDecl->getIvarRBraceLoc(), "// ");
976
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000977 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
978 E = CatDecl->prop_end(); I != E; ++I)
979 RewriteProperty(*I);
980
981 for (ObjCCategoryDecl::instmeth_iterator
982 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
983 I != E; ++I)
984 RewriteMethodDeclaration(*I);
985 for (ObjCCategoryDecl::classmeth_iterator
986 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
987 I != E; ++I)
988 RewriteMethodDeclaration(*I);
989
990 // Lastly, comment out the @end.
991 ReplaceText(CatDecl->getAtEndRange().getBegin(),
992 strlen("@end"), "/* @end */");
993}
994
995void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
996 SourceLocation LocStart = PDecl->getLocStart();
997 assert(PDecl->isThisDeclarationADefinition());
998
999 // FIXME: handle protocol headers that are declared across multiple lines.
1000 ReplaceText(LocStart, 0, "// ");
1001
1002 for (ObjCProtocolDecl::instmeth_iterator
1003 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
1004 I != E; ++I)
1005 RewriteMethodDeclaration(*I);
1006 for (ObjCProtocolDecl::classmeth_iterator
1007 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1008 I != E; ++I)
1009 RewriteMethodDeclaration(*I);
1010
1011 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1012 E = PDecl->prop_end(); I != E; ++I)
1013 RewriteProperty(*I);
1014
1015 // Lastly, comment out the @end.
1016 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1017 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
1018
1019 // Must comment out @optional/@required
1020 const char *startBuf = SM->getCharacterData(LocStart);
1021 const char *endBuf = SM->getCharacterData(LocEnd);
1022 for (const char *p = startBuf; p < endBuf; p++) {
1023 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1024 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1025 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1026
1027 }
1028 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1029 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1030 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1031
1032 }
1033 }
1034}
1035
1036void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1037 SourceLocation LocStart = (*D.begin())->getLocStart();
1038 if (LocStart.isInvalid())
1039 llvm_unreachable("Invalid SourceLocation");
1040 // FIXME: handle forward protocol that are declared across multiple lines.
1041 ReplaceText(LocStart, 0, "// ");
1042}
1043
1044void
1045RewriteModernObjC::RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG) {
1046 SourceLocation LocStart = DG[0]->getLocStart();
1047 if (LocStart.isInvalid())
1048 llvm_unreachable("Invalid SourceLocation");
1049 // FIXME: handle forward protocol that are declared across multiple lines.
1050 ReplaceText(LocStart, 0, "// ");
1051}
1052
1053void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1054 const FunctionType *&FPRetType) {
1055 if (T->isObjCQualifiedIdType())
1056 ResultStr += "id";
1057 else if (T->isFunctionPointerType() ||
1058 T->isBlockPointerType()) {
1059 // needs special handling, since pointer-to-functions have special
1060 // syntax (where a decaration models use).
1061 QualType retType = T;
1062 QualType PointeeTy;
1063 if (const PointerType* PT = retType->getAs<PointerType>())
1064 PointeeTy = PT->getPointeeType();
1065 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1066 PointeeTy = BPT->getPointeeType();
1067 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1068 ResultStr += FPRetType->getResultType().getAsString(
1069 Context->getPrintingPolicy());
1070 ResultStr += "(*";
1071 }
1072 } else
1073 ResultStr += T.getAsString(Context->getPrintingPolicy());
1074}
1075
1076void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1077 ObjCMethodDecl *OMD,
1078 std::string &ResultStr) {
1079 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1080 const FunctionType *FPRetType = 0;
1081 ResultStr += "\nstatic ";
1082 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1083 ResultStr += " ";
1084
1085 // Unique method name
1086 std::string NameStr;
1087
1088 if (OMD->isInstanceMethod())
1089 NameStr += "_I_";
1090 else
1091 NameStr += "_C_";
1092
1093 NameStr += IDecl->getNameAsString();
1094 NameStr += "_";
1095
1096 if (ObjCCategoryImplDecl *CID =
1097 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1098 NameStr += CID->getNameAsString();
1099 NameStr += "_";
1100 }
1101 // Append selector names, replacing ':' with '_'
1102 {
1103 std::string selString = OMD->getSelector().getAsString();
1104 int len = selString.size();
1105 for (int i = 0; i < len; i++)
1106 if (selString[i] == ':')
1107 selString[i] = '_';
1108 NameStr += selString;
1109 }
1110 // Remember this name for metadata emission
1111 MethodInternalNames[OMD] = NameStr;
1112 ResultStr += NameStr;
1113
1114 // Rewrite arguments
1115 ResultStr += "(";
1116
1117 // invisible arguments
1118 if (OMD->isInstanceMethod()) {
1119 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1120 selfTy = Context->getPointerType(selfTy);
1121 if (!LangOpts.MicrosoftExt) {
1122 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1123 ResultStr += "struct ";
1124 }
1125 // When rewriting for Microsoft, explicitly omit the structure name.
1126 ResultStr += IDecl->getNameAsString();
1127 ResultStr += " *";
1128 }
1129 else
1130 ResultStr += Context->getObjCClassType().getAsString(
1131 Context->getPrintingPolicy());
1132
1133 ResultStr += " self, ";
1134 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1135 ResultStr += " _cmd";
1136
1137 // Method arguments.
1138 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1139 E = OMD->param_end(); PI != E; ++PI) {
1140 ParmVarDecl *PDecl = *PI;
1141 ResultStr += ", ";
1142 if (PDecl->getType()->isObjCQualifiedIdType()) {
1143 ResultStr += "id ";
1144 ResultStr += PDecl->getNameAsString();
1145 } else {
1146 std::string Name = PDecl->getNameAsString();
1147 QualType QT = PDecl->getType();
1148 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1149 if (convertBlockPointerToFunctionPointer(QT))
1150 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
1151 else
1152 PDecl->getType().getAsStringInternal(Name, Context->getPrintingPolicy());
1153 ResultStr += Name;
1154 }
1155 }
1156 if (OMD->isVariadic())
1157 ResultStr += ", ...";
1158 ResultStr += ") ";
1159
1160 if (FPRetType) {
1161 ResultStr += ")"; // close the precedence "scope" for "*".
1162
1163 // Now, emit the argument types (if any).
1164 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1165 ResultStr += "(";
1166 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1167 if (i) ResultStr += ", ";
1168 std::string ParamStr = FT->getArgType(i).getAsString(
1169 Context->getPrintingPolicy());
1170 ResultStr += ParamStr;
1171 }
1172 if (FT->isVariadic()) {
1173 if (FT->getNumArgs()) ResultStr += ", ";
1174 ResultStr += "...";
1175 }
1176 ResultStr += ")";
1177 } else {
1178 ResultStr += "()";
1179 }
1180 }
1181}
1182void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1183 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1184 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1185
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001186 if (IMD) {
1187 InsertText(IMD->getLocStart(), "// ");
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001188 if (IMD->getIvarLBraceLoc().isValid())
1189 InsertText(IMD->getIvarLBraceLoc(), "// ");
1190 for (ObjCImplementationDecl::ivar_iterator
1191 I = IMD->ivar_begin(), E = IMD->ivar_end(); I != E; ++I) {
1192 ObjCIvarDecl *Ivar = (*I);
1193 SourceLocation LocStart = Ivar->getLocStart();
1194 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001195 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001196 if (IMD->getIvarRBraceLoc().isValid())
1197 InsertText(IMD->getIvarRBraceLoc(), "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001198 }
1199 else
1200 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001201
1202 for (ObjCCategoryImplDecl::instmeth_iterator
1203 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1204 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1205 I != E; ++I) {
1206 std::string ResultStr;
1207 ObjCMethodDecl *OMD = *I;
1208 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1209 SourceLocation LocStart = OMD->getLocStart();
1210 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1211
1212 const char *startBuf = SM->getCharacterData(LocStart);
1213 const char *endBuf = SM->getCharacterData(LocEnd);
1214 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1215 }
1216
1217 for (ObjCCategoryImplDecl::classmeth_iterator
1218 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1219 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1220 I != E; ++I) {
1221 std::string ResultStr;
1222 ObjCMethodDecl *OMD = *I;
1223 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1224 SourceLocation LocStart = OMD->getLocStart();
1225 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1226
1227 const char *startBuf = SM->getCharacterData(LocStart);
1228 const char *endBuf = SM->getCharacterData(LocEnd);
1229 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1230 }
1231 for (ObjCCategoryImplDecl::propimpl_iterator
1232 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1233 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1234 I != E; ++I) {
1235 RewritePropertyImplDecl(*I, IMD, CID);
1236 }
1237
1238 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1239}
1240
1241void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00001242 // Do not synthesize more than once.
1243 if (ObjCSynthesizedStructs.count(ClassDecl))
1244 return;
1245 // Make sure super class's are written before current class is written.
1246 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1247 while (SuperClass) {
1248 RewriteInterfaceDecl(SuperClass);
1249 SuperClass = SuperClass->getSuperClass();
1250 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001251 std::string ResultStr;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001252 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001253 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001254 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00001255 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1256
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001257 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001258 // Mark this typedef as having been written into its c++ equivalent.
1259 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001260
1261 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001262 E = ClassDecl->prop_end(); I != E; ++I)
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001263 RewriteProperty(*I);
1264 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001265 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001266 I != E; ++I)
1267 RewriteMethodDeclaration(*I);
1268 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001269 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001270 I != E; ++I)
1271 RewriteMethodDeclaration(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001272
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001273 // Lastly, comment out the @end.
1274 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1275 "/* @end */");
1276 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001277}
1278
1279Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1280 SourceRange OldRange = PseudoOp->getSourceRange();
1281
1282 // We just magically know some things about the structure of this
1283 // expression.
1284 ObjCMessageExpr *OldMsg =
1285 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1286 PseudoOp->getNumSemanticExprs() - 1));
1287
1288 // Because the rewriter doesn't allow us to rewrite rewritten code,
1289 // we need to suppress rewriting the sub-statements.
1290 Expr *Base, *RHS;
1291 {
1292 DisableReplaceStmtScope S(*this);
1293
1294 // Rebuild the base expression if we have one.
1295 Base = 0;
1296 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1297 Base = OldMsg->getInstanceReceiver();
1298 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1299 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1300 }
1301
1302 // Rebuild the RHS.
1303 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1304 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1305 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1306 }
1307
1308 // TODO: avoid this copy.
1309 SmallVector<SourceLocation, 1> SelLocs;
1310 OldMsg->getSelectorLocs(SelLocs);
1311
1312 ObjCMessageExpr *NewMsg = 0;
1313 switch (OldMsg->getReceiverKind()) {
1314 case ObjCMessageExpr::Class:
1315 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1316 OldMsg->getValueKind(),
1317 OldMsg->getLeftLoc(),
1318 OldMsg->getClassReceiverTypeInfo(),
1319 OldMsg->getSelector(),
1320 SelLocs,
1321 OldMsg->getMethodDecl(),
1322 RHS,
1323 OldMsg->getRightLoc(),
1324 OldMsg->isImplicit());
1325 break;
1326
1327 case ObjCMessageExpr::Instance:
1328 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1329 OldMsg->getValueKind(),
1330 OldMsg->getLeftLoc(),
1331 Base,
1332 OldMsg->getSelector(),
1333 SelLocs,
1334 OldMsg->getMethodDecl(),
1335 RHS,
1336 OldMsg->getRightLoc(),
1337 OldMsg->isImplicit());
1338 break;
1339
1340 case ObjCMessageExpr::SuperClass:
1341 case ObjCMessageExpr::SuperInstance:
1342 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1343 OldMsg->getValueKind(),
1344 OldMsg->getLeftLoc(),
1345 OldMsg->getSuperLoc(),
1346 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1347 OldMsg->getSuperType(),
1348 OldMsg->getSelector(),
1349 SelLocs,
1350 OldMsg->getMethodDecl(),
1351 RHS,
1352 OldMsg->getRightLoc(),
1353 OldMsg->isImplicit());
1354 break;
1355 }
1356
1357 Stmt *Replacement = SynthMessageExpr(NewMsg);
1358 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1359 return Replacement;
1360}
1361
1362Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1363 SourceRange OldRange = PseudoOp->getSourceRange();
1364
1365 // We just magically know some things about the structure of this
1366 // expression.
1367 ObjCMessageExpr *OldMsg =
1368 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1369
1370 // Because the rewriter doesn't allow us to rewrite rewritten code,
1371 // we need to suppress rewriting the sub-statements.
1372 Expr *Base = 0;
1373 {
1374 DisableReplaceStmtScope S(*this);
1375
1376 // Rebuild the base expression if we have one.
1377 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1378 Base = OldMsg->getInstanceReceiver();
1379 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1380 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1381 }
1382 }
1383
1384 // Intentionally empty.
1385 SmallVector<SourceLocation, 1> SelLocs;
1386 SmallVector<Expr*, 1> Args;
1387
1388 ObjCMessageExpr *NewMsg = 0;
1389 switch (OldMsg->getReceiverKind()) {
1390 case ObjCMessageExpr::Class:
1391 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1392 OldMsg->getValueKind(),
1393 OldMsg->getLeftLoc(),
1394 OldMsg->getClassReceiverTypeInfo(),
1395 OldMsg->getSelector(),
1396 SelLocs,
1397 OldMsg->getMethodDecl(),
1398 Args,
1399 OldMsg->getRightLoc(),
1400 OldMsg->isImplicit());
1401 break;
1402
1403 case ObjCMessageExpr::Instance:
1404 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1405 OldMsg->getValueKind(),
1406 OldMsg->getLeftLoc(),
1407 Base,
1408 OldMsg->getSelector(),
1409 SelLocs,
1410 OldMsg->getMethodDecl(),
1411 Args,
1412 OldMsg->getRightLoc(),
1413 OldMsg->isImplicit());
1414 break;
1415
1416 case ObjCMessageExpr::SuperClass:
1417 case ObjCMessageExpr::SuperInstance:
1418 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1419 OldMsg->getValueKind(),
1420 OldMsg->getLeftLoc(),
1421 OldMsg->getSuperLoc(),
1422 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1423 OldMsg->getSuperType(),
1424 OldMsg->getSelector(),
1425 SelLocs,
1426 OldMsg->getMethodDecl(),
1427 Args,
1428 OldMsg->getRightLoc(),
1429 OldMsg->isImplicit());
1430 break;
1431 }
1432
1433 Stmt *Replacement = SynthMessageExpr(NewMsg);
1434 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1435 return Replacement;
1436}
1437
1438/// SynthCountByEnumWithState - To print:
1439/// ((unsigned int (*)
1440/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1441/// (void *)objc_msgSend)((id)l_collection,
1442/// sel_registerName(
1443/// "countByEnumeratingWithState:objects:count:"),
1444/// &enumState,
1445/// (id *)__rw_items, (unsigned int)16)
1446///
1447void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1448 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1449 "id *, unsigned int))(void *)objc_msgSend)";
1450 buf += "\n\t\t";
1451 buf += "((id)l_collection,\n\t\t";
1452 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1453 buf += "\n\t\t";
1454 buf += "&enumState, "
1455 "(id *)__rw_items, (unsigned int)16)";
1456}
1457
1458/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1459/// statement to exit to its outer synthesized loop.
1460///
1461Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1462 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1463 return S;
1464 // replace break with goto __break_label
1465 std::string buf;
1466
1467 SourceLocation startLoc = S->getLocStart();
1468 buf = "goto __break_label_";
1469 buf += utostr(ObjCBcLabelNo.back());
1470 ReplaceText(startLoc, strlen("break"), buf);
1471
1472 return 0;
1473}
1474
1475/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1476/// statement to continue with its inner synthesized loop.
1477///
1478Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1479 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1480 return S;
1481 // replace continue with goto __continue_label
1482 std::string buf;
1483
1484 SourceLocation startLoc = S->getLocStart();
1485 buf = "goto __continue_label_";
1486 buf += utostr(ObjCBcLabelNo.back());
1487 ReplaceText(startLoc, strlen("continue"), buf);
1488
1489 return 0;
1490}
1491
1492/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1493/// It rewrites:
1494/// for ( type elem in collection) { stmts; }
1495
1496/// Into:
1497/// {
1498/// type elem;
1499/// struct __objcFastEnumerationState enumState = { 0 };
1500/// id __rw_items[16];
1501/// id l_collection = (id)collection;
1502/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1503/// objects:__rw_items count:16];
1504/// if (limit) {
1505/// unsigned long startMutations = *enumState.mutationsPtr;
1506/// do {
1507/// unsigned long counter = 0;
1508/// do {
1509/// if (startMutations != *enumState.mutationsPtr)
1510/// objc_enumerationMutation(l_collection);
1511/// elem = (type)enumState.itemsPtr[counter++];
1512/// stmts;
1513/// __continue_label: ;
1514/// } while (counter < limit);
1515/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1516/// objects:__rw_items count:16]);
1517/// elem = nil;
1518/// __break_label: ;
1519/// }
1520/// else
1521/// elem = nil;
1522/// }
1523///
1524Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1525 SourceLocation OrigEnd) {
1526 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1527 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1528 "ObjCForCollectionStmt Statement stack mismatch");
1529 assert(!ObjCBcLabelNo.empty() &&
1530 "ObjCForCollectionStmt - Label No stack empty");
1531
1532 SourceLocation startLoc = S->getLocStart();
1533 const char *startBuf = SM->getCharacterData(startLoc);
1534 StringRef elementName;
1535 std::string elementTypeAsString;
1536 std::string buf;
1537 buf = "\n{\n\t";
1538 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1539 // type elem;
1540 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1541 QualType ElementType = cast<ValueDecl>(D)->getType();
1542 if (ElementType->isObjCQualifiedIdType() ||
1543 ElementType->isObjCQualifiedInterfaceType())
1544 // Simply use 'id' for all qualified types.
1545 elementTypeAsString = "id";
1546 else
1547 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1548 buf += elementTypeAsString;
1549 buf += " ";
1550 elementName = D->getName();
1551 buf += elementName;
1552 buf += ";\n\t";
1553 }
1554 else {
1555 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1556 elementName = DR->getDecl()->getName();
1557 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1558 if (VD->getType()->isObjCQualifiedIdType() ||
1559 VD->getType()->isObjCQualifiedInterfaceType())
1560 // Simply use 'id' for all qualified types.
1561 elementTypeAsString = "id";
1562 else
1563 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1564 }
1565
1566 // struct __objcFastEnumerationState enumState = { 0 };
1567 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1568 // id __rw_items[16];
1569 buf += "id __rw_items[16];\n\t";
1570 // id l_collection = (id)
1571 buf += "id l_collection = (id)";
1572 // Find start location of 'collection' the hard way!
1573 const char *startCollectionBuf = startBuf;
1574 startCollectionBuf += 3; // skip 'for'
1575 startCollectionBuf = strchr(startCollectionBuf, '(');
1576 startCollectionBuf++; // skip '('
1577 // find 'in' and skip it.
1578 while (*startCollectionBuf != ' ' ||
1579 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1580 (*(startCollectionBuf+3) != ' ' &&
1581 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1582 startCollectionBuf++;
1583 startCollectionBuf += 3;
1584
1585 // Replace: "for (type element in" with string constructed thus far.
1586 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1587 // Replace ')' in for '(' type elem in collection ')' with ';'
1588 SourceLocation rightParenLoc = S->getRParenLoc();
1589 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1590 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1591 buf = ";\n\t";
1592
1593 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1594 // objects:__rw_items count:16];
1595 // which is synthesized into:
1596 // unsigned int limit =
1597 // ((unsigned int (*)
1598 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1599 // (void *)objc_msgSend)((id)l_collection,
1600 // sel_registerName(
1601 // "countByEnumeratingWithState:objects:count:"),
1602 // (struct __objcFastEnumerationState *)&state,
1603 // (id *)__rw_items, (unsigned int)16);
1604 buf += "unsigned long limit =\n\t\t";
1605 SynthCountByEnumWithState(buf);
1606 buf += ";\n\t";
1607 /// if (limit) {
1608 /// unsigned long startMutations = *enumState.mutationsPtr;
1609 /// do {
1610 /// unsigned long counter = 0;
1611 /// do {
1612 /// if (startMutations != *enumState.mutationsPtr)
1613 /// objc_enumerationMutation(l_collection);
1614 /// elem = (type)enumState.itemsPtr[counter++];
1615 buf += "if (limit) {\n\t";
1616 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1617 buf += "do {\n\t\t";
1618 buf += "unsigned long counter = 0;\n\t\t";
1619 buf += "do {\n\t\t\t";
1620 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1621 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1622 buf += elementName;
1623 buf += " = (";
1624 buf += elementTypeAsString;
1625 buf += ")enumState.itemsPtr[counter++];";
1626 // Replace ')' in for '(' type elem in collection ')' with all of these.
1627 ReplaceText(lparenLoc, 1, buf);
1628
1629 /// __continue_label: ;
1630 /// } while (counter < limit);
1631 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1632 /// objects:__rw_items count:16]);
1633 /// elem = nil;
1634 /// __break_label: ;
1635 /// }
1636 /// else
1637 /// elem = nil;
1638 /// }
1639 ///
1640 buf = ";\n\t";
1641 buf += "__continue_label_";
1642 buf += utostr(ObjCBcLabelNo.back());
1643 buf += ": ;";
1644 buf += "\n\t\t";
1645 buf += "} while (counter < limit);\n\t";
1646 buf += "} while (limit = ";
1647 SynthCountByEnumWithState(buf);
1648 buf += ");\n\t";
1649 buf += elementName;
1650 buf += " = ((";
1651 buf += elementTypeAsString;
1652 buf += ")0);\n\t";
1653 buf += "__break_label_";
1654 buf += utostr(ObjCBcLabelNo.back());
1655 buf += ": ;\n\t";
1656 buf += "}\n\t";
1657 buf += "else\n\t\t";
1658 buf += elementName;
1659 buf += " = ((";
1660 buf += elementTypeAsString;
1661 buf += ")0);\n\t";
1662 buf += "}\n";
1663
1664 // Insert all these *after* the statement body.
1665 // FIXME: If this should support Obj-C++, support CXXTryStmt
1666 if (isa<CompoundStmt>(S->getBody())) {
1667 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1668 InsertText(endBodyLoc, buf);
1669 } else {
1670 /* Need to treat single statements specially. For example:
1671 *
1672 * for (A *a in b) if (stuff()) break;
1673 * for (A *a in b) xxxyy;
1674 *
1675 * The following code simply scans ahead to the semi to find the actual end.
1676 */
1677 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1678 const char *semiBuf = strchr(stmtBuf, ';');
1679 assert(semiBuf && "Can't find ';'");
1680 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1681 InsertText(endBodyLoc, buf);
1682 }
1683 Stmts.pop_back();
1684 ObjCBcLabelNo.pop_back();
1685 return 0;
1686}
1687
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001688static void Write_RethrowObject(std::string &buf) {
1689 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1690 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1691 buf += "\tid rethrow;\n";
1692 buf += "\t} _fin_force_rethow(_rethrow);";
1693}
1694
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001695/// RewriteObjCSynchronizedStmt -
1696/// This routine rewrites @synchronized(expr) stmt;
1697/// into:
1698/// objc_sync_enter(expr);
1699/// @try stmt @finally { objc_sync_exit(expr); }
1700///
1701Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1702 // Get the start location and compute the semi location.
1703 SourceLocation startLoc = S->getLocStart();
1704 const char *startBuf = SM->getCharacterData(startLoc);
1705
1706 assert((*startBuf == '@') && "bogus @synchronized location");
1707
1708 std::string buf;
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001709 buf = "{ id _rethrow = 0; id _sync_obj = ";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001710
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001711 const char *lparenBuf = startBuf;
1712 while (*lparenBuf != '(') lparenBuf++;
1713 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001714
1715 buf = "; objc_sync_enter(_sync_obj);\n";
1716 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1717 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1718 buf += "\n\tid sync_exit;";
1719 buf += "\n\t} _sync_exit(_sync_obj);\n";
1720
1721 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1722 // the sync expression is typically a message expression that's already
1723 // been rewritten! (which implies the SourceLocation's are invalid).
1724 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1725 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1726 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1727 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1728
1729 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1730 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1731 assert (*LBraceLocBuf == '{');
1732 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001733
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001734 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay9ab511c2012-03-16 22:20:39 +00001735 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1736 "bogus @synchronized block");
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001737
1738 buf = "} catch (id e) {_rethrow = e;}\n";
1739 Write_RethrowObject(buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001740 buf += "}\n";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001741 buf += "}\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001742
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001743 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001744
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001745 return 0;
1746}
1747
1748void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1749{
1750 // Perform a bottom up traversal of all children.
1751 for (Stmt::child_range CI = S->children(); CI; ++CI)
1752 if (*CI)
1753 WarnAboutReturnGotoStmts(*CI);
1754
1755 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1756 Diags.Report(Context->getFullLoc(S->getLocStart()),
1757 TryFinallyContainsReturnDiag);
1758 }
1759 return;
1760}
1761
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001762Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001763 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001764 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001765 std::string buf;
1766
1767 if (finalStmt) {
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001768 if (noCatch)
1769 buf = "{ id volatile _rethrow = 0;\n";
1770 else {
1771 buf = "{ id volatile _rethrow = 0;\ntry {\n";
1772 }
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001773 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001774 // Get the start location and compute the semi location.
1775 SourceLocation startLoc = S->getLocStart();
1776 const char *startBuf = SM->getCharacterData(startLoc);
1777
1778 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001779 if (finalStmt)
1780 ReplaceText(startLoc, 1, buf);
1781 else
1782 // @try -> try
1783 ReplaceText(startLoc, 1, "");
1784
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001785 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1786 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001787 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001788
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001789 startLoc = Catch->getLocStart();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001790 bool AtRemoved = false;
1791 if (catchDecl) {
1792 QualType t = catchDecl->getType();
1793 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1794 // Should be a pointer to a class.
1795 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1796 if (IDecl) {
1797 std::string Result;
1798 startBuf = SM->getCharacterData(startLoc);
1799 assert((*startBuf == '@') && "bogus @catch location");
1800 SourceLocation rParenLoc = Catch->getRParenLoc();
1801 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1802
1803 // _objc_exc_Foo *_e as argument to catch.
1804 Result = "catch (_objc_exc_"; Result += IDecl->getNameAsString();
1805 Result += " *_"; Result += catchDecl->getNameAsString();
1806 Result += ")";
1807 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1808 // Foo *e = (Foo *)_e;
1809 Result.clear();
1810 Result = "{ ";
1811 Result += IDecl->getNameAsString();
1812 Result += " *"; Result += catchDecl->getNameAsString();
1813 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1814 Result += "_"; Result += catchDecl->getNameAsString();
1815
1816 Result += "; ";
1817 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
1818 ReplaceText(lBraceLoc, 1, Result);
1819 AtRemoved = true;
1820 }
1821 }
1822 }
1823 if (!AtRemoved)
1824 // @catch -> catch
1825 ReplaceText(startLoc, 1, "");
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001826
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001827 }
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001828 if (finalStmt) {
1829 buf.clear();
1830 if (noCatch)
1831 buf = "catch (id e) {_rethrow = e;}\n";
1832 else
1833 buf = "}\ncatch (id e) {_rethrow = e;}\n";
1834
1835 SourceLocation startFinalLoc = finalStmt->getLocStart();
1836 ReplaceText(startFinalLoc, 8, buf);
1837 Stmt *body = finalStmt->getFinallyBody();
1838 SourceLocation startFinalBodyLoc = body->getLocStart();
1839 buf.clear();
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001840 Write_RethrowObject(buf);
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001841 ReplaceText(startFinalBodyLoc, 1, buf);
1842
1843 SourceLocation endFinalBodyLoc = body->getLocEnd();
1844 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001845 // Now check for any return/continue/go statements within the @try.
1846 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001847 }
1848
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001849 return 0;
1850}
1851
1852// This can't be done with ReplaceStmt(S, ThrowExpr), since
1853// the throw expression is typically a message expression that's already
1854// been rewritten! (which implies the SourceLocation's are invalid).
1855Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
1856 // Get the start location and compute the semi location.
1857 SourceLocation startLoc = S->getLocStart();
1858 const char *startBuf = SM->getCharacterData(startLoc);
1859
1860 assert((*startBuf == '@') && "bogus @throw location");
1861
1862 std::string buf;
1863 /* void objc_exception_throw(id) __attribute__((noreturn)); */
1864 if (S->getThrowExpr())
1865 buf = "objc_exception_throw(";
Fariborz Jahanian40539462012-03-16 16:52:06 +00001866 else
1867 buf = "throw";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001868
1869 // handle "@ throw" correctly.
1870 const char *wBuf = strchr(startBuf, 'w');
1871 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1872 ReplaceText(startLoc, wBuf-startBuf+1, buf);
1873
1874 const char *semiBuf = strchr(startBuf, ';');
1875 assert((*semiBuf == ';') && "@throw: can't find ';'");
1876 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian40539462012-03-16 16:52:06 +00001877 if (S->getThrowExpr())
1878 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001879 return 0;
1880}
1881
1882Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
1883 // Create a new string expression.
1884 QualType StrType = Context->getPointerType(Context->CharTy);
1885 std::string StrEncoding;
1886 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
1887 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
1888 StringLiteral::Ascii, false,
1889 StrType, SourceLocation());
1890 ReplaceStmt(Exp, Replacement);
1891
1892 // Replace this subexpr in the parent.
1893 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1894 return Replacement;
1895}
1896
1897Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1898 if (!SelGetUidFunctionDecl)
1899 SynthSelGetUidFunctionDecl();
1900 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1901 // Create a call to sel_registerName("selName").
1902 SmallVector<Expr*, 8> SelExprs;
1903 QualType argType = Context->getPointerType(Context->CharTy);
1904 SelExprs.push_back(StringLiteral::Create(*Context,
1905 Exp->getSelector().getAsString(),
1906 StringLiteral::Ascii, false,
1907 argType, SourceLocation()));
1908 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1909 &SelExprs[0], SelExprs.size());
1910 ReplaceStmt(Exp, SelExp);
1911 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1912 return SelExp;
1913}
1914
1915CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
1916 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
1917 SourceLocation EndLoc) {
1918 // Get the type, we will need to reference it in a couple spots.
1919 QualType msgSendType = FD->getType();
1920
1921 // Create a reference to the objc_msgSend() declaration.
1922 DeclRefExpr *DRE =
John McCallf4b88a42012-03-10 09:33:50 +00001923 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001924
1925 // Now, we cast the reference to a pointer to the objc_msgSend type.
1926 QualType pToFunc = Context->getPointerType(msgSendType);
1927 ImplicitCastExpr *ICE =
1928 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
1929 DRE, 0, VK_RValue);
1930
1931 const FunctionType *FT = msgSendType->getAs<FunctionType>();
1932
1933 CallExpr *Exp =
1934 new (Context) CallExpr(*Context, ICE, args, nargs,
1935 FT->getCallResultType(*Context),
1936 VK_RValue, EndLoc);
1937 return Exp;
1938}
1939
1940static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1941 const char *&startRef, const char *&endRef) {
1942 while (startBuf < endBuf) {
1943 if (*startBuf == '<')
1944 startRef = startBuf; // mark the start.
1945 if (*startBuf == '>') {
1946 if (startRef && *startRef == '<') {
1947 endRef = startBuf; // mark the end.
1948 return true;
1949 }
1950 return false;
1951 }
1952 startBuf++;
1953 }
1954 return false;
1955}
1956
1957static void scanToNextArgument(const char *&argRef) {
1958 int angle = 0;
1959 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1960 if (*argRef == '<')
1961 angle++;
1962 else if (*argRef == '>')
1963 angle--;
1964 argRef++;
1965 }
1966 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1967}
1968
1969bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
1970 if (T->isObjCQualifiedIdType())
1971 return true;
1972 if (const PointerType *PT = T->getAs<PointerType>()) {
1973 if (PT->getPointeeType()->isObjCQualifiedIdType())
1974 return true;
1975 }
1976 if (T->isObjCObjectPointerType()) {
1977 T = T->getPointeeType();
1978 return T->isObjCQualifiedInterfaceType();
1979 }
1980 if (T->isArrayType()) {
1981 QualType ElemTy = Context->getBaseElementType(T);
1982 return needToScanForQualifiers(ElemTy);
1983 }
1984 return false;
1985}
1986
1987void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1988 QualType Type = E->getType();
1989 if (needToScanForQualifiers(Type)) {
1990 SourceLocation Loc, EndLoc;
1991
1992 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1993 Loc = ECE->getLParenLoc();
1994 EndLoc = ECE->getRParenLoc();
1995 } else {
1996 Loc = E->getLocStart();
1997 EndLoc = E->getLocEnd();
1998 }
1999 // This will defend against trying to rewrite synthesized expressions.
2000 if (Loc.isInvalid() || EndLoc.isInvalid())
2001 return;
2002
2003 const char *startBuf = SM->getCharacterData(Loc);
2004 const char *endBuf = SM->getCharacterData(EndLoc);
2005 const char *startRef = 0, *endRef = 0;
2006 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2007 // Get the locations of the startRef, endRef.
2008 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2009 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2010 // Comment out the protocol references.
2011 InsertText(LessLoc, "/*");
2012 InsertText(GreaterLoc, "*/");
2013 }
2014 }
2015}
2016
2017void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2018 SourceLocation Loc;
2019 QualType Type;
2020 const FunctionProtoType *proto = 0;
2021 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2022 Loc = VD->getLocation();
2023 Type = VD->getType();
2024 }
2025 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2026 Loc = FD->getLocation();
2027 // Check for ObjC 'id' and class types that have been adorned with protocol
2028 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2029 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2030 assert(funcType && "missing function type");
2031 proto = dyn_cast<FunctionProtoType>(funcType);
2032 if (!proto)
2033 return;
2034 Type = proto->getResultType();
2035 }
2036 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2037 Loc = FD->getLocation();
2038 Type = FD->getType();
2039 }
2040 else
2041 return;
2042
2043 if (needToScanForQualifiers(Type)) {
2044 // Since types are unique, we need to scan the buffer.
2045
2046 const char *endBuf = SM->getCharacterData(Loc);
2047 const char *startBuf = endBuf;
2048 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2049 startBuf--; // scan backward (from the decl location) for return type.
2050 const char *startRef = 0, *endRef = 0;
2051 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2052 // Get the locations of the startRef, endRef.
2053 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2054 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2055 // Comment out the protocol references.
2056 InsertText(LessLoc, "/*");
2057 InsertText(GreaterLoc, "*/");
2058 }
2059 }
2060 if (!proto)
2061 return; // most likely, was a variable
2062 // Now check arguments.
2063 const char *startBuf = SM->getCharacterData(Loc);
2064 const char *startFuncBuf = startBuf;
2065 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2066 if (needToScanForQualifiers(proto->getArgType(i))) {
2067 // Since types are unique, we need to scan the buffer.
2068
2069 const char *endBuf = startBuf;
2070 // scan forward (from the decl location) for argument types.
2071 scanToNextArgument(endBuf);
2072 const char *startRef = 0, *endRef = 0;
2073 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2074 // Get the locations of the startRef, endRef.
2075 SourceLocation LessLoc =
2076 Loc.getLocWithOffset(startRef-startFuncBuf);
2077 SourceLocation GreaterLoc =
2078 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2079 // Comment out the protocol references.
2080 InsertText(LessLoc, "/*");
2081 InsertText(GreaterLoc, "*/");
2082 }
2083 startBuf = ++endBuf;
2084 }
2085 else {
2086 // If the function name is derived from a macro expansion, then the
2087 // argument buffer will not follow the name. Need to speak with Chris.
2088 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2089 startBuf++; // scan forward (from the decl location) for argument types.
2090 startBuf++;
2091 }
2092 }
2093}
2094
2095void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2096 QualType QT = ND->getType();
2097 const Type* TypePtr = QT->getAs<Type>();
2098 if (!isa<TypeOfExprType>(TypePtr))
2099 return;
2100 while (isa<TypeOfExprType>(TypePtr)) {
2101 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2102 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2103 TypePtr = QT->getAs<Type>();
2104 }
2105 // FIXME. This will not work for multiple declarators; as in:
2106 // __typeof__(a) b,c,d;
2107 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2108 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2109 const char *startBuf = SM->getCharacterData(DeclLoc);
2110 if (ND->getInit()) {
2111 std::string Name(ND->getNameAsString());
2112 TypeAsString += " " + Name + " = ";
2113 Expr *E = ND->getInit();
2114 SourceLocation startLoc;
2115 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2116 startLoc = ECE->getLParenLoc();
2117 else
2118 startLoc = E->getLocStart();
2119 startLoc = SM->getExpansionLoc(startLoc);
2120 const char *endBuf = SM->getCharacterData(startLoc);
2121 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2122 }
2123 else {
2124 SourceLocation X = ND->getLocEnd();
2125 X = SM->getExpansionLoc(X);
2126 const char *endBuf = SM->getCharacterData(X);
2127 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2128 }
2129}
2130
2131// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2132void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2133 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2134 SmallVector<QualType, 16> ArgTys;
2135 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2136 QualType getFuncType =
2137 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
2138 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2139 SourceLocation(),
2140 SourceLocation(),
2141 SelGetUidIdent, getFuncType, 0,
2142 SC_Extern,
2143 SC_None, false);
2144}
2145
2146void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2147 // declared in <objc/objc.h>
2148 if (FD->getIdentifier() &&
2149 FD->getName() == "sel_registerName") {
2150 SelGetUidFunctionDecl = FD;
2151 return;
2152 }
2153 RewriteObjCQualifiedInterfaceTypes(FD);
2154}
2155
2156void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2157 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2158 const char *argPtr = TypeString.c_str();
2159 if (!strchr(argPtr, '^')) {
2160 Str += TypeString;
2161 return;
2162 }
2163 while (*argPtr) {
2164 Str += (*argPtr == '^' ? '*' : *argPtr);
2165 argPtr++;
2166 }
2167}
2168
2169// FIXME. Consolidate this routine with RewriteBlockPointerType.
2170void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2171 ValueDecl *VD) {
2172 QualType Type = VD->getType();
2173 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2174 const char *argPtr = TypeString.c_str();
2175 int paren = 0;
2176 while (*argPtr) {
2177 switch (*argPtr) {
2178 case '(':
2179 Str += *argPtr;
2180 paren++;
2181 break;
2182 case ')':
2183 Str += *argPtr;
2184 paren--;
2185 break;
2186 case '^':
2187 Str += '*';
2188 if (paren == 1)
2189 Str += VD->getNameAsString();
2190 break;
2191 default:
2192 Str += *argPtr;
2193 break;
2194 }
2195 argPtr++;
2196 }
2197}
2198
2199
2200void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2201 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2202 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2203 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2204 if (!proto)
2205 return;
2206 QualType Type = proto->getResultType();
2207 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2208 FdStr += " ";
2209 FdStr += FD->getName();
2210 FdStr += "(";
2211 unsigned numArgs = proto->getNumArgs();
2212 for (unsigned i = 0; i < numArgs; i++) {
2213 QualType ArgType = proto->getArgType(i);
2214 RewriteBlockPointerType(FdStr, ArgType);
2215 if (i+1 < numArgs)
2216 FdStr += ", ";
2217 }
2218 FdStr += ");\n";
2219 InsertText(FunLocStart, FdStr);
2220 CurFunctionDeclToDeclareForBlock = 0;
2221}
2222
2223// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
2224void RewriteModernObjC::SynthSuperContructorFunctionDecl() {
2225 if (SuperContructorFunctionDecl)
2226 return;
2227 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2228 SmallVector<QualType, 16> ArgTys;
2229 QualType argT = Context->getObjCIdType();
2230 assert(!argT.isNull() && "Can't find 'id' type");
2231 ArgTys.push_back(argT);
2232 ArgTys.push_back(argT);
2233 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2234 &ArgTys[0], ArgTys.size());
2235 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2236 SourceLocation(),
2237 SourceLocation(),
2238 msgSendIdent, msgSendType, 0,
2239 SC_Extern,
2240 SC_None, false);
2241}
2242
2243// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2244void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2245 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2246 SmallVector<QualType, 16> ArgTys;
2247 QualType argT = Context->getObjCIdType();
2248 assert(!argT.isNull() && "Can't find 'id' type");
2249 ArgTys.push_back(argT);
2250 argT = Context->getObjCSelType();
2251 assert(!argT.isNull() && "Can't find 'SEL' type");
2252 ArgTys.push_back(argT);
2253 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2254 &ArgTys[0], ArgTys.size(),
2255 true /*isVariadic*/);
2256 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2257 SourceLocation(),
2258 SourceLocation(),
2259 msgSendIdent, msgSendType, 0,
2260 SC_Extern,
2261 SC_None, false);
2262}
2263
2264// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
2265void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2266 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2267 SmallVector<QualType, 16> ArgTys;
2268 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2269 SourceLocation(), SourceLocation(),
2270 &Context->Idents.get("objc_super"));
2271 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2272 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2273 ArgTys.push_back(argT);
2274 argT = Context->getObjCSelType();
2275 assert(!argT.isNull() && "Can't find 'SEL' type");
2276 ArgTys.push_back(argT);
2277 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2278 &ArgTys[0], ArgTys.size(),
2279 true /*isVariadic*/);
2280 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2281 SourceLocation(),
2282 SourceLocation(),
2283 msgSendIdent, msgSendType, 0,
2284 SC_Extern,
2285 SC_None, false);
2286}
2287
2288// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2289void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2290 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2291 SmallVector<QualType, 16> ArgTys;
2292 QualType argT = Context->getObjCIdType();
2293 assert(!argT.isNull() && "Can't find 'id' type");
2294 ArgTys.push_back(argT);
2295 argT = Context->getObjCSelType();
2296 assert(!argT.isNull() && "Can't find 'SEL' type");
2297 ArgTys.push_back(argT);
2298 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2299 &ArgTys[0], ArgTys.size(),
2300 true /*isVariadic*/);
2301 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2302 SourceLocation(),
2303 SourceLocation(),
2304 msgSendIdent, msgSendType, 0,
2305 SC_Extern,
2306 SC_None, false);
2307}
2308
2309// SynthMsgSendSuperStretFunctionDecl -
2310// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
2311void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2312 IdentifierInfo *msgSendIdent =
2313 &Context->Idents.get("objc_msgSendSuper_stret");
2314 SmallVector<QualType, 16> ArgTys;
2315 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2316 SourceLocation(), SourceLocation(),
2317 &Context->Idents.get("objc_super"));
2318 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2319 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2320 ArgTys.push_back(argT);
2321 argT = Context->getObjCSelType();
2322 assert(!argT.isNull() && "Can't find 'SEL' type");
2323 ArgTys.push_back(argT);
2324 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2325 &ArgTys[0], ArgTys.size(),
2326 true /*isVariadic*/);
2327 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2328 SourceLocation(),
2329 SourceLocation(),
2330 msgSendIdent, msgSendType, 0,
2331 SC_Extern,
2332 SC_None, false);
2333}
2334
2335// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2336void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2337 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2338 SmallVector<QualType, 16> ArgTys;
2339 QualType argT = Context->getObjCIdType();
2340 assert(!argT.isNull() && "Can't find 'id' type");
2341 ArgTys.push_back(argT);
2342 argT = Context->getObjCSelType();
2343 assert(!argT.isNull() && "Can't find 'SEL' type");
2344 ArgTys.push_back(argT);
2345 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2346 &ArgTys[0], ArgTys.size(),
2347 true /*isVariadic*/);
2348 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2349 SourceLocation(),
2350 SourceLocation(),
2351 msgSendIdent, msgSendType, 0,
2352 SC_Extern,
2353 SC_None, false);
2354}
2355
2356// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
2357void RewriteModernObjC::SynthGetClassFunctionDecl() {
2358 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2359 SmallVector<QualType, 16> ArgTys;
2360 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2361 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2362 &ArgTys[0], ArgTys.size());
2363 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2364 SourceLocation(),
2365 SourceLocation(),
2366 getClassIdent, getClassType, 0,
2367 SC_Extern,
2368 SC_None, false);
2369}
2370
2371// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2372void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2373 IdentifierInfo *getSuperClassIdent =
2374 &Context->Idents.get("class_getSuperclass");
2375 SmallVector<QualType, 16> ArgTys;
2376 ArgTys.push_back(Context->getObjCClassType());
2377 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2378 &ArgTys[0], ArgTys.size());
2379 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2380 SourceLocation(),
2381 SourceLocation(),
2382 getSuperClassIdent,
2383 getClassType, 0,
2384 SC_Extern,
2385 SC_None,
2386 false);
2387}
2388
2389// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
2390void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2391 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2392 SmallVector<QualType, 16> ArgTys;
2393 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2394 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2395 &ArgTys[0], ArgTys.size());
2396 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2397 SourceLocation(),
2398 SourceLocation(),
2399 getClassIdent, getClassType, 0,
2400 SC_Extern,
2401 SC_None, false);
2402}
2403
2404Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2405 QualType strType = getConstantStringStructType();
2406
2407 std::string S = "__NSConstantStringImpl_";
2408
2409 std::string tmpName = InFileName;
2410 unsigned i;
2411 for (i=0; i < tmpName.length(); i++) {
2412 char c = tmpName.at(i);
2413 // replace any non alphanumeric characters with '_'.
2414 if (!isalpha(c) && (c < '0' || c > '9'))
2415 tmpName[i] = '_';
2416 }
2417 S += tmpName;
2418 S += "_";
2419 S += utostr(NumObjCStringLiterals++);
2420
2421 Preamble += "static __NSConstantStringImpl " + S;
2422 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2423 Preamble += "0x000007c8,"; // utf8_str
2424 // The pretty printer for StringLiteral handles escape characters properly.
2425 std::string prettyBufS;
2426 llvm::raw_string_ostream prettyBuf(prettyBufS);
2427 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2428 PrintingPolicy(LangOpts));
2429 Preamble += prettyBuf.str();
2430 Preamble += ",";
2431 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2432
2433 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2434 SourceLocation(), &Context->Idents.get(S),
2435 strType, 0, SC_Static, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002436 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002437 SourceLocation());
2438 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2439 Context->getPointerType(DRE->getType()),
2440 VK_RValue, OK_Ordinary,
2441 SourceLocation());
2442 // cast to NSConstantString *
2443 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2444 CK_CPointerToObjCPointerCast, Unop);
2445 ReplaceStmt(Exp, cast);
2446 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2447 return cast;
2448}
2449
2450// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
2451QualType RewriteModernObjC::getSuperStructType() {
2452 if (!SuperStructDecl) {
2453 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2454 SourceLocation(), SourceLocation(),
2455 &Context->Idents.get("objc_super"));
2456 QualType FieldTypes[2];
2457
2458 // struct objc_object *receiver;
2459 FieldTypes[0] = Context->getObjCIdType();
2460 // struct objc_class *super;
2461 FieldTypes[1] = Context->getObjCClassType();
2462
2463 // Create fields
2464 for (unsigned i = 0; i < 2; ++i) {
2465 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2466 SourceLocation(),
2467 SourceLocation(), 0,
2468 FieldTypes[i], 0,
2469 /*BitWidth=*/0,
2470 /*Mutable=*/false,
2471 /*HasInit=*/false));
2472 }
2473
2474 SuperStructDecl->completeDefinition();
2475 }
2476 return Context->getTagDeclType(SuperStructDecl);
2477}
2478
2479QualType RewriteModernObjC::getConstantStringStructType() {
2480 if (!ConstantStringDecl) {
2481 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2482 SourceLocation(), SourceLocation(),
2483 &Context->Idents.get("__NSConstantStringImpl"));
2484 QualType FieldTypes[4];
2485
2486 // struct objc_object *receiver;
2487 FieldTypes[0] = Context->getObjCIdType();
2488 // int flags;
2489 FieldTypes[1] = Context->IntTy;
2490 // char *str;
2491 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2492 // long length;
2493 FieldTypes[3] = Context->LongTy;
2494
2495 // Create fields
2496 for (unsigned i = 0; i < 4; ++i) {
2497 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2498 ConstantStringDecl,
2499 SourceLocation(),
2500 SourceLocation(), 0,
2501 FieldTypes[i], 0,
2502 /*BitWidth=*/0,
2503 /*Mutable=*/true,
2504 /*HasInit=*/false));
2505 }
2506
2507 ConstantStringDecl->completeDefinition();
2508 }
2509 return Context->getTagDeclType(ConstantStringDecl);
2510}
2511
2512Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2513 SourceLocation StartLoc,
2514 SourceLocation EndLoc) {
2515 if (!SelGetUidFunctionDecl)
2516 SynthSelGetUidFunctionDecl();
2517 if (!MsgSendFunctionDecl)
2518 SynthMsgSendFunctionDecl();
2519 if (!MsgSendSuperFunctionDecl)
2520 SynthMsgSendSuperFunctionDecl();
2521 if (!MsgSendStretFunctionDecl)
2522 SynthMsgSendStretFunctionDecl();
2523 if (!MsgSendSuperStretFunctionDecl)
2524 SynthMsgSendSuperStretFunctionDecl();
2525 if (!MsgSendFpretFunctionDecl)
2526 SynthMsgSendFpretFunctionDecl();
2527 if (!GetClassFunctionDecl)
2528 SynthGetClassFunctionDecl();
2529 if (!GetSuperClassFunctionDecl)
2530 SynthGetSuperClassFunctionDecl();
2531 if (!GetMetaClassFunctionDecl)
2532 SynthGetMetaClassFunctionDecl();
2533
2534 // default to objc_msgSend().
2535 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2536 // May need to use objc_msgSend_stret() as well.
2537 FunctionDecl *MsgSendStretFlavor = 0;
2538 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2539 QualType resultType = mDecl->getResultType();
2540 if (resultType->isRecordType())
2541 MsgSendStretFlavor = MsgSendStretFunctionDecl;
2542 else if (resultType->isRealFloatingType())
2543 MsgSendFlavor = MsgSendFpretFunctionDecl;
2544 }
2545
2546 // Synthesize a call to objc_msgSend().
2547 SmallVector<Expr*, 8> MsgExprs;
2548 switch (Exp->getReceiverKind()) {
2549 case ObjCMessageExpr::SuperClass: {
2550 MsgSendFlavor = MsgSendSuperFunctionDecl;
2551 if (MsgSendStretFlavor)
2552 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2553 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2554
2555 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2556
2557 SmallVector<Expr*, 4> InitExprs;
2558
2559 // set the receiver to self, the first argument to all methods.
2560 InitExprs.push_back(
2561 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2562 CK_BitCast,
2563 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00002564 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002565 Context->getObjCIdType(),
2566 VK_RValue,
2567 SourceLocation()))
2568 ); // set the 'receiver'.
2569
2570 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2571 SmallVector<Expr*, 8> ClsExprs;
2572 QualType argType = Context->getPointerType(Context->CharTy);
2573 ClsExprs.push_back(StringLiteral::Create(*Context,
2574 ClassDecl->getIdentifier()->getName(),
2575 StringLiteral::Ascii, false,
2576 argType, SourceLocation()));
2577 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2578 &ClsExprs[0],
2579 ClsExprs.size(),
2580 StartLoc,
2581 EndLoc);
2582 // (Class)objc_getClass("CurrentClass")
2583 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2584 Context->getObjCClassType(),
2585 CK_BitCast, Cls);
2586 ClsExprs.clear();
2587 ClsExprs.push_back(ArgExpr);
2588 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2589 &ClsExprs[0], ClsExprs.size(),
2590 StartLoc, EndLoc);
2591
2592 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2593 // To turn off a warning, type-cast to 'id'
2594 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2595 NoTypeInfoCStyleCastExpr(Context,
2596 Context->getObjCIdType(),
2597 CK_BitCast, Cls));
2598 // struct objc_super
2599 QualType superType = getSuperStructType();
2600 Expr *SuperRep;
2601
2602 if (LangOpts.MicrosoftExt) {
2603 SynthSuperContructorFunctionDecl();
2604 // Simulate a contructor call...
2605 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00002606 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002607 SourceLocation());
2608 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2609 InitExprs.size(),
2610 superType, VK_LValue,
2611 SourceLocation());
2612 // The code for super is a little tricky to prevent collision with
2613 // the structure definition in the header. The rewriter has it's own
2614 // internal definition (__rw_objc_super) that is uses. This is why
2615 // we need the cast below. For example:
2616 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2617 //
2618 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2619 Context->getPointerType(SuperRep->getType()),
2620 VK_RValue, OK_Ordinary,
2621 SourceLocation());
2622 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2623 Context->getPointerType(superType),
2624 CK_BitCast, SuperRep);
2625 } else {
2626 // (struct objc_super) { <exprs from above> }
2627 InitListExpr *ILE =
2628 new (Context) InitListExpr(*Context, SourceLocation(),
2629 &InitExprs[0], InitExprs.size(),
2630 SourceLocation());
2631 TypeSourceInfo *superTInfo
2632 = Context->getTrivialTypeSourceInfo(superType);
2633 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2634 superType, VK_LValue,
2635 ILE, false);
2636 // struct objc_super *
2637 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2638 Context->getPointerType(SuperRep->getType()),
2639 VK_RValue, OK_Ordinary,
2640 SourceLocation());
2641 }
2642 MsgExprs.push_back(SuperRep);
2643 break;
2644 }
2645
2646 case ObjCMessageExpr::Class: {
2647 SmallVector<Expr*, 8> ClsExprs;
2648 QualType argType = Context->getPointerType(Context->CharTy);
2649 ObjCInterfaceDecl *Class
2650 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
2651 IdentifierInfo *clsName = Class->getIdentifier();
2652 ClsExprs.push_back(StringLiteral::Create(*Context,
2653 clsName->getName(),
2654 StringLiteral::Ascii, false,
2655 argType, SourceLocation()));
2656 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2657 &ClsExprs[0],
2658 ClsExprs.size(),
2659 StartLoc, EndLoc);
2660 MsgExprs.push_back(Cls);
2661 break;
2662 }
2663
2664 case ObjCMessageExpr::SuperInstance:{
2665 MsgSendFlavor = MsgSendSuperFunctionDecl;
2666 if (MsgSendStretFlavor)
2667 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2668 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2669 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2670 SmallVector<Expr*, 4> InitExprs;
2671
2672 InitExprs.push_back(
2673 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2674 CK_BitCast,
2675 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00002676 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002677 Context->getObjCIdType(),
2678 VK_RValue, SourceLocation()))
2679 ); // set the 'receiver'.
2680
2681 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2682 SmallVector<Expr*, 8> ClsExprs;
2683 QualType argType = Context->getPointerType(Context->CharTy);
2684 ClsExprs.push_back(StringLiteral::Create(*Context,
2685 ClassDecl->getIdentifier()->getName(),
2686 StringLiteral::Ascii, false, argType,
2687 SourceLocation()));
2688 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2689 &ClsExprs[0],
2690 ClsExprs.size(),
2691 StartLoc, EndLoc);
2692 // (Class)objc_getClass("CurrentClass")
2693 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2694 Context->getObjCClassType(),
2695 CK_BitCast, Cls);
2696 ClsExprs.clear();
2697 ClsExprs.push_back(ArgExpr);
2698 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2699 &ClsExprs[0], ClsExprs.size(),
2700 StartLoc, EndLoc);
2701
2702 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2703 // To turn off a warning, type-cast to 'id'
2704 InitExprs.push_back(
2705 // set 'super class', using class_getSuperclass().
2706 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2707 CK_BitCast, Cls));
2708 // struct objc_super
2709 QualType superType = getSuperStructType();
2710 Expr *SuperRep;
2711
2712 if (LangOpts.MicrosoftExt) {
2713 SynthSuperContructorFunctionDecl();
2714 // Simulate a contructor call...
2715 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00002716 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002717 SourceLocation());
2718 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2719 InitExprs.size(),
2720 superType, VK_LValue, SourceLocation());
2721 // The code for super is a little tricky to prevent collision with
2722 // the structure definition in the header. The rewriter has it's own
2723 // internal definition (__rw_objc_super) that is uses. This is why
2724 // we need the cast below. For example:
2725 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2726 //
2727 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2728 Context->getPointerType(SuperRep->getType()),
2729 VK_RValue, OK_Ordinary,
2730 SourceLocation());
2731 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2732 Context->getPointerType(superType),
2733 CK_BitCast, SuperRep);
2734 } else {
2735 // (struct objc_super) { <exprs from above> }
2736 InitListExpr *ILE =
2737 new (Context) InitListExpr(*Context, SourceLocation(),
2738 &InitExprs[0], InitExprs.size(),
2739 SourceLocation());
2740 TypeSourceInfo *superTInfo
2741 = Context->getTrivialTypeSourceInfo(superType);
2742 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2743 superType, VK_RValue, ILE,
2744 false);
2745 }
2746 MsgExprs.push_back(SuperRep);
2747 break;
2748 }
2749
2750 case ObjCMessageExpr::Instance: {
2751 // Remove all type-casts because it may contain objc-style types; e.g.
2752 // Foo<Proto> *.
2753 Expr *recExpr = Exp->getInstanceReceiver();
2754 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2755 recExpr = CE->getSubExpr();
2756 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
2757 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
2758 ? CK_BlockPointerToObjCPointerCast
2759 : CK_CPointerToObjCPointerCast;
2760
2761 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2762 CK, recExpr);
2763 MsgExprs.push_back(recExpr);
2764 break;
2765 }
2766 }
2767
2768 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
2769 SmallVector<Expr*, 8> SelExprs;
2770 QualType argType = Context->getPointerType(Context->CharTy);
2771 SelExprs.push_back(StringLiteral::Create(*Context,
2772 Exp->getSelector().getAsString(),
2773 StringLiteral::Ascii, false,
2774 argType, SourceLocation()));
2775 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2776 &SelExprs[0], SelExprs.size(),
2777 StartLoc,
2778 EndLoc);
2779 MsgExprs.push_back(SelExp);
2780
2781 // Now push any user supplied arguments.
2782 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
2783 Expr *userExpr = Exp->getArg(i);
2784 // Make all implicit casts explicit...ICE comes in handy:-)
2785 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2786 // Reuse the ICE type, it is exactly what the doctor ordered.
2787 QualType type = ICE->getType();
2788 if (needToScanForQualifiers(type))
2789 type = Context->getObjCIdType();
2790 // Make sure we convert "type (^)(...)" to "type (*)(...)".
2791 (void)convertBlockPointerToFunctionPointer(type);
2792 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2793 CastKind CK;
2794 if (SubExpr->getType()->isIntegralType(*Context) &&
2795 type->isBooleanType()) {
2796 CK = CK_IntegralToBoolean;
2797 } else if (type->isObjCObjectPointerType()) {
2798 if (SubExpr->getType()->isBlockPointerType()) {
2799 CK = CK_BlockPointerToObjCPointerCast;
2800 } else if (SubExpr->getType()->isPointerType()) {
2801 CK = CK_CPointerToObjCPointerCast;
2802 } else {
2803 CK = CK_BitCast;
2804 }
2805 } else {
2806 CK = CK_BitCast;
2807 }
2808
2809 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
2810 }
2811 // Make id<P...> cast into an 'id' cast.
2812 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
2813 if (CE->getType()->isObjCQualifiedIdType()) {
2814 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
2815 userExpr = CE->getSubExpr();
2816 CastKind CK;
2817 if (userExpr->getType()->isIntegralType(*Context)) {
2818 CK = CK_IntegralToPointer;
2819 } else if (userExpr->getType()->isBlockPointerType()) {
2820 CK = CK_BlockPointerToObjCPointerCast;
2821 } else if (userExpr->getType()->isPointerType()) {
2822 CK = CK_CPointerToObjCPointerCast;
2823 } else {
2824 CK = CK_BitCast;
2825 }
2826 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2827 CK, userExpr);
2828 }
2829 }
2830 MsgExprs.push_back(userExpr);
2831 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2832 // out the argument in the original expression (since we aren't deleting
2833 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
2834 //Exp->setArg(i, 0);
2835 }
2836 // Generate the funky cast.
2837 CastExpr *cast;
2838 SmallVector<QualType, 8> ArgTypes;
2839 QualType returnType;
2840
2841 // Push 'id' and 'SEL', the 2 implicit arguments.
2842 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2843 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2844 else
2845 ArgTypes.push_back(Context->getObjCIdType());
2846 ArgTypes.push_back(Context->getObjCSelType());
2847 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
2848 // Push any user argument types.
2849 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2850 E = OMD->param_end(); PI != E; ++PI) {
2851 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
2852 ? Context->getObjCIdType()
2853 : (*PI)->getType();
2854 // Make sure we convert "t (^)(...)" to "t (*)(...)".
2855 (void)convertBlockPointerToFunctionPointer(t);
2856 ArgTypes.push_back(t);
2857 }
2858 returnType = Exp->getType();
2859 convertToUnqualifiedObjCType(returnType);
2860 (void)convertBlockPointerToFunctionPointer(returnType);
2861 } else {
2862 returnType = Context->getObjCIdType();
2863 }
2864 // Get the type, we will need to reference it in a couple spots.
2865 QualType msgSendType = MsgSendFlavor->getType();
2866
2867 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00002868 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002869 VK_LValue, SourceLocation());
2870
2871 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2872 // If we don't do this cast, we get the following bizarre warning/note:
2873 // xx.m:13: warning: function called through a non-compatible type
2874 // xx.m:13: note: if this code is reached, the program will abort
2875 cast = NoTypeInfoCStyleCastExpr(Context,
2876 Context->getPointerType(Context->VoidTy),
2877 CK_BitCast, DRE);
2878
2879 // Now do the "normal" pointer to function cast.
2880 QualType castType =
2881 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2882 // If we don't have a method decl, force a variadic cast.
2883 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
2884 castType = Context->getPointerType(castType);
2885 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2886 cast);
2887
2888 // Don't forget the parens to enforce the proper binding.
2889 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2890
2891 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2892 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2893 MsgExprs.size(),
2894 FT->getResultType(), VK_RValue,
2895 EndLoc);
2896 Stmt *ReplacingStmt = CE;
2897 if (MsgSendStretFlavor) {
2898 // We have the method which returns a struct/union. Must also generate
2899 // call to objc_msgSend_stret and hang both varieties on a conditional
2900 // expression which dictate which one to envoke depending on size of
2901 // method's return type.
2902
2903 // Create a reference to the objc_msgSend_stret() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00002904 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
2905 false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002906 VK_LValue, SourceLocation());
2907 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2908 cast = NoTypeInfoCStyleCastExpr(Context,
2909 Context->getPointerType(Context->VoidTy),
2910 CK_BitCast, STDRE);
2911 // Now do the "normal" pointer to function cast.
2912 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2913 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
2914 castType = Context->getPointerType(castType);
2915 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2916 cast);
2917
2918 // Don't forget the parens to enforce the proper binding.
2919 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
2920
2921 FT = msgSendType->getAs<FunctionType>();
2922 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2923 MsgExprs.size(),
2924 FT->getResultType(), VK_RValue,
2925 SourceLocation());
2926
2927 // Build sizeof(returnType)
2928 UnaryExprOrTypeTraitExpr *sizeofExpr =
2929 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
2930 Context->getTrivialTypeSourceInfo(returnType),
2931 Context->getSizeType(), SourceLocation(),
2932 SourceLocation());
2933 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2934 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2935 // For X86 it is more complicated and some kind of target specific routine
2936 // is needed to decide what to do.
2937 unsigned IntSize =
2938 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2939 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
2940 llvm::APInt(IntSize, 8),
2941 Context->IntTy,
2942 SourceLocation());
2943 BinaryOperator *lessThanExpr =
2944 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
2945 VK_RValue, OK_Ordinary, SourceLocation());
2946 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2947 ConditionalOperator *CondExpr =
2948 new (Context) ConditionalOperator(lessThanExpr,
2949 SourceLocation(), CE,
2950 SourceLocation(), STCE,
2951 returnType, VK_RValue, OK_Ordinary);
2952 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
2953 CondExpr);
2954 }
2955 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2956 return ReplacingStmt;
2957}
2958
2959Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
2960 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
2961 Exp->getLocEnd());
2962
2963 // Now do the actual rewrite.
2964 ReplaceStmt(Exp, ReplacingStmt);
2965
2966 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2967 return ReplacingStmt;
2968}
2969
2970// typedef struct objc_object Protocol;
2971QualType RewriteModernObjC::getProtocolType() {
2972 if (!ProtocolTypeDecl) {
2973 TypeSourceInfo *TInfo
2974 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
2975 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
2976 SourceLocation(), SourceLocation(),
2977 &Context->Idents.get("Protocol"),
2978 TInfo);
2979 }
2980 return Context->getTypeDeclType(ProtocolTypeDecl);
2981}
2982
2983/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2984/// a synthesized/forward data reference (to the protocol's metadata).
2985/// The forward references (and metadata) are generated in
2986/// RewriteModernObjC::HandleTranslationUnit().
2987Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00002988 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
2989 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002990 IdentifierInfo *ID = &Context->Idents.get(Name);
2991 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2992 SourceLocation(), ID, getProtocolType(), 0,
2993 SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002994 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
2995 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002996 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
2997 Context->getPointerType(DRE->getType()),
2998 VK_RValue, OK_Ordinary, SourceLocation());
2999 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3000 CK_BitCast,
3001 DerefExpr);
3002 ReplaceStmt(Exp, castExpr);
3003 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3004 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3005 return castExpr;
3006
3007}
3008
3009bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3010 const char *endBuf) {
3011 while (startBuf < endBuf) {
3012 if (*startBuf == '#') {
3013 // Skip whitespace.
3014 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3015 ;
3016 if (!strncmp(startBuf, "if", strlen("if")) ||
3017 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3018 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3019 !strncmp(startBuf, "define", strlen("define")) ||
3020 !strncmp(startBuf, "undef", strlen("undef")) ||
3021 !strncmp(startBuf, "else", strlen("else")) ||
3022 !strncmp(startBuf, "elif", strlen("elif")) ||
3023 !strncmp(startBuf, "endif", strlen("endif")) ||
3024 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3025 !strncmp(startBuf, "include", strlen("include")) ||
3026 !strncmp(startBuf, "import", strlen("import")) ||
3027 !strncmp(startBuf, "include_next", strlen("include_next")))
3028 return true;
3029 }
3030 startBuf++;
3031 }
3032 return false;
3033}
3034
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003035/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003036/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003037bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3038 std::string &Result) {
3039 if (Type->isArrayType()) {
3040 QualType ElemTy = Context->getBaseElementType(Type);
3041 return RewriteObjCFieldDeclType(ElemTy, Result);
3042 }
3043 else if (Type->isRecordType()) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003044 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3045 if (RD->isCompleteDefinition()) {
3046 if (RD->isStruct())
3047 Result += "\n\tstruct ";
3048 else if (RD->isUnion())
3049 Result += "\n\tunion ";
3050 else
3051 assert(false && "class not allowed as an ivar type");
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003052
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003053 Result += RD->getName();
3054 if (TagsDefinedInIvarDecls.count(RD)) {
3055 // This struct is already defined. Do not write its definition again.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003056 Result += " ";
3057 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003058 }
3059 TagsDefinedInIvarDecls.insert(RD);
3060 Result += " {\n";
3061 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003062 e = RD->field_end(); i != e; ++i) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003063 FieldDecl *FD = *i;
3064 RewriteObjCFieldDecl(FD, Result);
3065 }
3066 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003067 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003068 }
3069 }
3070 else if (Type->isEnumeralType()) {
3071 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3072 if (ED->isCompleteDefinition()) {
3073 Result += "\n\tenum ";
3074 Result += ED->getName();
3075 if (TagsDefinedInIvarDecls.count(ED)) {
3076 // This enum is already defined. Do not write its definition again.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003077 Result += " ";
3078 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003079 }
3080 TagsDefinedInIvarDecls.insert(ED);
3081
3082 Result += " {\n";
3083 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3084 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3085 Result += "\t"; Result += EC->getName(); Result += " = ";
3086 llvm::APSInt Val = EC->getInitVal();
3087 Result += Val.toString(10);
3088 Result += ",\n";
3089 }
3090 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003091 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003092 }
3093 }
3094
3095 Result += "\t";
3096 convertObjCTypeToCStyleType(Type);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003097 return false;
3098}
3099
3100
3101/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3102/// It handles elaborated types, as well as enum types in the process.
3103void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3104 std::string &Result) {
3105 QualType Type = fieldDecl->getType();
3106 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003107
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003108 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3109 if (!EleboratedType)
3110 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003111 Result += Name;
3112 if (fieldDecl->isBitField()) {
3113 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3114 }
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003115 else if (EleboratedType && Type->isArrayType()) {
3116 CanQualType CType = Context->getCanonicalType(Type);
3117 while (isa<ArrayType>(CType)) {
3118 if (const ConstantArrayType *CAT = Context->getAsConstantArrayType(CType)) {
3119 Result += "[";
3120 llvm::APInt Dim = CAT->getSize();
3121 Result += utostr(Dim.getZExtValue());
3122 Result += "]";
3123 }
3124 CType = CType->getAs<ArrayType>()->getElementType();
3125 }
3126 }
3127
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003128 Result += ";\n";
3129}
3130
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003131/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3132/// an objective-c class with ivars.
3133void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3134 std::string &Result) {
3135 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3136 assert(CDecl->getName() != "" &&
3137 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003138 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003139 SmallVector<ObjCIvarDecl *, 8> IVars;
3140 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003141 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003142 IVars.push_back(IVD);
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003143
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003144 SourceLocation LocStart = CDecl->getLocStart();
3145 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003146
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003147 const char *startBuf = SM->getCharacterData(LocStart);
3148 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003149
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003150 // If no ivars and no root or if its root, directly or indirectly,
3151 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003152 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003153 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3154 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3155 ReplaceText(LocStart, endBuf-startBuf, Result);
3156 return;
3157 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003158
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003159 Result += "\nstruct ";
3160 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003161 Result += "_IMPL {\n";
3162
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003163 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003164 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3165 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3166 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003167 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003168 TagsDefinedInIvarDecls.clear();
3169 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3170 RewriteObjCFieldDecl(IVars[i], Result);
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00003171
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003172 Result += "};\n";
3173 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3174 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003175 // Mark this struct as having been generated.
3176 if (!ObjCSynthesizedStructs.insert(CDecl))
3177 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003178}
3179
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003180static void WriteInternalIvarName(ObjCInterfaceDecl *IDecl,
3181 ObjCIvarDecl *IvarDecl, std::string &Result) {
3182 Result += "OBJC_IVAR_$_";
3183 Result += IDecl->getName();
3184 Result += "$";
3185 Result += IvarDecl->getName();
3186}
3187
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003188/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3189/// have been referenced in an ivar access expression.
3190void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3191 std::string &Result) {
3192 // write out ivar offset symbols which have been referenced in an ivar
3193 // access expression.
3194 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3195 if (Ivars.empty())
3196 return;
3197 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
3198 e = Ivars.end(); i != e; i++) {
3199 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003200 Result += "\n";
3201 if (LangOpts.MicrosoftExt)
3202 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
3203 if (LangOpts.MicrosoftExt &&
3204 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
3205 IvarDecl->getAccessControl() != ObjCIvarDecl::Package) {
3206 const ObjCInterfaceDecl *CDecl = IvarDecl->getContainingInterface();
3207 if (CDecl->getImplementation())
3208 Result += "__declspec(dllexport) ";
3209 }
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003210 Result += "extern unsigned long ";
3211 WriteInternalIvarName(CDecl, IvarDecl, Result);
3212 Result += ";";
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003213 }
3214}
3215
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003216//===----------------------------------------------------------------------===//
3217// Meta Data Emission
3218//===----------------------------------------------------------------------===//
3219
3220
3221/// RewriteImplementations - This routine rewrites all method implementations
3222/// and emits meta-data.
3223
3224void RewriteModernObjC::RewriteImplementations() {
3225 int ClsDefCount = ClassImplementation.size();
3226 int CatDefCount = CategoryImplementation.size();
3227
3228 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003229 for (int i = 0; i < ClsDefCount; i++) {
3230 ObjCImplementationDecl *OIMP = ClassImplementation[i];
3231 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
3232 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00003233 assert(false &&
3234 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003235 RewriteImplementationDecl(OIMP);
3236 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003237
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003238 for (int i = 0; i < CatDefCount; i++) {
3239 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
3240 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
3241 if (CDecl->isImplicitInterfaceDecl())
3242 assert(false &&
3243 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003244 RewriteImplementationDecl(CIMP);
3245 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003246}
3247
3248void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
3249 const std::string &Name,
3250 ValueDecl *VD, bool def) {
3251 assert(BlockByRefDeclNo.count(VD) &&
3252 "RewriteByRefString: ByRef decl missing");
3253 if (def)
3254 ResultStr += "struct ";
3255 ResultStr += "__Block_byref_" + Name +
3256 "_" + utostr(BlockByRefDeclNo[VD]) ;
3257}
3258
3259static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3260 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3261 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3262 return false;
3263}
3264
3265std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3266 StringRef funcName,
3267 std::string Tag) {
3268 const FunctionType *AFT = CE->getFunctionType();
3269 QualType RT = AFT->getResultType();
3270 std::string StructRef = "struct " + Tag;
3271 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
3272 funcName.str() + "_" + "block_func_" + utostr(i);
3273
3274 BlockDecl *BD = CE->getBlockDecl();
3275
3276 if (isa<FunctionNoProtoType>(AFT)) {
3277 // No user-supplied arguments. Still need to pass in a pointer to the
3278 // block (to reference imported block decl refs).
3279 S += "(" + StructRef + " *__cself)";
3280 } else if (BD->param_empty()) {
3281 S += "(" + StructRef + " *__cself)";
3282 } else {
3283 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
3284 assert(FT && "SynthesizeBlockFunc: No function proto");
3285 S += '(';
3286 // first add the implicit argument.
3287 S += StructRef + " *__cself, ";
3288 std::string ParamStr;
3289 for (BlockDecl::param_iterator AI = BD->param_begin(),
3290 E = BD->param_end(); AI != E; ++AI) {
3291 if (AI != BD->param_begin()) S += ", ";
3292 ParamStr = (*AI)->getNameAsString();
3293 QualType QT = (*AI)->getType();
3294 if (convertBlockPointerToFunctionPointer(QT))
3295 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
3296 else
3297 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
3298 S += ParamStr;
3299 }
3300 if (FT->isVariadic()) {
3301 if (!BD->param_empty()) S += ", ";
3302 S += "...";
3303 }
3304 S += ')';
3305 }
3306 S += " {\n";
3307
3308 // Create local declarations to avoid rewriting all closure decl ref exprs.
3309 // First, emit a declaration for all "by ref" decls.
3310 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3311 E = BlockByRefDecls.end(); I != E; ++I) {
3312 S += " ";
3313 std::string Name = (*I)->getNameAsString();
3314 std::string TypeString;
3315 RewriteByRefString(TypeString, Name, (*I));
3316 TypeString += " *";
3317 Name = TypeString + Name;
3318 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
3319 }
3320 // Next, emit a declaration for all "by copy" declarations.
3321 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3322 E = BlockByCopyDecls.end(); I != E; ++I) {
3323 S += " ";
3324 // Handle nested closure invocation. For example:
3325 //
3326 // void (^myImportedClosure)(void);
3327 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3328 //
3329 // void (^anotherClosure)(void);
3330 // anotherClosure = ^(void) {
3331 // myImportedClosure(); // import and invoke the closure
3332 // };
3333 //
3334 if (isTopLevelBlockPointerType((*I)->getType())) {
3335 RewriteBlockPointerTypeVariable(S, (*I));
3336 S += " = (";
3337 RewriteBlockPointerType(S, (*I)->getType());
3338 S += ")";
3339 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3340 }
3341 else {
3342 std::string Name = (*I)->getNameAsString();
3343 QualType QT = (*I)->getType();
3344 if (HasLocalVariableExternalStorage(*I))
3345 QT = Context->getPointerType(QT);
3346 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
3347 S += Name + " = __cself->" +
3348 (*I)->getNameAsString() + "; // bound by copy\n";
3349 }
3350 }
3351 std::string RewrittenStr = RewrittenBlockExprs[CE];
3352 const char *cstr = RewrittenStr.c_str();
3353 while (*cstr++ != '{') ;
3354 S += cstr;
3355 S += "\n";
3356 return S;
3357}
3358
3359std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3360 StringRef funcName,
3361 std::string Tag) {
3362 std::string StructRef = "struct " + Tag;
3363 std::string S = "static void __";
3364
3365 S += funcName;
3366 S += "_block_copy_" + utostr(i);
3367 S += "(" + StructRef;
3368 S += "*dst, " + StructRef;
3369 S += "*src) {";
3370 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3371 E = ImportedBlockDecls.end(); I != E; ++I) {
3372 ValueDecl *VD = (*I);
3373 S += "_Block_object_assign((void*)&dst->";
3374 S += (*I)->getNameAsString();
3375 S += ", (void*)src->";
3376 S += (*I)->getNameAsString();
3377 if (BlockByRefDeclsPtrSet.count((*I)))
3378 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3379 else if (VD->getType()->isBlockPointerType())
3380 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3381 else
3382 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3383 }
3384 S += "}\n";
3385
3386 S += "\nstatic void __";
3387 S += funcName;
3388 S += "_block_dispose_" + utostr(i);
3389 S += "(" + StructRef;
3390 S += "*src) {";
3391 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3392 E = ImportedBlockDecls.end(); I != E; ++I) {
3393 ValueDecl *VD = (*I);
3394 S += "_Block_object_dispose((void*)src->";
3395 S += (*I)->getNameAsString();
3396 if (BlockByRefDeclsPtrSet.count((*I)))
3397 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3398 else if (VD->getType()->isBlockPointerType())
3399 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3400 else
3401 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3402 }
3403 S += "}\n";
3404 return S;
3405}
3406
3407std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3408 std::string Desc) {
3409 std::string S = "\nstruct " + Tag;
3410 std::string Constructor = " " + Tag;
3411
3412 S += " {\n struct __block_impl impl;\n";
3413 S += " struct " + Desc;
3414 S += "* Desc;\n";
3415
3416 Constructor += "(void *fp, "; // Invoke function pointer.
3417 Constructor += "struct " + Desc; // Descriptor pointer.
3418 Constructor += " *desc";
3419
3420 if (BlockDeclRefs.size()) {
3421 // Output all "by copy" declarations.
3422 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3423 E = BlockByCopyDecls.end(); I != E; ++I) {
3424 S += " ";
3425 std::string FieldName = (*I)->getNameAsString();
3426 std::string ArgName = "_" + FieldName;
3427 // Handle nested closure invocation. For example:
3428 //
3429 // void (^myImportedBlock)(void);
3430 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3431 //
3432 // void (^anotherBlock)(void);
3433 // anotherBlock = ^(void) {
3434 // myImportedBlock(); // import and invoke the closure
3435 // };
3436 //
3437 if (isTopLevelBlockPointerType((*I)->getType())) {
3438 S += "struct __block_impl *";
3439 Constructor += ", void *" + ArgName;
3440 } else {
3441 QualType QT = (*I)->getType();
3442 if (HasLocalVariableExternalStorage(*I))
3443 QT = Context->getPointerType(QT);
3444 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3445 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
3446 Constructor += ", " + ArgName;
3447 }
3448 S += FieldName + ";\n";
3449 }
3450 // Output all "by ref" declarations.
3451 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3452 E = BlockByRefDecls.end(); I != E; ++I) {
3453 S += " ";
3454 std::string FieldName = (*I)->getNameAsString();
3455 std::string ArgName = "_" + FieldName;
3456 {
3457 std::string TypeString;
3458 RewriteByRefString(TypeString, FieldName, (*I));
3459 TypeString += " *";
3460 FieldName = TypeString + FieldName;
3461 ArgName = TypeString + ArgName;
3462 Constructor += ", " + ArgName;
3463 }
3464 S += FieldName + "; // by ref\n";
3465 }
3466 // Finish writing the constructor.
3467 Constructor += ", int flags=0)";
3468 // Initialize all "by copy" arguments.
3469 bool firsTime = true;
3470 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3471 E = BlockByCopyDecls.end(); I != E; ++I) {
3472 std::string Name = (*I)->getNameAsString();
3473 if (firsTime) {
3474 Constructor += " : ";
3475 firsTime = false;
3476 }
3477 else
3478 Constructor += ", ";
3479 if (isTopLevelBlockPointerType((*I)->getType()))
3480 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3481 else
3482 Constructor += Name + "(_" + Name + ")";
3483 }
3484 // Initialize all "by ref" arguments.
3485 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3486 E = BlockByRefDecls.end(); I != E; ++I) {
3487 std::string Name = (*I)->getNameAsString();
3488 if (firsTime) {
3489 Constructor += " : ";
3490 firsTime = false;
3491 }
3492 else
3493 Constructor += ", ";
3494 Constructor += Name + "(_" + Name + "->__forwarding)";
3495 }
3496
3497 Constructor += " {\n";
3498 if (GlobalVarDecl)
3499 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3500 else
3501 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3502 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3503
3504 Constructor += " Desc = desc;\n";
3505 } else {
3506 // Finish writing the constructor.
3507 Constructor += ", int flags=0) {\n";
3508 if (GlobalVarDecl)
3509 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3510 else
3511 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3512 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3513 Constructor += " Desc = desc;\n";
3514 }
3515 Constructor += " ";
3516 Constructor += "}\n";
3517 S += Constructor;
3518 S += "};\n";
3519 return S;
3520}
3521
3522std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
3523 std::string ImplTag, int i,
3524 StringRef FunName,
3525 unsigned hasCopy) {
3526 std::string S = "\nstatic struct " + DescTag;
3527
3528 S += " {\n unsigned long reserved;\n";
3529 S += " unsigned long Block_size;\n";
3530 if (hasCopy) {
3531 S += " void (*copy)(struct ";
3532 S += ImplTag; S += "*, struct ";
3533 S += ImplTag; S += "*);\n";
3534
3535 S += " void (*dispose)(struct ";
3536 S += ImplTag; S += "*);\n";
3537 }
3538 S += "} ";
3539
3540 S += DescTag + "_DATA = { 0, sizeof(struct ";
3541 S += ImplTag + ")";
3542 if (hasCopy) {
3543 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3544 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
3545 }
3546 S += "};\n";
3547 return S;
3548}
3549
3550void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3551 StringRef FunName) {
3552 // Insert declaration for the function in which block literal is used.
3553 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
3554 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
3555 bool RewriteSC = (GlobalVarDecl &&
3556 !Blocks.empty() &&
3557 GlobalVarDecl->getStorageClass() == SC_Static &&
3558 GlobalVarDecl->getType().getCVRQualifiers());
3559 if (RewriteSC) {
3560 std::string SC(" void __");
3561 SC += GlobalVarDecl->getNameAsString();
3562 SC += "() {}";
3563 InsertText(FunLocStart, SC);
3564 }
3565
3566 // Insert closures that were part of the function.
3567 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3568 CollectBlockDeclRefInfo(Blocks[i]);
3569 // Need to copy-in the inner copied-in variables not actually used in this
3570 // block.
3571 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00003572 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003573 ValueDecl *VD = Exp->getDecl();
3574 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00003575 if (!VD->hasAttr<BlocksAttr>()) {
3576 if (!BlockByCopyDeclsPtrSet.count(VD)) {
3577 BlockByCopyDeclsPtrSet.insert(VD);
3578 BlockByCopyDecls.push_back(VD);
3579 }
3580 continue;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003581 }
John McCallf4b88a42012-03-10 09:33:50 +00003582
3583 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003584 BlockByRefDeclsPtrSet.insert(VD);
3585 BlockByRefDecls.push_back(VD);
3586 }
John McCallf4b88a42012-03-10 09:33:50 +00003587
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003588 // imported objects in the inner blocks not used in the outer
3589 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00003590 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003591 VD->getType()->isBlockPointerType())
3592 ImportedBlockDecls.insert(VD);
3593 }
3594
3595 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3596 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
3597
3598 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
3599
3600 InsertText(FunLocStart, CI);
3601
3602 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
3603
3604 InsertText(FunLocStart, CF);
3605
3606 if (ImportedBlockDecls.size()) {
3607 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
3608 InsertText(FunLocStart, HF);
3609 }
3610 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3611 ImportedBlockDecls.size() > 0);
3612 InsertText(FunLocStart, BD);
3613
3614 BlockDeclRefs.clear();
3615 BlockByRefDecls.clear();
3616 BlockByRefDeclsPtrSet.clear();
3617 BlockByCopyDecls.clear();
3618 BlockByCopyDeclsPtrSet.clear();
3619 ImportedBlockDecls.clear();
3620 }
3621 if (RewriteSC) {
3622 // Must insert any 'const/volatile/static here. Since it has been
3623 // removed as result of rewriting of block literals.
3624 std::string SC;
3625 if (GlobalVarDecl->getStorageClass() == SC_Static)
3626 SC = "static ";
3627 if (GlobalVarDecl->getType().isConstQualified())
3628 SC += "const ";
3629 if (GlobalVarDecl->getType().isVolatileQualified())
3630 SC += "volatile ";
3631 if (GlobalVarDecl->getType().isRestrictQualified())
3632 SC += "restrict ";
3633 InsertText(FunLocStart, SC);
3634 }
3635
3636 Blocks.clear();
3637 InnerDeclRefsCount.clear();
3638 InnerDeclRefs.clear();
3639 RewrittenBlockExprs.clear();
3640}
3641
3642void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3643 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
3644 StringRef FuncName = FD->getName();
3645
3646 SynthesizeBlockLiterals(FunLocStart, FuncName);
3647}
3648
3649static void BuildUniqueMethodName(std::string &Name,
3650 ObjCMethodDecl *MD) {
3651 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3652 Name = IFace->getName();
3653 Name += "__" + MD->getSelector().getAsString();
3654 // Convert colons to underscores.
3655 std::string::size_type loc = 0;
3656 while ((loc = Name.find(":", loc)) != std::string::npos)
3657 Name.replace(loc, 1, "_");
3658}
3659
3660void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
3661 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3662 //SourceLocation FunLocStart = MD->getLocStart();
3663 SourceLocation FunLocStart = MD->getLocStart();
3664 std::string FuncName;
3665 BuildUniqueMethodName(FuncName, MD);
3666 SynthesizeBlockLiterals(FunLocStart, FuncName);
3667}
3668
3669void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
3670 for (Stmt::child_range CI = S->children(); CI; ++CI)
3671 if (*CI) {
3672 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3673 GetBlockDeclRefExprs(CBE->getBody());
3674 else
3675 GetBlockDeclRefExprs(*CI);
3676 }
3677 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00003678 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
3679 if (DRE->refersToEnclosingLocal() &&
3680 HasLocalVariableExternalStorage(DRE->getDecl())) {
3681 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003682 }
3683
3684 return;
3685}
3686
3687void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +00003688 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003689 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
3690 for (Stmt::child_range CI = S->children(); CI; ++CI)
3691 if (*CI) {
3692 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
3693 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
3694 GetInnerBlockDeclRefExprs(CBE->getBody(),
3695 InnerBlockDeclRefs,
3696 InnerContexts);
3697 }
3698 else
3699 GetInnerBlockDeclRefExprs(*CI,
3700 InnerBlockDeclRefs,
3701 InnerContexts);
3702
3703 }
3704 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00003705 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3706 if (DRE->refersToEnclosingLocal()) {
3707 if (!isa<FunctionDecl>(DRE->getDecl()) &&
3708 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
3709 InnerBlockDeclRefs.push_back(DRE);
3710 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
3711 if (Var->isFunctionOrMethodVarDecl())
3712 ImportedLocalExternalDecls.insert(Var);
3713 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003714 }
3715
3716 return;
3717}
3718
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003719/// convertObjCTypeToCStyleType - This routine converts such objc types
3720/// as qualified objects, and blocks to their closest c/c++ types that
3721/// it can. It returns true if input type was modified.
3722bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
3723 QualType oldT = T;
3724 convertBlockPointerToFunctionPointer(T);
3725 if (T->isFunctionPointerType()) {
3726 QualType PointeeTy;
3727 if (const PointerType* PT = T->getAs<PointerType>()) {
3728 PointeeTy = PT->getPointeeType();
3729 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
3730 T = convertFunctionTypeOfBlocks(FT);
3731 T = Context->getPointerType(T);
3732 }
3733 }
3734 }
3735
3736 convertToUnqualifiedObjCType(T);
3737 return T != oldT;
3738}
3739
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003740/// convertFunctionTypeOfBlocks - This routine converts a function type
3741/// whose result type may be a block pointer or whose argument type(s)
3742/// might be block pointers to an equivalent function type replacing
3743/// all block pointers to function pointers.
3744QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3745 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3746 // FTP will be null for closures that don't take arguments.
3747 // Generate a funky cast.
3748 SmallVector<QualType, 8> ArgTypes;
3749 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003750 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003751
3752 if (FTP) {
3753 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3754 E = FTP->arg_type_end(); I && (I != E); ++I) {
3755 QualType t = *I;
3756 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003757 if (convertObjCTypeToCStyleType(t))
3758 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003759 ArgTypes.push_back(t);
3760 }
3761 }
3762 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003763 if (modified)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003764 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
3765 else FuncType = QualType(FT, 0);
3766 return FuncType;
3767}
3768
3769Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
3770 // Navigate to relevant type information.
3771 const BlockPointerType *CPT = 0;
3772
3773 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
3774 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003775 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
3776 CPT = MExpr->getType()->getAs<BlockPointerType>();
3777 }
3778 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3779 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3780 }
3781 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3782 CPT = IEXPR->getType()->getAs<BlockPointerType>();
3783 else if (const ConditionalOperator *CEXPR =
3784 dyn_cast<ConditionalOperator>(BlockExp)) {
3785 Expr *LHSExp = CEXPR->getLHS();
3786 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3787 Expr *RHSExp = CEXPR->getRHS();
3788 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3789 Expr *CONDExp = CEXPR->getCond();
3790 ConditionalOperator *CondExpr =
3791 new (Context) ConditionalOperator(CONDExp,
3792 SourceLocation(), cast<Expr>(LHSStmt),
3793 SourceLocation(), cast<Expr>(RHSStmt),
3794 Exp->getType(), VK_RValue, OK_Ordinary);
3795 return CondExpr;
3796 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3797 CPT = IRE->getType()->getAs<BlockPointerType>();
3798 } else if (const PseudoObjectExpr *POE
3799 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3800 CPT = POE->getType()->castAs<BlockPointerType>();
3801 } else {
3802 assert(1 && "RewriteBlockClass: Bad type");
3803 }
3804 assert(CPT && "RewriteBlockClass: Bad type");
3805 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
3806 assert(FT && "RewriteBlockClass: Bad type");
3807 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3808 // FTP will be null for closures that don't take arguments.
3809
3810 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3811 SourceLocation(), SourceLocation(),
3812 &Context->Idents.get("__block_impl"));
3813 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
3814
3815 // Generate a funky cast.
3816 SmallVector<QualType, 8> ArgTypes;
3817
3818 // Push the block argument type.
3819 ArgTypes.push_back(PtrBlock);
3820 if (FTP) {
3821 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3822 E = FTP->arg_type_end(); I && (I != E); ++I) {
3823 QualType t = *I;
3824 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3825 if (!convertBlockPointerToFunctionPointer(t))
3826 convertToUnqualifiedObjCType(t);
3827 ArgTypes.push_back(t);
3828 }
3829 }
3830 // Now do the pointer to function cast.
3831 QualType PtrToFuncCastType
3832 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
3833
3834 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
3835
3836 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
3837 CK_BitCast,
3838 const_cast<Expr*>(BlockExp));
3839 // Don't forget the parens to enforce the proper binding.
3840 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3841 BlkCast);
3842 //PE->dump();
3843
3844 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3845 SourceLocation(),
3846 &Context->Idents.get("FuncPtr"),
3847 Context->VoidPtrTy, 0,
3848 /*BitWidth=*/0, /*Mutable=*/true,
3849 /*HasInit=*/false);
3850 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
3851 FD->getType(), VK_LValue,
3852 OK_Ordinary);
3853
3854
3855 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
3856 CK_BitCast, ME);
3857 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3858
3859 SmallVector<Expr*, 8> BlkExprs;
3860 // Add the implicit argument.
3861 BlkExprs.push_back(BlkCast);
3862 // Add the user arguments.
3863 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3864 E = Exp->arg_end(); I != E; ++I) {
3865 BlkExprs.push_back(*I);
3866 }
3867 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
3868 BlkExprs.size(),
3869 Exp->getType(), VK_RValue,
3870 SourceLocation());
3871 return CE;
3872}
3873
3874// We need to return the rewritten expression to handle cases where the
John McCallf4b88a42012-03-10 09:33:50 +00003875// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003876// For example:
3877//
3878// int main() {
3879// __block Foo *f;
3880// __block int i;
3881//
3882// void (^myblock)() = ^() {
John McCallf4b88a42012-03-10 09:33:50 +00003883// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003884// i = 77;
3885// };
3886//}
John McCallf4b88a42012-03-10 09:33:50 +00003887Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003888 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
3889 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00003890 ValueDecl *VD = DeclRefExp->getDecl();
3891 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003892
3893 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3894 SourceLocation(),
3895 &Context->Idents.get("__forwarding"),
3896 Context->VoidPtrTy, 0,
3897 /*BitWidth=*/0, /*Mutable=*/true,
3898 /*HasInit=*/false);
3899 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
3900 FD, SourceLocation(),
3901 FD->getType(), VK_LValue,
3902 OK_Ordinary);
3903
3904 StringRef Name = VD->getName();
3905 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
3906 &Context->Idents.get(Name),
3907 Context->VoidPtrTy, 0,
3908 /*BitWidth=*/0, /*Mutable=*/true,
3909 /*HasInit=*/false);
3910 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
3911 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
3912
3913
3914
3915 // Need parens to enforce precedence.
3916 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
3917 DeclRefExp->getExprLoc(),
3918 ME);
3919 ReplaceStmt(DeclRefExp, PE);
3920 return PE;
3921}
3922
3923// Rewrites the imported local variable V with external storage
3924// (static, extern, etc.) as *V
3925//
3926Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
3927 ValueDecl *VD = DRE->getDecl();
3928 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3929 if (!ImportedLocalExternalDecls.count(Var))
3930 return DRE;
3931 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
3932 VK_LValue, OK_Ordinary,
3933 DRE->getLocation());
3934 // Need parens to enforce precedence.
3935 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3936 Exp);
3937 ReplaceStmt(DRE, PE);
3938 return PE;
3939}
3940
3941void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3942 SourceLocation LocStart = CE->getLParenLoc();
3943 SourceLocation LocEnd = CE->getRParenLoc();
3944
3945 // Need to avoid trying to rewrite synthesized casts.
3946 if (LocStart.isInvalid())
3947 return;
3948 // Need to avoid trying to rewrite casts contained in macros.
3949 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3950 return;
3951
3952 const char *startBuf = SM->getCharacterData(LocStart);
3953 const char *endBuf = SM->getCharacterData(LocEnd);
3954 QualType QT = CE->getType();
3955 const Type* TypePtr = QT->getAs<Type>();
3956 if (isa<TypeOfExprType>(TypePtr)) {
3957 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
3958 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
3959 std::string TypeAsString = "(";
3960 RewriteBlockPointerType(TypeAsString, QT);
3961 TypeAsString += ")";
3962 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
3963 return;
3964 }
3965 // advance the location to startArgList.
3966 const char *argPtr = startBuf;
3967
3968 while (*argPtr++ && (argPtr < endBuf)) {
3969 switch (*argPtr) {
3970 case '^':
3971 // Replace the '^' with '*'.
3972 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
3973 ReplaceText(LocStart, 1, "*");
3974 break;
3975 }
3976 }
3977 return;
3978}
3979
3980void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3981 SourceLocation DeclLoc = FD->getLocation();
3982 unsigned parenCount = 0;
3983
3984 // We have 1 or more arguments that have closure pointers.
3985 const char *startBuf = SM->getCharacterData(DeclLoc);
3986 const char *startArgList = strchr(startBuf, '(');
3987
3988 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3989
3990 parenCount++;
3991 // advance the location to startArgList.
3992 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
3993 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3994
3995 const char *argPtr = startArgList;
3996
3997 while (*argPtr++ && parenCount) {
3998 switch (*argPtr) {
3999 case '^':
4000 // Replace the '^' with '*'.
4001 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4002 ReplaceText(DeclLoc, 1, "*");
4003 break;
4004 case '(':
4005 parenCount++;
4006 break;
4007 case ')':
4008 parenCount--;
4009 break;
4010 }
4011 }
4012 return;
4013}
4014
4015bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4016 const FunctionProtoType *FTP;
4017 const PointerType *PT = QT->getAs<PointerType>();
4018 if (PT) {
4019 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4020 } else {
4021 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4022 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4023 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4024 }
4025 if (FTP) {
4026 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4027 E = FTP->arg_type_end(); I != E; ++I)
4028 if (isTopLevelBlockPointerType(*I))
4029 return true;
4030 }
4031 return false;
4032}
4033
4034bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4035 const FunctionProtoType *FTP;
4036 const PointerType *PT = QT->getAs<PointerType>();
4037 if (PT) {
4038 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4039 } else {
4040 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4041 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4042 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4043 }
4044 if (FTP) {
4045 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4046 E = FTP->arg_type_end(); I != E; ++I) {
4047 if ((*I)->isObjCQualifiedIdType())
4048 return true;
4049 if ((*I)->isObjCObjectPointerType() &&
4050 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4051 return true;
4052 }
4053
4054 }
4055 return false;
4056}
4057
4058void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4059 const char *&RParen) {
4060 const char *argPtr = strchr(Name, '(');
4061 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4062
4063 LParen = argPtr; // output the start.
4064 argPtr++; // skip past the left paren.
4065 unsigned parenCount = 1;
4066
4067 while (*argPtr && parenCount) {
4068 switch (*argPtr) {
4069 case '(': parenCount++; break;
4070 case ')': parenCount--; break;
4071 default: break;
4072 }
4073 if (parenCount) argPtr++;
4074 }
4075 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4076 RParen = argPtr; // output the end
4077}
4078
4079void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4080 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4081 RewriteBlockPointerFunctionArgs(FD);
4082 return;
4083 }
4084 // Handle Variables and Typedefs.
4085 SourceLocation DeclLoc = ND->getLocation();
4086 QualType DeclT;
4087 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4088 DeclT = VD->getType();
4089 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4090 DeclT = TDD->getUnderlyingType();
4091 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4092 DeclT = FD->getType();
4093 else
4094 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4095
4096 const char *startBuf = SM->getCharacterData(DeclLoc);
4097 const char *endBuf = startBuf;
4098 // scan backward (from the decl location) for the end of the previous decl.
4099 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4100 startBuf--;
4101 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4102 std::string buf;
4103 unsigned OrigLength=0;
4104 // *startBuf != '^' if we are dealing with a pointer to function that
4105 // may take block argument types (which will be handled below).
4106 if (*startBuf == '^') {
4107 // Replace the '^' with '*', computing a negative offset.
4108 buf = '*';
4109 startBuf++;
4110 OrigLength++;
4111 }
4112 while (*startBuf != ')') {
4113 buf += *startBuf;
4114 startBuf++;
4115 OrigLength++;
4116 }
4117 buf += ')';
4118 OrigLength++;
4119
4120 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4121 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4122 // Replace the '^' with '*' for arguments.
4123 // Replace id<P> with id/*<>*/
4124 DeclLoc = ND->getLocation();
4125 startBuf = SM->getCharacterData(DeclLoc);
4126 const char *argListBegin, *argListEnd;
4127 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4128 while (argListBegin < argListEnd) {
4129 if (*argListBegin == '^')
4130 buf += '*';
4131 else if (*argListBegin == '<') {
4132 buf += "/*";
4133 buf += *argListBegin++;
4134 OrigLength++;;
4135 while (*argListBegin != '>') {
4136 buf += *argListBegin++;
4137 OrigLength++;
4138 }
4139 buf += *argListBegin;
4140 buf += "*/";
4141 }
4142 else
4143 buf += *argListBegin;
4144 argListBegin++;
4145 OrigLength++;
4146 }
4147 buf += ')';
4148 OrigLength++;
4149 }
4150 ReplaceText(Start, OrigLength, buf);
4151
4152 return;
4153}
4154
4155
4156/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4157/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4158/// struct Block_byref_id_object *src) {
4159/// _Block_object_assign (&_dest->object, _src->object,
4160/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4161/// [|BLOCK_FIELD_IS_WEAK]) // object
4162/// _Block_object_assign(&_dest->object, _src->object,
4163/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4164/// [|BLOCK_FIELD_IS_WEAK]) // block
4165/// }
4166/// And:
4167/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4168/// _Block_object_dispose(_src->object,
4169/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4170/// [|BLOCK_FIELD_IS_WEAK]) // object
4171/// _Block_object_dispose(_src->object,
4172/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4173/// [|BLOCK_FIELD_IS_WEAK]) // block
4174/// }
4175
4176std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4177 int flag) {
4178 std::string S;
4179 if (CopyDestroyCache.count(flag))
4180 return S;
4181 CopyDestroyCache.insert(flag);
4182 S = "static void __Block_byref_id_object_copy_";
4183 S += utostr(flag);
4184 S += "(void *dst, void *src) {\n";
4185
4186 // offset into the object pointer is computed as:
4187 // void * + void* + int + int + void* + void *
4188 unsigned IntSize =
4189 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4190 unsigned VoidPtrSize =
4191 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4192
4193 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4194 S += " _Block_object_assign((char*)dst + ";
4195 S += utostr(offset);
4196 S += ", *(void * *) ((char*)src + ";
4197 S += utostr(offset);
4198 S += "), ";
4199 S += utostr(flag);
4200 S += ");\n}\n";
4201
4202 S += "static void __Block_byref_id_object_dispose_";
4203 S += utostr(flag);
4204 S += "(void *src) {\n";
4205 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4206 S += utostr(offset);
4207 S += "), ";
4208 S += utostr(flag);
4209 S += ");\n}\n";
4210 return S;
4211}
4212
4213/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4214/// the declaration into:
4215/// struct __Block_byref_ND {
4216/// void *__isa; // NULL for everything except __weak pointers
4217/// struct __Block_byref_ND *__forwarding;
4218/// int32_t __flags;
4219/// int32_t __size;
4220/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4221/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4222/// typex ND;
4223/// };
4224///
4225/// It then replaces declaration of ND variable with:
4226/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4227/// __size=sizeof(struct __Block_byref_ND),
4228/// ND=initializer-if-any};
4229///
4230///
4231void RewriteModernObjC::RewriteByRefVar(VarDecl *ND) {
4232 // Insert declaration for the function in which block literal is
4233 // used.
4234 if (CurFunctionDeclToDeclareForBlock)
4235 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
4236 int flag = 0;
4237 int isa = 0;
4238 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4239 if (DeclLoc.isInvalid())
4240 // If type location is missing, it is because of missing type (a warning).
4241 // Use variable's location which is good for this case.
4242 DeclLoc = ND->getLocation();
4243 const char *startBuf = SM->getCharacterData(DeclLoc);
4244 SourceLocation X = ND->getLocEnd();
4245 X = SM->getExpansionLoc(X);
4246 const char *endBuf = SM->getCharacterData(X);
4247 std::string Name(ND->getNameAsString());
4248 std::string ByrefType;
4249 RewriteByRefString(ByrefType, Name, ND, true);
4250 ByrefType += " {\n";
4251 ByrefType += " void *__isa;\n";
4252 RewriteByRefString(ByrefType, Name, ND);
4253 ByrefType += " *__forwarding;\n";
4254 ByrefType += " int __flags;\n";
4255 ByrefType += " int __size;\n";
4256 // Add void *__Block_byref_id_object_copy;
4257 // void *__Block_byref_id_object_dispose; if needed.
4258 QualType Ty = ND->getType();
4259 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4260 if (HasCopyAndDispose) {
4261 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4262 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4263 }
4264
4265 QualType T = Ty;
4266 (void)convertBlockPointerToFunctionPointer(T);
4267 T.getAsStringInternal(Name, Context->getPrintingPolicy());
4268
4269 ByrefType += " " + Name + ";\n";
4270 ByrefType += "};\n";
4271 // Insert this type in global scope. It is needed by helper function.
4272 SourceLocation FunLocStart;
4273 if (CurFunctionDef)
4274 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4275 else {
4276 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4277 FunLocStart = CurMethodDef->getLocStart();
4278 }
4279 InsertText(FunLocStart, ByrefType);
4280 if (Ty.isObjCGCWeak()) {
4281 flag |= BLOCK_FIELD_IS_WEAK;
4282 isa = 1;
4283 }
4284
4285 if (HasCopyAndDispose) {
4286 flag = BLOCK_BYREF_CALLER;
4287 QualType Ty = ND->getType();
4288 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4289 if (Ty->isBlockPointerType())
4290 flag |= BLOCK_FIELD_IS_BLOCK;
4291 else
4292 flag |= BLOCK_FIELD_IS_OBJECT;
4293 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
4294 if (!HF.empty())
4295 InsertText(FunLocStart, HF);
4296 }
4297
4298 // struct __Block_byref_ND ND =
4299 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4300 // initializer-if-any};
4301 bool hasInit = (ND->getInit() != 0);
4302 unsigned flags = 0;
4303 if (HasCopyAndDispose)
4304 flags |= BLOCK_HAS_COPY_DISPOSE;
4305 Name = ND->getNameAsString();
4306 ByrefType.clear();
4307 RewriteByRefString(ByrefType, Name, ND);
4308 std::string ForwardingCastType("(");
4309 ForwardingCastType += ByrefType + " *)";
4310 if (!hasInit) {
4311 ByrefType += " " + Name + " = {(void*)";
4312 ByrefType += utostr(isa);
4313 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4314 ByrefType += utostr(flags);
4315 ByrefType += ", ";
4316 ByrefType += "sizeof(";
4317 RewriteByRefString(ByrefType, Name, ND);
4318 ByrefType += ")";
4319 if (HasCopyAndDispose) {
4320 ByrefType += ", __Block_byref_id_object_copy_";
4321 ByrefType += utostr(flag);
4322 ByrefType += ", __Block_byref_id_object_dispose_";
4323 ByrefType += utostr(flag);
4324 }
4325 ByrefType += "};\n";
4326 unsigned nameSize = Name.size();
4327 // for block or function pointer declaration. Name is aleady
4328 // part of the declaration.
4329 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4330 nameSize = 1;
4331 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
4332 }
4333 else {
4334 SourceLocation startLoc;
4335 Expr *E = ND->getInit();
4336 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4337 startLoc = ECE->getLParenLoc();
4338 else
4339 startLoc = E->getLocStart();
4340 startLoc = SM->getExpansionLoc(startLoc);
4341 endBuf = SM->getCharacterData(startLoc);
4342 ByrefType += " " + Name;
4343 ByrefType += " = {(void*)";
4344 ByrefType += utostr(isa);
4345 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4346 ByrefType += utostr(flags);
4347 ByrefType += ", ";
4348 ByrefType += "sizeof(";
4349 RewriteByRefString(ByrefType, Name, ND);
4350 ByrefType += "), ";
4351 if (HasCopyAndDispose) {
4352 ByrefType += "__Block_byref_id_object_copy_";
4353 ByrefType += utostr(flag);
4354 ByrefType += ", __Block_byref_id_object_dispose_";
4355 ByrefType += utostr(flag);
4356 ByrefType += ", ";
4357 }
4358 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
4359
4360 // Complete the newly synthesized compound expression by inserting a right
4361 // curly brace before the end of the declaration.
4362 // FIXME: This approach avoids rewriting the initializer expression. It
4363 // also assumes there is only one declarator. For example, the following
4364 // isn't currently supported by this routine (in general):
4365 //
4366 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4367 //
4368 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4369 const char *semiBuf = strchr(startInitializerBuf, ';');
4370 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4371 SourceLocation semiLoc =
4372 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
4373
4374 InsertText(semiLoc, "}");
4375 }
4376 return;
4377}
4378
4379void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4380 // Add initializers for any closure decl refs.
4381 GetBlockDeclRefExprs(Exp->getBody());
4382 if (BlockDeclRefs.size()) {
4383 // Unique all "by copy" declarations.
4384 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004385 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004386 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4387 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4388 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4389 }
4390 }
4391 // Unique all "by ref" declarations.
4392 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004393 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004394 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4395 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4396 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4397 }
4398 }
4399 // Find any imported blocks...they will need special attention.
4400 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004401 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004402 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4403 BlockDeclRefs[i]->getType()->isBlockPointerType())
4404 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4405 }
4406}
4407
4408FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
4409 IdentifierInfo *ID = &Context->Idents.get(name);
4410 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
4411 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4412 SourceLocation(), ID, FType, 0, SC_Extern,
4413 SC_None, false, false);
4414}
4415
4416Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +00004417 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00004418
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004419 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00004420
4421 if (block->getDeclContext()->getRedeclContext()->isFileContext())
4422 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
4423
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004424 Blocks.push_back(Exp);
4425
4426 CollectBlockDeclRefInfo(Exp);
4427
4428 // Add inner imported variables now used in current block.
4429 int countOfInnerDecls = 0;
4430 if (!InnerBlockDeclRefs.empty()) {
4431 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00004432 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004433 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00004434 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004435 // We need to save the copied-in variables in nested
4436 // blocks because it is needed at the end for some of the API generations.
4437 // See SynthesizeBlockLiterals routine.
4438 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4439 BlockDeclRefs.push_back(Exp);
4440 BlockByCopyDeclsPtrSet.insert(VD);
4441 BlockByCopyDecls.push_back(VD);
4442 }
John McCallf4b88a42012-03-10 09:33:50 +00004443 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004444 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4445 BlockDeclRefs.push_back(Exp);
4446 BlockByRefDeclsPtrSet.insert(VD);
4447 BlockByRefDecls.push_back(VD);
4448 }
4449 }
4450 // Find any imported blocks...they will need special attention.
4451 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004452 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004453 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4454 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4455 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
4456 }
4457 InnerDeclRefsCount.push_back(countOfInnerDecls);
4458
4459 std::string FuncName;
4460
4461 if (CurFunctionDef)
4462 FuncName = CurFunctionDef->getNameAsString();
4463 else if (CurMethodDef)
4464 BuildUniqueMethodName(FuncName, CurMethodDef);
4465 else if (GlobalVarDecl)
4466 FuncName = std::string(GlobalVarDecl->getNameAsString());
4467
4468 std::string BlockNumber = utostr(Blocks.size()-1);
4469
4470 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4471 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4472
4473 // Get a pointer to the function type so we can cast appropriately.
4474 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4475 QualType FType = Context->getPointerType(BFT);
4476
4477 FunctionDecl *FD;
4478 Expr *NewRep;
4479
4480 // Simulate a contructor call...
4481 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00004482 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004483 SourceLocation());
4484
4485 SmallVector<Expr*, 4> InitExprs;
4486
4487 // Initialize the block function.
4488 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00004489 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4490 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004491 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4492 CK_BitCast, Arg);
4493 InitExprs.push_back(castExpr);
4494
4495 // Initialize the block descriptor.
4496 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
4497
4498 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
4499 SourceLocation(), SourceLocation(),
4500 &Context->Idents.get(DescData.c_str()),
4501 Context->VoidPtrTy, 0,
4502 SC_Static, SC_None);
4503 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00004504 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004505 Context->VoidPtrTy,
4506 VK_LValue,
4507 SourceLocation()),
4508 UO_AddrOf,
4509 Context->getPointerType(Context->VoidPtrTy),
4510 VK_RValue, OK_Ordinary,
4511 SourceLocation());
4512 InitExprs.push_back(DescRefExpr);
4513
4514 // Add initializers for any closure decl refs.
4515 if (BlockDeclRefs.size()) {
4516 Expr *Exp;
4517 // Output all "by copy" declarations.
4518 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4519 E = BlockByCopyDecls.end(); I != E; ++I) {
4520 if (isObjCType((*I)->getType())) {
4521 // FIXME: Conform to ABI ([[obj retain] autorelease]).
4522 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004523 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
4524 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004525 if (HasLocalVariableExternalStorage(*I)) {
4526 QualType QT = (*I)->getType();
4527 QT = Context->getPointerType(QT);
4528 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4529 OK_Ordinary, SourceLocation());
4530 }
4531 } else if (isTopLevelBlockPointerType((*I)->getType())) {
4532 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004533 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4534 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004535 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4536 CK_BitCast, Arg);
4537 } else {
4538 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004539 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
4540 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004541 if (HasLocalVariableExternalStorage(*I)) {
4542 QualType QT = (*I)->getType();
4543 QT = Context->getPointerType(QT);
4544 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4545 OK_Ordinary, SourceLocation());
4546 }
4547
4548 }
4549 InitExprs.push_back(Exp);
4550 }
4551 // Output all "by ref" declarations.
4552 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4553 E = BlockByRefDecls.end(); I != E; ++I) {
4554 ValueDecl *ND = (*I);
4555 std::string Name(ND->getNameAsString());
4556 std::string RecName;
4557 RewriteByRefString(RecName, Name, ND, true);
4558 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4559 + sizeof("struct"));
4560 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4561 SourceLocation(), SourceLocation(),
4562 II);
4563 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4564 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4565
4566 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004567 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004568 SourceLocation());
4569 bool isNestedCapturedVar = false;
4570 if (block)
4571 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
4572 ce = block->capture_end(); ci != ce; ++ci) {
4573 const VarDecl *variable = ci->getVariable();
4574 if (variable == ND && ci->isNested()) {
4575 assert (ci->isByRef() &&
4576 "SynthBlockInitExpr - captured block variable is not byref");
4577 isNestedCapturedVar = true;
4578 break;
4579 }
4580 }
4581 // captured nested byref variable has its address passed. Do not take
4582 // its address again.
4583 if (!isNestedCapturedVar)
4584 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
4585 Context->getPointerType(Exp->getType()),
4586 VK_RValue, OK_Ordinary, SourceLocation());
4587 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
4588 InitExprs.push_back(Exp);
4589 }
4590 }
4591 if (ImportedBlockDecls.size()) {
4592 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4593 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
4594 unsigned IntSize =
4595 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4596 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4597 Context->IntTy, SourceLocation());
4598 InitExprs.push_back(FlagExp);
4599 }
4600 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4601 FType, VK_LValue, SourceLocation());
4602 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
4603 Context->getPointerType(NewRep->getType()),
4604 VK_RValue, OK_Ordinary, SourceLocation());
4605 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
4606 NewRep);
4607 BlockDeclRefs.clear();
4608 BlockByRefDecls.clear();
4609 BlockByRefDeclsPtrSet.clear();
4610 BlockByCopyDecls.clear();
4611 BlockByCopyDeclsPtrSet.clear();
4612 ImportedBlockDecls.clear();
4613 return NewRep;
4614}
4615
4616bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4617 if (const ObjCForCollectionStmt * CS =
4618 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4619 return CS->getElement() == DS;
4620 return false;
4621}
4622
4623//===----------------------------------------------------------------------===//
4624// Function Body / Expression rewriting
4625//===----------------------------------------------------------------------===//
4626
4627Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4628 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4629 isa<DoStmt>(S) || isa<ForStmt>(S))
4630 Stmts.push_back(S);
4631 else if (isa<ObjCForCollectionStmt>(S)) {
4632 Stmts.push_back(S);
4633 ObjCBcLabelNo.push_back(++BcLabelCount);
4634 }
4635
4636 // Pseudo-object operations and ivar references need special
4637 // treatment because we're going to recursively rewrite them.
4638 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4639 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4640 return RewritePropertyOrImplicitSetter(PseudoOp);
4641 } else {
4642 return RewritePropertyOrImplicitGetter(PseudoOp);
4643 }
4644 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4645 return RewriteObjCIvarRefExpr(IvarRefExpr);
4646 }
4647
4648 SourceRange OrigStmtRange = S->getSourceRange();
4649
4650 // Perform a bottom up rewrite of all children.
4651 for (Stmt::child_range CI = S->children(); CI; ++CI)
4652 if (*CI) {
4653 Stmt *childStmt = (*CI);
4654 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
4655 if (newStmt) {
4656 *CI = newStmt;
4657 }
4658 }
4659
4660 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00004661 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004662 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4663 InnerContexts.insert(BE->getBlockDecl());
4664 ImportedLocalExternalDecls.clear();
4665 GetInnerBlockDeclRefExprs(BE->getBody(),
4666 InnerBlockDeclRefs, InnerContexts);
4667 // Rewrite the block body in place.
4668 Stmt *SaveCurrentBody = CurrentBody;
4669 CurrentBody = BE->getBody();
4670 PropParentMap = 0;
4671 // block literal on rhs of a property-dot-sytax assignment
4672 // must be replaced by its synthesize ast so getRewrittenText
4673 // works as expected. In this case, what actually ends up on RHS
4674 // is the blockTranscribed which is the helper function for the
4675 // block literal; as in: self.c = ^() {[ace ARR];};
4676 bool saveDisableReplaceStmt = DisableReplaceStmt;
4677 DisableReplaceStmt = false;
4678 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4679 DisableReplaceStmt = saveDisableReplaceStmt;
4680 CurrentBody = SaveCurrentBody;
4681 PropParentMap = 0;
4682 ImportedLocalExternalDecls.clear();
4683 // Now we snarf the rewritten text and stash it away for later use.
4684 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
4685 RewrittenBlockExprs[BE] = Str;
4686
4687 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4688
4689 //blockTranscribed->dump();
4690 ReplaceStmt(S, blockTranscribed);
4691 return blockTranscribed;
4692 }
4693 // Handle specific things.
4694 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4695 return RewriteAtEncode(AtEncode);
4696
4697 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4698 return RewriteAtSelector(AtSelector);
4699
4700 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4701 return RewriteObjCStringLiteral(AtString);
4702
4703 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
4704#if 0
4705 // Before we rewrite it, put the original message expression in a comment.
4706 SourceLocation startLoc = MessExpr->getLocStart();
4707 SourceLocation endLoc = MessExpr->getLocEnd();
4708
4709 const char *startBuf = SM->getCharacterData(startLoc);
4710 const char *endBuf = SM->getCharacterData(endLoc);
4711
4712 std::string messString;
4713 messString += "// ";
4714 messString.append(startBuf, endBuf-startBuf+1);
4715 messString += "\n";
4716
4717 // FIXME: Missing definition of
4718 // InsertText(clang::SourceLocation, char const*, unsigned int).
4719 // InsertText(startLoc, messString.c_str(), messString.size());
4720 // Tried this, but it didn't work either...
4721 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
4722#endif
4723 return RewriteMessageExpr(MessExpr);
4724 }
4725
4726 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4727 return RewriteObjCTryStmt(StmtTry);
4728
4729 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4730 return RewriteObjCSynchronizedStmt(StmtTry);
4731
4732 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4733 return RewriteObjCThrowStmt(StmtThrow);
4734
4735 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4736 return RewriteObjCProtocolExpr(ProtocolExp);
4737
4738 if (ObjCForCollectionStmt *StmtForCollection =
4739 dyn_cast<ObjCForCollectionStmt>(S))
4740 return RewriteObjCForCollectionStmt(StmtForCollection,
4741 OrigStmtRange.getEnd());
4742 if (BreakStmt *StmtBreakStmt =
4743 dyn_cast<BreakStmt>(S))
4744 return RewriteBreakStmt(StmtBreakStmt);
4745 if (ContinueStmt *StmtContinueStmt =
4746 dyn_cast<ContinueStmt>(S))
4747 return RewriteContinueStmt(StmtContinueStmt);
4748
4749 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4750 // and cast exprs.
4751 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4752 // FIXME: What we're doing here is modifying the type-specifier that
4753 // precedes the first Decl. In the future the DeclGroup should have
4754 // a separate type-specifier that we can rewrite.
4755 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4756 // the context of an ObjCForCollectionStmt. For example:
4757 // NSArray *someArray;
4758 // for (id <FooProtocol> index in someArray) ;
4759 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4760 // and it depends on the original text locations/positions.
4761 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
4762 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4763
4764 // Blocks rewrite rules.
4765 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4766 DI != DE; ++DI) {
4767 Decl *SD = *DI;
4768 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
4769 if (isTopLevelBlockPointerType(ND->getType()))
4770 RewriteBlockPointerDecl(ND);
4771 else if (ND->getType()->isFunctionPointerType())
4772 CheckFunctionPointerDecl(ND->getType(), ND);
4773 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
4774 if (VD->hasAttr<BlocksAttr>()) {
4775 static unsigned uniqueByrefDeclCount = 0;
4776 assert(!BlockByRefDeclNo.count(ND) &&
4777 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4778 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
4779 RewriteByRefVar(VD);
4780 }
4781 else
4782 RewriteTypeOfDecl(VD);
4783 }
4784 }
4785 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
4786 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4787 RewriteBlockPointerDecl(TD);
4788 else if (TD->getUnderlyingType()->isFunctionPointerType())
4789 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4790 }
4791 }
4792 }
4793
4794 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4795 RewriteObjCQualifiedInterfaceTypes(CE);
4796
4797 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4798 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4799 assert(!Stmts.empty() && "Statement stack is empty");
4800 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4801 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4802 && "Statement stack mismatch");
4803 Stmts.pop_back();
4804 }
4805 // Handle blocks rewriting.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004806 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4807 ValueDecl *VD = DRE->getDecl();
4808 if (VD->hasAttr<BlocksAttr>())
4809 return RewriteBlockDeclRefExpr(DRE);
4810 if (HasLocalVariableExternalStorage(VD))
4811 return RewriteLocalVariableExternalStorage(DRE);
4812 }
4813
4814 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4815 if (CE->getCallee()->getType()->isBlockPointerType()) {
4816 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
4817 ReplaceStmt(S, BlockCall);
4818 return BlockCall;
4819 }
4820 }
4821 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
4822 RewriteCastExpr(CE);
4823 }
4824#if 0
4825 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4826 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4827 ICE->getSubExpr(),
4828 SourceLocation());
4829 // Get the new text.
4830 std::string SStr;
4831 llvm::raw_string_ostream Buf(SStr);
4832 Replacement->printPretty(Buf, *Context);
4833 const std::string &Str = Buf.str();
4834
4835 printf("CAST = %s\n", &Str[0]);
4836 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4837 delete S;
4838 return Replacement;
4839 }
4840#endif
4841 // Return this stmt unmodified.
4842 return S;
4843}
4844
4845void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
4846 for (RecordDecl::field_iterator i = RD->field_begin(),
4847 e = RD->field_end(); i != e; ++i) {
4848 FieldDecl *FD = *i;
4849 if (isTopLevelBlockPointerType(FD->getType()))
4850 RewriteBlockPointerDecl(FD);
4851 if (FD->getType()->isObjCQualifiedIdType() ||
4852 FD->getType()->isObjCQualifiedInterfaceType())
4853 RewriteObjCQualifiedInterfaceTypes(FD);
4854 }
4855}
4856
4857/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4858/// main file of the input.
4859void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
4860 switch (D->getKind()) {
4861 case Decl::Function: {
4862 FunctionDecl *FD = cast<FunctionDecl>(D);
4863 if (FD->isOverloadedOperator())
4864 return;
4865
4866 // Since function prototypes don't have ParmDecl's, we check the function
4867 // prototype. This enables us to rewrite function declarations and
4868 // definitions using the same code.
4869 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
4870
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00004871 if (!FD->isThisDeclarationADefinition())
4872 break;
4873
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004874 // FIXME: If this should support Obj-C++, support CXXTryStmt
4875 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4876 CurFunctionDef = FD;
4877 CurFunctionDeclToDeclareForBlock = FD;
4878 CurrentBody = Body;
4879 Body =
4880 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4881 FD->setBody(Body);
4882 CurrentBody = 0;
4883 if (PropParentMap) {
4884 delete PropParentMap;
4885 PropParentMap = 0;
4886 }
4887 // This synthesizes and inserts the block "impl" struct, invoke function,
4888 // and any copy/dispose helper functions.
4889 InsertBlockLiteralsWithinFunction(FD);
4890 CurFunctionDef = 0;
4891 CurFunctionDeclToDeclareForBlock = 0;
4892 }
4893 break;
4894 }
4895 case Decl::ObjCMethod: {
4896 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
4897 if (CompoundStmt *Body = MD->getCompoundBody()) {
4898 CurMethodDef = MD;
4899 CurrentBody = Body;
4900 Body =
4901 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4902 MD->setBody(Body);
4903 CurrentBody = 0;
4904 if (PropParentMap) {
4905 delete PropParentMap;
4906 PropParentMap = 0;
4907 }
4908 InsertBlockLiteralsWithinMethod(MD);
4909 CurMethodDef = 0;
4910 }
4911 break;
4912 }
4913 case Decl::ObjCImplementation: {
4914 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
4915 ClassImplementation.push_back(CI);
4916 break;
4917 }
4918 case Decl::ObjCCategoryImpl: {
4919 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
4920 CategoryImplementation.push_back(CI);
4921 break;
4922 }
4923 case Decl::Var: {
4924 VarDecl *VD = cast<VarDecl>(D);
4925 RewriteObjCQualifiedInterfaceTypes(VD);
4926 if (isTopLevelBlockPointerType(VD->getType()))
4927 RewriteBlockPointerDecl(VD);
4928 else if (VD->getType()->isFunctionPointerType()) {
4929 CheckFunctionPointerDecl(VD->getType(), VD);
4930 if (VD->getInit()) {
4931 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4932 RewriteCastExpr(CE);
4933 }
4934 }
4935 } else if (VD->getType()->isRecordType()) {
4936 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4937 if (RD->isCompleteDefinition())
4938 RewriteRecordBody(RD);
4939 }
4940 if (VD->getInit()) {
4941 GlobalVarDecl = VD;
4942 CurrentBody = VD->getInit();
4943 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
4944 CurrentBody = 0;
4945 if (PropParentMap) {
4946 delete PropParentMap;
4947 PropParentMap = 0;
4948 }
4949 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
4950 GlobalVarDecl = 0;
4951
4952 // This is needed for blocks.
4953 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4954 RewriteCastExpr(CE);
4955 }
4956 }
4957 break;
4958 }
4959 case Decl::TypeAlias:
4960 case Decl::Typedef: {
4961 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
4962 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4963 RewriteBlockPointerDecl(TD);
4964 else if (TD->getUnderlyingType()->isFunctionPointerType())
4965 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4966 }
4967 break;
4968 }
4969 case Decl::CXXRecord:
4970 case Decl::Record: {
4971 RecordDecl *RD = cast<RecordDecl>(D);
4972 if (RD->isCompleteDefinition())
4973 RewriteRecordBody(RD);
4974 break;
4975 }
4976 default:
4977 break;
4978 }
4979 // Nothing yet.
4980}
4981
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00004982/// Write_ProtocolExprReferencedMetadata - This routine writer out the
4983/// protocol reference symbols in the for of:
4984/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
4985static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
4986 ObjCProtocolDecl *PDecl,
4987 std::string &Result) {
4988 // Also output .objc_protorefs$B section and its meta-data.
4989 if (Context->getLangOpts().MicrosoftExt)
4990 Result += "__declspec(allocate(\".objc_protorefs$B\")) ";
4991 Result += "struct _protocol_t *";
4992 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
4993 Result += PDecl->getNameAsString();
4994 Result += " = &";
4995 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
4996 Result += ";\n";
4997}
4998
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004999void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5000 if (Diags.hasErrorOccurred())
5001 return;
5002
5003 RewriteInclude();
5004
5005 // Here's a great place to add any extra declarations that may be needed.
5006 // Write out meta data for each @protocol(<expr>).
5007 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005008 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005009 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005010 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
5011 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005012
5013 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian57317782012-02-21 23:58:41 +00005014 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5015 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5016 // Write struct declaration for the class matching its ivar declarations.
5017 // Note that for modern abi, this is postponed until the end of TU
5018 // because class extensions and the implementation might declare their own
5019 // private ivars.
5020 RewriteInterfaceDecl(CDecl);
5021 }
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00005022
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005023 if (ClassImplementation.size() || CategoryImplementation.size())
5024 RewriteImplementations();
5025
5026 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5027 // we are done.
5028 if (const RewriteBuffer *RewriteBuf =
5029 Rewrite.getRewriteBufferFor(MainFileID)) {
5030 //printf("Changed:\n");
5031 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5032 } else {
5033 llvm::errs() << "No changes\n";
5034 }
5035
5036 if (ClassImplementation.size() || CategoryImplementation.size() ||
5037 ProtocolExprDecls.size()) {
5038 // Rewrite Objective-c meta data*
5039 std::string ResultStr;
5040 RewriteMetaDataIntoBuffer(ResultStr);
5041 // Emit metadata.
5042 *OutFile << ResultStr;
5043 }
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005044 // Emit ImageInfo;
5045 {
5046 std::string ResultStr;
5047 WriteImageInfo(ResultStr);
5048 *OutFile << ResultStr;
5049 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005050 OutFile->flush();
5051}
5052
5053void RewriteModernObjC::Initialize(ASTContext &context) {
5054 InitializeCommon(context);
5055
Fariborz Jahanian6991bc52012-03-10 17:45:38 +00005056 Preamble += "#ifndef __OBJC2__\n";
5057 Preamble += "#define __OBJC2__\n";
5058 Preamble += "#endif\n";
5059
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005060 // declaring objc_selector outside the parameter list removes a silly
5061 // scope related warning...
5062 if (IsHeader)
5063 Preamble = "#pragma once\n";
5064 Preamble += "struct objc_selector; struct objc_class;\n";
5065 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
5066 Preamble += "struct objc_object *superClass; ";
5067 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005068 // Define all sections using syntax that makes sense.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005069 // These are currently generated.
5070 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005071 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005072 Preamble += "#pragma section(\".objc_protolist$B\", long, read, write)\n";
5073 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005074 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5075 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005076 Preamble += "#pragma section(\".objc_protorefs$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005077 // These are generated but not necessary for functionality.
5078 Preamble += "#pragma section(\".datacoal_nt$B\", long, read, write)\n";
5079 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005080 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5081 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005082 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005083
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005084 // These need be generated for performance. Currently they are not,
5085 // using API calls instead.
5086 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5087 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5088 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5089
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005090 // Add a constructor for creating temporary objects.
5091 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
5092 ": ";
5093 Preamble += "object(o), superClass(s) {} ";
5094 }
5095 Preamble += "};\n";
5096 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5097 Preamble += "typedef struct objc_object Protocol;\n";
5098 Preamble += "#define _REWRITER_typedef_Protocol\n";
5099 Preamble += "#endif\n";
5100 if (LangOpts.MicrosoftExt) {
5101 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5102 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005103 }
5104 else
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005105 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005106
5107 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
5108 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
5109 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
5110 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
5111 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
5112
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005113 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5114 Preamble += "(const char *);\n";
5115 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5116 Preamble += "(struct objc_class *);\n";
5117 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5118 Preamble += "(const char *);\n";
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005119 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005120 // @synchronized hooks.
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005121 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter( struct objc_object *);\n";
5122 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005123 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5124 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5125 Preamble += "struct __objcFastEnumerationState {\n\t";
5126 Preamble += "unsigned long state;\n\t";
5127 Preamble += "void **itemsPtr;\n\t";
5128 Preamble += "unsigned long *mutationsPtr;\n\t";
5129 Preamble += "unsigned long extra[5];\n};\n";
5130 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5131 Preamble += "#define __FASTENUMERATIONSTATE\n";
5132 Preamble += "#endif\n";
5133 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5134 Preamble += "struct __NSConstantStringImpl {\n";
5135 Preamble += " int *isa;\n";
5136 Preamble += " int flags;\n";
5137 Preamble += " char *str;\n";
5138 Preamble += " long length;\n";
5139 Preamble += "};\n";
5140 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5141 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5142 Preamble += "#else\n";
5143 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5144 Preamble += "#endif\n";
5145 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5146 Preamble += "#endif\n";
5147 // Blocks preamble.
5148 Preamble += "#ifndef BLOCK_IMPL\n";
5149 Preamble += "#define BLOCK_IMPL\n";
5150 Preamble += "struct __block_impl {\n";
5151 Preamble += " void *isa;\n";
5152 Preamble += " int Flags;\n";
5153 Preamble += " int Reserved;\n";
5154 Preamble += " void *FuncPtr;\n";
5155 Preamble += "};\n";
5156 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5157 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5158 Preamble += "extern \"C\" __declspec(dllexport) "
5159 "void _Block_object_assign(void *, const void *, const int);\n";
5160 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5161 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5162 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5163 Preamble += "#else\n";
5164 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5165 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5166 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5167 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5168 Preamble += "#endif\n";
5169 Preamble += "#endif\n";
5170 if (LangOpts.MicrosoftExt) {
5171 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5172 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5173 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5174 Preamble += "#define __attribute__(X)\n";
5175 Preamble += "#endif\n";
5176 Preamble += "#define __weak\n";
5177 }
5178 else {
5179 Preamble += "#define __block\n";
5180 Preamble += "#define __weak\n";
5181 }
5182 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5183 // as this avoids warning in any 64bit/32bit compilation model.
5184 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5185}
5186
5187/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5188/// ivar offset.
5189void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5190 std::string &Result) {
5191 if (ivar->isBitField()) {
5192 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5193 // place all bitfields at offset 0.
5194 Result += "0";
5195 } else {
5196 Result += "__OFFSETOFIVAR__(struct ";
5197 Result += ivar->getContainingInterface()->getNameAsString();
5198 if (LangOpts.MicrosoftExt)
5199 Result += "_IMPL";
5200 Result += ", ";
5201 Result += ivar->getNameAsString();
5202 Result += ")";
5203 }
5204}
5205
5206/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
5207/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005208/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005209/// char *attributes;
5210/// }
5211
5212/// struct _prop_list_t {
5213/// uint32_t entsize; // sizeof(struct _prop_t)
5214/// uint32_t count_of_properties;
5215/// struct _prop_t prop_list[count_of_properties];
5216/// }
5217
5218/// struct _protocol_t;
5219
5220/// struct _protocol_list_t {
5221/// long protocol_count; // Note, this is 32/64 bit
5222/// struct _protocol_t * protocol_list[protocol_count];
5223/// }
5224
5225/// struct _objc_method {
5226/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005227/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005228/// char *_imp;
5229/// }
5230
5231/// struct _method_list_t {
5232/// uint32_t entsize; // sizeof(struct _objc_method)
5233/// uint32_t method_count;
5234/// struct _objc_method method_list[method_count];
5235/// }
5236
5237/// struct _protocol_t {
5238/// id isa; // NULL
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005239/// const char *protocol_name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005240/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005241/// const struct method_list_t *instance_methods;
5242/// const struct method_list_t *class_methods;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005243/// const struct method_list_t *optionalInstanceMethods;
5244/// const struct method_list_t *optionalClassMethods;
5245/// const struct _prop_list_t * properties;
5246/// const uint32_t size; // sizeof(struct _protocol_t)
5247/// const uint32_t flags; // = 0
5248/// const char ** extendedMethodTypes;
5249/// }
5250
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005251/// struct _ivar_t {
5252/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00005253/// const char *name;
5254/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005255/// uint32_t alignment;
5256/// uint32_t size;
5257/// }
5258
5259/// struct _ivar_list_t {
5260/// uint32 entsize; // sizeof(struct _ivar_t)
5261/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00005262/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005263/// }
5264
5265/// struct _class_ro_t {
5266/// uint32_t const flags;
5267/// uint32_t const instanceStart;
5268/// uint32_t const instanceSize;
5269/// uint32_t const reserved; // only when building for 64bit targets
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005270/// const uint8_t *ivarLayout;
5271/// const char *name;
5272/// const struct _method_list_t *baseMethods;
5273/// const struct _protocol_list_t *baseProtocols;
5274/// const struct _ivar_list_t *ivars;
5275/// const uint8_t *weakIvarLayout;
5276/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005277/// }
5278
5279/// struct _class_t {
5280/// struct _class_t *isa;
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00005281/// struct _class_t *superclass;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005282/// void *cache;
5283/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005284/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005285/// }
5286
5287/// struct _category_t {
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005288/// const char *name;
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005289/// struct _class_t *cls;
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005290/// const struct _method_list_t *instance_methods;
5291/// const struct _method_list_t *class_methods;
5292/// const struct _protocol_list_t *protocols;
5293/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005294/// }
5295
5296/// MessageRefTy - LLVM for:
5297/// struct _message_ref_t {
5298/// IMP messenger;
5299/// SEL name;
5300/// };
5301
5302/// SuperMessageRefTy - LLVM for:
5303/// struct _super_message_ref_t {
5304/// SUPER_IMP messenger;
5305/// SEL name;
5306/// };
5307
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005308static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005309 static bool meta_data_declared = false;
5310 if (meta_data_declared)
5311 return;
5312
5313 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005314 Result += "\tconst char *name;\n";
5315 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005316 Result += "};\n";
5317
5318 Result += "\nstruct _protocol_t;\n";
5319
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005320 Result += "\nstruct _objc_method {\n";
5321 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005322 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005323 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005324 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005325
5326 Result += "\nstruct _protocol_t {\n";
5327 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005328 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005329 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005330 Result += "\tconst struct method_list_t *instance_methods;\n";
5331 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005332 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
5333 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
5334 Result += "\tconst struct _prop_list_t * properties;\n";
5335 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
5336 Result += "\tconst unsigned int flags; // = 0\n";
5337 Result += "\tconst char ** extendedMethodTypes;\n";
5338 Result += "};\n";
5339
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005340 Result += "\nstruct _ivar_t {\n";
5341 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005342 Result += "\tconst char *name;\n";
5343 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005344 Result += "\tunsigned int alignment;\n";
5345 Result += "\tunsigned int size;\n";
5346 Result += "};\n";
5347
5348 Result += "\nstruct _class_ro_t {\n";
5349 Result += "\tunsigned int const flags;\n";
5350 Result += "\tunsigned int instanceStart;\n";
5351 Result += "\tunsigned int const instanceSize;\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005352 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
5353 if (Triple.getArch() == llvm::Triple::x86_64)
5354 Result += "\tunsigned int const reserved;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005355 Result += "\tconst unsigned char *ivarLayout;\n";
5356 Result += "\tconst char *name;\n";
5357 Result += "\tconst struct _method_list_t *baseMethods;\n";
5358 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
5359 Result += "\tconst struct _ivar_list_t *ivars;\n";
5360 Result += "\tconst unsigned char *weakIvarLayout;\n";
5361 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005362 Result += "};\n";
5363
5364 Result += "\nstruct _class_t {\n";
5365 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00005366 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005367 Result += "\tvoid *cache;\n";
5368 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005369 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005370 Result += "};\n";
5371
5372 Result += "\nstruct _category_t {\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005373 Result += "\tconst char *name;\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005374 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005375 Result += "\tconst struct _method_list_t *instance_methods;\n";
5376 Result += "\tconst struct _method_list_t *class_methods;\n";
5377 Result += "\tconst struct _protocol_list_t *protocols;\n";
5378 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005379 Result += "};\n";
5380
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00005381 Result += "__declspec(dllimport) extern struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005382 Result += "extern void *_objc_empty_vtable;\n";
5383
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005384 meta_data_declared = true;
5385}
5386
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005387static void Write_protocol_list_t_TypeDecl(std::string &Result,
5388 long super_protocol_count) {
5389 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
5390 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
5391 Result += "\tstruct _protocol_t *super_protocols[";
5392 Result += utostr(super_protocol_count); Result += "];\n";
5393 Result += "}";
5394}
5395
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005396static void Write_method_list_t_TypeDecl(std::string &Result,
5397 unsigned int method_count) {
5398 Result += "struct /*_method_list_t*/"; Result += " {\n";
5399 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
5400 Result += "\tunsigned int method_count;\n";
5401 Result += "\tstruct _objc_method method_list[";
5402 Result += utostr(method_count); Result += "];\n";
5403 Result += "}";
5404}
5405
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005406static void Write__prop_list_t_TypeDecl(std::string &Result,
5407 unsigned int property_count) {
5408 Result += "struct /*_prop_list_t*/"; Result += " {\n";
5409 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5410 Result += "\tunsigned int count_of_properties;\n";
5411 Result += "\tstruct _prop_t prop_list[";
5412 Result += utostr(property_count); Result += "];\n";
5413 Result += "}";
5414}
5415
Fariborz Jahanianae932952012-02-10 20:47:10 +00005416static void Write__ivar_list_t_TypeDecl(std::string &Result,
5417 unsigned int ivar_count) {
5418 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
5419 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5420 Result += "\tunsigned int count;\n";
5421 Result += "\tstruct _ivar_t ivar_list[";
5422 Result += utostr(ivar_count); Result += "];\n";
5423 Result += "}";
5424}
5425
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005426static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
5427 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
5428 StringRef VarName,
5429 StringRef ProtocolName) {
5430 if (SuperProtocols.size() > 0) {
5431 Result += "\nstatic ";
5432 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
5433 Result += " "; Result += VarName;
5434 Result += ProtocolName;
5435 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5436 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
5437 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
5438 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
5439 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
5440 Result += SuperPD->getNameAsString();
5441 if (i == e-1)
5442 Result += "\n};\n";
5443 else
5444 Result += ",\n";
5445 }
5446 }
5447}
5448
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005449static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
5450 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005451 ArrayRef<ObjCMethodDecl *> Methods,
5452 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005453 StringRef TopLevelDeclName,
5454 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005455 if (Methods.size() > 0) {
5456 Result += "\nstatic ";
5457 Write_method_list_t_TypeDecl(Result, Methods.size());
5458 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005459 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005460 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5461 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
5462 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
5463 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
5464 ObjCMethodDecl *MD = Methods[i];
5465 if (i == 0)
5466 Result += "\t{{(struct objc_selector *)\"";
5467 else
5468 Result += "\t{(struct objc_selector *)\"";
5469 Result += (MD)->getSelector().getAsString(); Result += "\"";
5470 Result += ", ";
5471 std::string MethodTypeString;
5472 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
5473 Result += "\""; Result += MethodTypeString; Result += "\"";
5474 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005475 if (!MethodImpl)
5476 Result += "0";
5477 else {
5478 Result += "(void *)";
5479 Result += RewriteObj.MethodInternalNames[MD];
5480 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005481 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005482 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005483 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005484 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005485 }
5486 Result += "};\n";
5487 }
5488}
5489
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005490static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005491 ASTContext *Context, std::string &Result,
5492 ArrayRef<ObjCPropertyDecl *> Properties,
5493 const Decl *Container,
5494 StringRef VarName,
5495 StringRef ProtocolName) {
5496 if (Properties.size() > 0) {
5497 Result += "\nstatic ";
5498 Write__prop_list_t_TypeDecl(Result, Properties.size());
5499 Result += " "; Result += VarName;
5500 Result += ProtocolName;
5501 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5502 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
5503 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
5504 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
5505 ObjCPropertyDecl *PropDecl = Properties[i];
5506 if (i == 0)
5507 Result += "\t{{\"";
5508 else
5509 Result += "\t{\"";
5510 Result += PropDecl->getName(); Result += "\",";
5511 std::string PropertyTypeString, QuotePropertyTypeString;
5512 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
5513 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
5514 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
5515 if (i == e-1)
5516 Result += "}}\n";
5517 else
5518 Result += "},\n";
5519 }
5520 Result += "};\n";
5521 }
5522}
5523
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005524// Metadata flags
5525enum MetaDataDlags {
5526 CLS = 0x0,
5527 CLS_META = 0x1,
5528 CLS_ROOT = 0x2,
5529 OBJC2_CLS_HIDDEN = 0x10,
5530 CLS_EXCEPTION = 0x20,
5531
5532 /// (Obsolete) ARC-specific: this class has a .release_ivars method
5533 CLS_HAS_IVAR_RELEASER = 0x40,
5534 /// class was compiled with -fobjc-arr
5535 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
5536};
5537
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005538static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
5539 unsigned int flags,
5540 const std::string &InstanceStart,
5541 const std::string &InstanceSize,
5542 ArrayRef<ObjCMethodDecl *>baseMethods,
5543 ArrayRef<ObjCProtocolDecl *>baseProtocols,
5544 ArrayRef<ObjCIvarDecl *>ivars,
5545 ArrayRef<ObjCPropertyDecl *>Properties,
5546 StringRef VarName,
5547 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005548 Result += "\nstatic struct _class_ro_t ";
5549 Result += VarName; Result += ClassName;
5550 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5551 Result += "\t";
5552 Result += llvm::utostr(flags); Result += ", ";
5553 Result += InstanceStart; Result += ", ";
5554 Result += InstanceSize; Result += ", \n";
5555 Result += "\t";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005556 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
5557 if (Triple.getArch() == llvm::Triple::x86_64)
5558 // uint32_t const reserved; // only when building for 64bit targets
5559 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005560 // const uint8_t * const ivarLayout;
5561 Result += "0, \n\t";
5562 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005563 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005564 if (baseMethods.size() > 0) {
5565 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005566 if (metaclass)
5567 Result += "_OBJC_$_CLASS_METHODS_";
5568 else
5569 Result += "_OBJC_$_INSTANCE_METHODS_";
5570 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005571 Result += ",\n\t";
5572 }
5573 else
5574 Result += "0, \n\t";
5575
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005576 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005577 Result += "(const struct _objc_protocol_list *)&";
5578 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
5579 Result += ",\n\t";
5580 }
5581 else
5582 Result += "0, \n\t";
5583
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005584 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005585 Result += "(const struct _ivar_list_t *)&";
5586 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
5587 Result += ",\n\t";
5588 }
5589 else
5590 Result += "0, \n\t";
5591
5592 // weakIvarLayout
5593 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005594 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005595 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00005596 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005597 Result += ",\n";
5598 }
5599 else
5600 Result += "0, \n";
5601
5602 Result += "};\n";
5603}
5604
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005605static void Write_class_t(ASTContext *Context, std::string &Result,
5606 StringRef VarName,
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005607 const ObjCInterfaceDecl *CDecl, bool metaclass) {
5608 bool rootClass = (!CDecl->getSuperClass());
5609 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005610
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005611 if (!rootClass) {
5612 // Find the Root class
5613 RootClass = CDecl->getSuperClass();
5614 while (RootClass->getSuperClass()) {
5615 RootClass = RootClass->getSuperClass();
5616 }
5617 }
5618
5619 if (metaclass && rootClass) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005620 // Need to handle a case of use of forward declaration.
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005621 Result += "\n";
5622 if (CDecl->getImplementation())
5623 Result += "__declspec(dllexport) ";
5624 Result += "extern struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005625 Result += CDecl->getNameAsString();
5626 Result += ";\n";
5627 }
5628 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005629 if (!rootClass) {
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005630 Result += "\n";
5631 if (CDecl->getSuperClass()->getImplementation())
5632 Result += "__declspec(dllexport) ";
5633 Result += "extern struct _class_t ";
5634 Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005635 Result += CDecl->getSuperClass()->getNameAsString();
5636 Result += ";\n";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00005637
5638 if (metaclass) {
5639 if (RootClass->getImplementation())
5640 Result += "__declspec(dllexport) ";
5641 Result += "extern struct _class_t ";
5642 Result += VarName;
5643 Result += RootClass->getNameAsString();
5644 Result += ";\n";
5645 }
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005646 }
5647
Fariborz Jahaniane57303c2012-03-10 00:39:34 +00005648 Result += "\n__declspec(dllexport) struct _class_t "; Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005649 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
5650 Result += "\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005651 if (metaclass) {
5652 if (!rootClass) {
5653 Result += "0, // &"; Result += VarName;
5654 Result += RootClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005655 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005656 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005657 Result += CDecl->getSuperClass()->getNameAsString();
5658 Result += ",\n\t";
5659 }
5660 else {
Fariborz Jahanian452eac12012-03-20 21:09:58 +00005661 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005662 Result += CDecl->getNameAsString();
5663 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005664 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005665 Result += ",\n\t";
5666 }
5667 }
5668 else {
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005669 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005670 Result += CDecl->getNameAsString();
5671 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005672 if (!rootClass) {
5673 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005674 Result += CDecl->getSuperClass()->getNameAsString();
5675 Result += ",\n\t";
5676 }
5677 else
5678 Result += "0,\n\t";
5679 }
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005680 Result += "0, // (void *)&_objc_empty_cache,\n\t";
5681 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
5682 if (metaclass)
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005683 Result += "&_OBJC_METACLASS_RO_$_";
5684 else
5685 Result += "&_OBJC_CLASS_RO_$_";
5686 Result += CDecl->getNameAsString();
5687 Result += ",\n};\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005688
5689 // Add static function to initialize some of the meta-data fields.
5690 // avoid doing it twice.
5691 if (metaclass)
5692 return;
5693
5694 const ObjCInterfaceDecl *SuperClass =
5695 rootClass ? CDecl : CDecl->getSuperClass();
5696
5697 Result += "static void OBJC_CLASS_SETUP_$_";
5698 Result += CDecl->getNameAsString();
5699 Result += "(void ) {\n";
5700 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
5701 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00005702 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005703
5704 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian452eac12012-03-20 21:09:58 +00005705 Result += ".superclass = ";
5706 if (rootClass)
5707 Result += "&OBJC_CLASS_$_";
5708 else
5709 Result += "&OBJC_METACLASS_$_";
5710
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005711 Result += SuperClass->getNameAsString(); Result += ";\n";
5712
5713 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
5714 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
5715
5716 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
5717 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
5718 Result += CDecl->getNameAsString(); Result += ";\n";
5719
5720 if (!rootClass) {
5721 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
5722 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
5723 Result += SuperClass->getNameAsString(); Result += ";\n";
5724 }
5725
5726 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
5727 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
5728 Result += "}\n";
5729
Fariborz Jahanianfde05e12012-03-21 00:01:15 +00005730 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005731 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
5732 Result += "static void *OBJC_CLASS_SETUP2_$_";
5733 Result += CDecl->getNameAsString();
5734 Result += " = (void *)&OBJC_CLASS_SETUP_$_";
5735 Result += CDecl->getNameAsString();
5736 Result += ";\n\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005737}
5738
Fariborz Jahanian61186122012-02-17 18:40:41 +00005739static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
5740 std::string &Result,
5741 StringRef CatName,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005742 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00005743 ArrayRef<ObjCMethodDecl *> InstanceMethods,
5744 ArrayRef<ObjCMethodDecl *> ClassMethods,
5745 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
5746 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005747
NAKAMURA Takumi20f89392012-03-21 03:21:46 +00005748 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00005749 // must declare an extern class object in case this class is not implemented
5750 // in this TU.
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005751 Result += "\n";
5752 if (ClassDecl->getImplementation())
5753 Result += "__declspec(dllexport) ";
5754
5755 Result += "extern struct _class_t ";
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00005756 Result += "OBJC_CLASS_$_"; Result += ClassName;
5757 Result += ";\n";
5758
Fariborz Jahanian61186122012-02-17 18:40:41 +00005759 Result += "\nstatic struct _category_t ";
5760 Result += "_OBJC_$_CATEGORY_";
5761 Result += ClassName; Result += "_$_"; Result += CatName;
5762 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
5763 Result += "{\n";
5764 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005765 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanian61186122012-02-17 18:40:41 +00005766 Result += ",\n";
5767 if (InstanceMethods.size() > 0) {
5768 Result += "\t(const struct _method_list_t *)&";
5769 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
5770 Result += ClassName; Result += "_$_"; Result += CatName;
5771 Result += ",\n";
5772 }
5773 else
5774 Result += "\t0,\n";
5775
5776 if (ClassMethods.size() > 0) {
5777 Result += "\t(const struct _method_list_t *)&";
5778 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
5779 Result += ClassName; Result += "_$_"; Result += CatName;
5780 Result += ",\n";
5781 }
5782 else
5783 Result += "\t0,\n";
5784
5785 if (RefedProtocols.size() > 0) {
5786 Result += "\t(const struct _protocol_list_t *)&";
5787 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
5788 Result += ClassName; Result += "_$_"; Result += CatName;
5789 Result += ",\n";
5790 }
5791 else
5792 Result += "\t0,\n";
5793
5794 if (ClassProperties.size() > 0) {
5795 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
5796 Result += ClassName; Result += "_$_"; Result += CatName;
5797 Result += ",\n";
5798 }
5799 else
5800 Result += "\t0,\n";
5801
5802 Result += "};\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005803
5804 // Add static function to initialize the class pointer in the category structure.
5805 Result += "static void OBJC_CATEGORY_SETUP_$_";
5806 Result += ClassDecl->getNameAsString();
5807 Result += "_$_";
5808 Result += CatName;
5809 Result += "(void ) {\n";
5810 Result += "\t_OBJC_$_CATEGORY_";
5811 Result += ClassDecl->getNameAsString();
5812 Result += "_$_";
5813 Result += CatName;
5814 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
5815 Result += ";\n}\n";
5816
Fariborz Jahanianfde05e12012-03-21 00:01:15 +00005817 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005818 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
5819 Result += "static void *OBJC_CATEGORY_SETUP2_$_";
5820 Result += ClassDecl->getNameAsString();
5821 Result += "_$_";
5822 Result += CatName;
5823 Result += " = (void *)&OBJC_CATEGORY_SETUP_$_";
5824 Result += ClassDecl->getNameAsString();
5825 Result += "_$_";
5826 Result += CatName;
5827 Result += ";\n\n";
Fariborz Jahanian61186122012-02-17 18:40:41 +00005828}
5829
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00005830static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
5831 ASTContext *Context, std::string &Result,
5832 ArrayRef<ObjCMethodDecl *> Methods,
5833 StringRef VarName,
5834 StringRef ProtocolName) {
5835 if (Methods.size() == 0)
5836 return;
5837
5838 Result += "\nstatic const char *";
5839 Result += VarName; Result += ProtocolName;
5840 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
5841 Result += "{\n";
5842 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
5843 ObjCMethodDecl *MD = Methods[i];
5844 std::string MethodTypeString, QuoteMethodTypeString;
5845 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
5846 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
5847 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
5848 if (i == e-1)
5849 Result += "\n};\n";
5850 else {
5851 Result += ",\n";
5852 }
5853 }
5854}
5855
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005856static void Write_IvarOffsetVar(ASTContext *Context,
5857 std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005858 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00005859 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005860 // FIXME. visibilty of offset symbols may have to be set; for Darwin
5861 // this is what happens:
5862 /**
5863 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
5864 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
5865 Class->getVisibility() == HiddenVisibility)
5866 Visibility shoud be: HiddenVisibility;
5867 else
5868 Visibility shoud be: DefaultVisibility;
5869 */
5870
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005871 Result += "\n";
5872 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
5873 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005874 if (Context->getLangOpts().MicrosoftExt)
5875 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
5876
5877 if (!Context->getLangOpts().MicrosoftExt ||
5878 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanian117591f2012-03-10 01:34:42 +00005879 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahaniand1c84d32012-03-10 00:53:02 +00005880 Result += "unsigned long int ";
5881 else
5882 Result += "__declspec(dllexport) unsigned long int ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00005883 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005884 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
5885 Result += " = ";
5886 if (IvarDecl->isBitField()) {
5887 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5888 // place all bitfields at offset 0.
5889 Result += "0;\n";
5890 }
5891 else {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005892 Result += "__OFFSETOFIVAR__(struct ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00005893 Result += CDecl->getNameAsString();
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005894 Result += "_IMPL, ";
5895 Result += IvarDecl->getName(); Result += ");\n";
5896 }
5897 }
5898}
5899
Fariborz Jahanianae932952012-02-10 20:47:10 +00005900static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
5901 ASTContext *Context, std::string &Result,
5902 ArrayRef<ObjCIvarDecl *> Ivars,
5903 StringRef VarName,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00005904 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanianae932952012-02-10 20:47:10 +00005905 if (Ivars.size() > 0) {
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00005906 Write_IvarOffsetVar(Context, Result, Ivars, CDecl);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005907
Fariborz Jahanianae932952012-02-10 20:47:10 +00005908 Result += "\nstatic ";
5909 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
5910 Result += " "; Result += VarName;
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00005911 Result += CDecl->getNameAsString();
Fariborz Jahanianae932952012-02-10 20:47:10 +00005912 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5913 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
5914 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
5915 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
5916 ObjCIvarDecl *IvarDecl = Ivars[i];
5917 if (i == 0)
5918 Result += "\t{{";
5919 else
5920 Result += "\t {";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00005921 Result += "(unsigned long int *)&";
5922 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005923 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005924
5925 Result += "\""; Result += IvarDecl->getName(); Result += "\", ";
5926 std::string IvarTypeString, QuoteIvarTypeString;
5927 Context->getObjCEncodingForType(IvarDecl->getType(), IvarTypeString,
5928 IvarDecl);
5929 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
5930 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
5931
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00005932 // FIXME. this alignment represents the host alignment and need be changed to
5933 // represent the target alignment.
5934 unsigned Align = Context->getTypeAlign(IvarDecl->getType())/8;
5935 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00005936 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00005937 CharUnits Size = Context->getTypeSizeInChars(IvarDecl->getType());
5938 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00005939 if (i == e-1)
5940 Result += "}}\n";
5941 else
5942 Result += "},\n";
5943 }
5944 Result += "};\n";
5945 }
5946}
5947
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005948/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005949void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
5950 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005951
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005952 // Do not synthesize the protocol more than once.
5953 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
5954 return;
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005955 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005956
5957 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
5958 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005959 // Must write out all protocol definitions in current qualifier list,
5960 // and in their nested qualifiers before writing out current definition.
5961 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
5962 E = PDecl->protocol_end(); I != E; ++I)
5963 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005964
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005965 // Construct method lists.
5966 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
5967 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
5968 for (ObjCProtocolDecl::instmeth_iterator
5969 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
5970 I != E; ++I) {
5971 ObjCMethodDecl *MD = *I;
5972 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
5973 OptInstanceMethods.push_back(MD);
5974 } else {
5975 InstanceMethods.push_back(MD);
5976 }
5977 }
5978
5979 for (ObjCProtocolDecl::classmeth_iterator
5980 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
5981 I != E; ++I) {
5982 ObjCMethodDecl *MD = *I;
5983 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
5984 OptClassMethods.push_back(MD);
5985 } else {
5986 ClassMethods.push_back(MD);
5987 }
5988 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00005989 std::vector<ObjCMethodDecl *> AllMethods;
5990 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
5991 AllMethods.push_back(InstanceMethods[i]);
5992 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
5993 AllMethods.push_back(ClassMethods[i]);
5994 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
5995 AllMethods.push_back(OptInstanceMethods[i]);
5996 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
5997 AllMethods.push_back(OptClassMethods[i]);
5998
5999 Write__extendedMethodTypes_initializer(*this, Context, Result,
6000 AllMethods,
6001 "_OBJC_PROTOCOL_METHOD_TYPES_",
6002 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006003 // Protocol's super protocol list
6004 std::vector<ObjCProtocolDecl *> SuperProtocols;
6005 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6006 E = PDecl->protocol_end(); I != E; ++I)
6007 SuperProtocols.push_back(*I);
6008
6009 Write_protocol_list_initializer(Context, Result, SuperProtocols,
6010 "_OBJC_PROTOCOL_REFS_",
6011 PDecl->getNameAsString());
6012
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006013 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006014 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006015 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006016
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006017 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006018 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006019 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006020
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006021 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006022 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006023 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006024
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006025 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006026 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006027 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006028
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006029 // Protocol's property metadata.
6030 std::vector<ObjCPropertyDecl *> ProtocolProperties;
6031 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
6032 E = PDecl->prop_end(); I != E; ++I)
6033 ProtocolProperties.push_back(*I);
6034
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006035 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006036 /* Container */0,
6037 "_OBJC_PROTOCOL_PROPERTIES_",
6038 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006039
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006040 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006041 Result += "\n";
6042 if (LangOpts.MicrosoftExt)
6043 Result += "__declspec(allocate(\".datacoal_nt$B\")) ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006044 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006045 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006046 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
6047 Result += "\t0,\n"; // id is; is null
6048 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006049 if (SuperProtocols.size() > 0) {
6050 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6051 Result += PDecl->getNameAsString(); Result += ",\n";
6052 }
6053 else
6054 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006055 if (InstanceMethods.size() > 0) {
6056 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
6057 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006058 }
6059 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006060 Result += "\t0,\n";
6061
6062 if (ClassMethods.size() > 0) {
6063 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
6064 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006065 }
6066 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006067 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006068
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006069 if (OptInstanceMethods.size() > 0) {
6070 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
6071 Result += PDecl->getNameAsString(); Result += ",\n";
6072 }
6073 else
6074 Result += "\t0,\n";
6075
6076 if (OptClassMethods.size() > 0) {
6077 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
6078 Result += PDecl->getNameAsString(); Result += ",\n";
6079 }
6080 else
6081 Result += "\t0,\n";
6082
6083 if (ProtocolProperties.size() > 0) {
6084 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
6085 Result += PDecl->getNameAsString(); Result += ",\n";
6086 }
6087 else
6088 Result += "\t0,\n";
6089
6090 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6091 Result += "\t0,\n";
6092
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006093 if (AllMethods.size() > 0) {
6094 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6095 Result += PDecl->getNameAsString();
6096 Result += "\n};\n";
6097 }
6098 else
6099 Result += "\t0\n};\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006100
6101 // Use this protocol meta-data to build protocol list table in section
6102 // .objc_protolist$B
6103 // Unspecified visibility means 'private extern'.
6104 if (LangOpts.MicrosoftExt)
6105 Result += "__declspec(allocate(\".objc_protolist$B\")) ";
6106 Result += "struct _protocol_t *";
6107 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6108 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6109 Result += ";\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006110
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006111 // Mark this protocol as having been generated.
6112 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
6113 llvm_unreachable("protocol already synthesized");
6114
6115}
6116
6117void RewriteModernObjC::RewriteObjCProtocolListMetaData(
6118 const ObjCList<ObjCProtocolDecl> &Protocols,
6119 StringRef prefix, StringRef ClassName,
6120 std::string &Result) {
6121 if (Protocols.empty()) return;
6122
6123 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006124 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006125
6126 // Output the top lovel protocol meta-data for the class.
6127 /* struct _objc_protocol_list {
6128 struct _objc_protocol_list *next;
6129 int protocol_count;
6130 struct _objc_protocol *class_protocols[];
6131 }
6132 */
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006133 Result += "\n";
6134 if (LangOpts.MicrosoftExt)
6135 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
6136 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006137 Result += "\tstruct _objc_protocol_list *next;\n";
6138 Result += "\tint protocol_count;\n";
6139 Result += "\tstruct _objc_protocol *class_protocols[";
6140 Result += utostr(Protocols.size());
6141 Result += "];\n} _OBJC_";
6142 Result += prefix;
6143 Result += "_PROTOCOLS_";
6144 Result += ClassName;
6145 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
6146 "{\n\t0, ";
6147 Result += utostr(Protocols.size());
6148 Result += "\n";
6149
6150 Result += "\t,{&_OBJC_PROTOCOL_";
6151 Result += Protocols[0]->getNameAsString();
6152 Result += " \n";
6153
6154 for (unsigned i = 1; i != Protocols.size(); i++) {
6155 Result += "\t ,&_OBJC_PROTOCOL_";
6156 Result += Protocols[i]->getNameAsString();
6157 Result += "\n";
6158 }
6159 Result += "\t }\n};\n";
6160}
6161
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006162/// hasObjCExceptionAttribute - Return true if this class or any super
6163/// class has the __objc_exception__ attribute.
6164/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
6165static bool hasObjCExceptionAttribute(ASTContext &Context,
6166 const ObjCInterfaceDecl *OID) {
6167 if (OID->hasAttr<ObjCExceptionAttr>())
6168 return true;
6169 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
6170 return hasObjCExceptionAttribute(Context, Super);
6171 return false;
6172}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006173
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006174void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
6175 std::string &Result) {
6176 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6177
6178 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00006179 if (CDecl->isImplicitInterfaceDecl())
6180 assert(false &&
6181 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006182
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006183 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006184 SmallVector<ObjCIvarDecl *, 8> IVars;
6185
6186 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6187 IVD; IVD = IVD->getNextIvar()) {
6188 // Ignore unnamed bit-fields.
6189 if (!IVD->getDeclName())
6190 continue;
6191 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006192 }
6193
Fariborz Jahanianae932952012-02-10 20:47:10 +00006194 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006195 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006196 CDecl);
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006197
6198 // Build _objc_method_list for class's instance methods if needed
6199 SmallVector<ObjCMethodDecl *, 32>
6200 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6201
6202 // If any of our property implementations have associated getters or
6203 // setters, produce metadata for them as well.
6204 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6205 PropEnd = IDecl->propimpl_end();
6206 Prop != PropEnd; ++Prop) {
6207 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6208 continue;
6209 if (!(*Prop)->getPropertyIvarDecl())
6210 continue;
6211 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
6212 if (!PD)
6213 continue;
6214 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
6215 if (!Getter->isDefined())
6216 InstanceMethods.push_back(Getter);
6217 if (PD->isReadOnly())
6218 continue;
6219 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
6220 if (!Setter->isDefined())
6221 InstanceMethods.push_back(Setter);
6222 }
6223
6224 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6225 "_OBJC_$_INSTANCE_METHODS_",
6226 IDecl->getNameAsString(), true);
6227
6228 SmallVector<ObjCMethodDecl *, 32>
6229 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6230
6231 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6232 "_OBJC_$_CLASS_METHODS_",
6233 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00006234
6235 // Protocols referenced in class declaration?
6236 // Protocol's super protocol list
6237 std::vector<ObjCProtocolDecl *> RefedProtocols;
6238 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
6239 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6240 E = Protocols.end();
6241 I != E; ++I) {
6242 RefedProtocols.push_back(*I);
6243 // Must write out all protocol definitions in current qualifier list,
6244 // and in their nested qualifiers before writing out current definition.
6245 RewriteObjCProtocolMetaData(*I, Result);
6246 }
6247
6248 Write_protocol_list_initializer(Context, Result,
6249 RefedProtocols,
6250 "_OBJC_CLASS_PROTOCOLS_$_",
6251 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006252
6253 // Protocol's property metadata.
6254 std::vector<ObjCPropertyDecl *> ClassProperties;
6255 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6256 E = CDecl->prop_end(); I != E; ++I)
6257 ClassProperties.push_back(*I);
6258
6259 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanian2df089d2012-03-22 17:39:35 +00006260 /* Container */IDecl,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006261 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006262 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006263
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006264
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006265 // Data for initializing _class_ro_t metaclass meta-data
6266 uint32_t flags = CLS_META;
6267 std::string InstanceSize;
6268 std::string InstanceStart;
6269
6270
6271 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
6272 if (classIsHidden)
6273 flags |= OBJC2_CLS_HIDDEN;
6274
6275 if (!CDecl->getSuperClass())
6276 // class is root
6277 flags |= CLS_ROOT;
6278 InstanceSize = "sizeof(struct _class_t)";
6279 InstanceStart = InstanceSize;
6280 Write__class_ro_t_initializer(Context, Result, flags,
6281 InstanceStart, InstanceSize,
6282 ClassMethods,
6283 0,
6284 0,
6285 0,
6286 "_OBJC_METACLASS_RO_$_",
6287 CDecl->getNameAsString());
6288
6289
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006290 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006291 flags = CLS;
6292 if (classIsHidden)
6293 flags |= OBJC2_CLS_HIDDEN;
6294
6295 if (hasObjCExceptionAttribute(*Context, CDecl))
6296 flags |= CLS_EXCEPTION;
6297
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006298 if (!CDecl->getSuperClass())
6299 // class is root
6300 flags |= CLS_ROOT;
6301
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006302 InstanceSize.clear();
6303 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006304 if (!ObjCSynthesizedStructs.count(CDecl)) {
6305 InstanceSize = "0";
6306 InstanceStart = "0";
6307 }
6308 else {
6309 InstanceSize = "sizeof(struct ";
6310 InstanceSize += CDecl->getNameAsString();
6311 InstanceSize += "_IMPL)";
6312
6313 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6314 if (IVD) {
6315 InstanceStart += "__OFFSETOFIVAR__(struct ";
6316 InstanceStart += CDecl->getNameAsString();
6317 InstanceStart += "_IMPL, ";
6318 InstanceStart += IVD->getNameAsString();
6319 InstanceStart += ")";
6320 }
6321 else
6322 InstanceStart = InstanceSize;
6323 }
6324 Write__class_ro_t_initializer(Context, Result, flags,
6325 InstanceStart, InstanceSize,
6326 InstanceMethods,
6327 RefedProtocols,
6328 IVars,
6329 ClassProperties,
6330 "_OBJC_CLASS_RO_$_",
6331 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006332
6333 Write_class_t(Context, Result,
6334 "OBJC_METACLASS_$_",
6335 CDecl, /*metaclass*/true);
6336
6337 Write_class_t(Context, Result,
6338 "OBJC_CLASS_$_",
6339 CDecl, /*metaclass*/false);
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006340
6341 if (ImplementationIsNonLazy(IDecl))
6342 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006343
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006344}
6345
6346void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
6347 int ClsDefCount = ClassImplementation.size();
6348 int CatDefCount = CategoryImplementation.size();
6349
6350 // For each implemented class, write out all its meta data.
6351 for (int i = 0; i < ClsDefCount; i++)
6352 RewriteObjCClassMetaData(ClassImplementation[i], Result);
6353
6354 // For each implemented category, write out all its meta data.
6355 for (int i = 0; i < CatDefCount; i++)
6356 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
6357
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006358 if (ClsDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006359 if (LangOpts.MicrosoftExt)
6360 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006361 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
6362 Result += llvm::utostr(ClsDefCount); Result += "]";
6363 Result +=
6364 " __attribute__((used, section (\"__DATA, __objc_classlist,"
6365 "regular,no_dead_strip\")))= {\n";
6366 for (int i = 0; i < ClsDefCount; i++) {
6367 Result += "\t&OBJC_CLASS_$_";
6368 Result += ClassImplementation[i]->getNameAsString();
6369 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006370 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006371 Result += "};\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006372
6373 if (!DefinedNonLazyClasses.empty()) {
6374 if (LangOpts.MicrosoftExt)
6375 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
6376 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
6377 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
6378 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
6379 Result += ",\n";
6380 }
6381 Result += "};\n";
6382 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006383 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00006384
6385 if (CatDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006386 if (LangOpts.MicrosoftExt)
6387 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006388 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
6389 Result += llvm::utostr(CatDefCount); Result += "]";
6390 Result +=
6391 " __attribute__((used, section (\"__DATA, __objc_catlist,"
6392 "regular,no_dead_strip\")))= {\n";
6393 for (int i = 0; i < CatDefCount; i++) {
6394 Result += "\t&_OBJC_$_CATEGORY_";
6395 Result +=
6396 CategoryImplementation[i]->getClassInterface()->getNameAsString();
6397 Result += "_$_";
6398 Result += CategoryImplementation[i]->getNameAsString();
6399 Result += ",\n";
6400 }
6401 Result += "};\n";
6402 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006403
6404 if (!DefinedNonLazyCategories.empty()) {
6405 if (LangOpts.MicrosoftExt)
6406 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
6407 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
6408 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
6409 Result += "\t&_OBJC_$_CATEGORY_";
6410 Result +=
6411 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
6412 Result += "_$_";
6413 Result += DefinedNonLazyCategories[i]->getNameAsString();
6414 Result += ",\n";
6415 }
6416 Result += "};\n";
6417 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006418}
6419
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006420void RewriteModernObjC::WriteImageInfo(std::string &Result) {
6421 if (LangOpts.MicrosoftExt)
6422 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
6423
6424 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
6425 // version 0, ObjCABI is 2
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006426 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006427}
6428
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006429/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
6430/// implementation.
6431void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
6432 std::string &Result) {
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006433 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006434 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
6435 // Find category declaration for this implementation.
Fariborz Jahanian61186122012-02-17 18:40:41 +00006436 ObjCCategoryDecl *CDecl=0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006437 for (CDecl = ClassDecl->getCategoryList(); CDecl;
6438 CDecl = CDecl->getNextClassCategory())
6439 if (CDecl->getIdentifier() == IDecl->getIdentifier())
6440 break;
6441
6442 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00006443 FullCategoryName += "_$_";
6444 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006445
6446 // Build _objc_method_list for class's instance methods if needed
6447 SmallVector<ObjCMethodDecl *, 32>
6448 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6449
6450 // If any of our property implementations have associated getters or
6451 // setters, produce metadata for them as well.
6452 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6453 PropEnd = IDecl->propimpl_end();
6454 Prop != PropEnd; ++Prop) {
6455 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6456 continue;
6457 if (!(*Prop)->getPropertyIvarDecl())
6458 continue;
6459 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
6460 if (!PD)
6461 continue;
6462 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
6463 InstanceMethods.push_back(Getter);
6464 if (PD->isReadOnly())
6465 continue;
6466 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
6467 InstanceMethods.push_back(Setter);
6468 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006469
Fariborz Jahanian61186122012-02-17 18:40:41 +00006470 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6471 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
6472 FullCategoryName, true);
6473
6474 SmallVector<ObjCMethodDecl *, 32>
6475 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6476
6477 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6478 "_OBJC_$_CATEGORY_CLASS_METHODS_",
6479 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006480
6481 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00006482 // Protocol's super protocol list
6483 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00006484 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
6485 E = CDecl->protocol_end();
6486
6487 I != E; ++I) {
Fariborz Jahanian61186122012-02-17 18:40:41 +00006488 RefedProtocols.push_back(*I);
6489 // Must write out all protocol definitions in current qualifier list,
6490 // and in their nested qualifiers before writing out current definition.
6491 RewriteObjCProtocolMetaData(*I, Result);
6492 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006493
Fariborz Jahanian61186122012-02-17 18:40:41 +00006494 Write_protocol_list_initializer(Context, Result,
6495 RefedProtocols,
6496 "_OBJC_CATEGORY_PROTOCOLS_$_",
6497 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006498
Fariborz Jahanian61186122012-02-17 18:40:41 +00006499 // Protocol's property metadata.
6500 std::vector<ObjCPropertyDecl *> ClassProperties;
6501 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6502 E = CDecl->prop_end(); I != E; ++I)
6503 ClassProperties.push_back(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006504
Fariborz Jahanian61186122012-02-17 18:40:41 +00006505 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
6506 /* Container */0,
6507 "_OBJC_$_PROP_LIST_",
6508 FullCategoryName);
6509
6510 Write_category_t(*this, Context, Result,
6511 CDecl->getNameAsString(),
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006512 ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006513 InstanceMethods,
6514 ClassMethods,
6515 RefedProtocols,
6516 ClassProperties);
6517
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006518 // Determine if this category is also "non-lazy".
6519 if (ImplementationIsNonLazy(IDecl))
6520 DefinedNonLazyCategories.push_back(CDecl);
6521
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006522}
6523
6524// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
6525/// class methods.
6526template<typename MethodIterator>
6527void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
6528 MethodIterator MethodEnd,
6529 bool IsInstanceMethod,
6530 StringRef prefix,
6531 StringRef ClassName,
6532 std::string &Result) {
6533 if (MethodBegin == MethodEnd) return;
6534
6535 if (!objc_impl_method) {
6536 /* struct _objc_method {
6537 SEL _cmd;
6538 char *method_types;
6539 void *_imp;
6540 }
6541 */
6542 Result += "\nstruct _objc_method {\n";
6543 Result += "\tSEL _cmd;\n";
6544 Result += "\tchar *method_types;\n";
6545 Result += "\tvoid *_imp;\n";
6546 Result += "};\n";
6547
6548 objc_impl_method = true;
6549 }
6550
6551 // Build _objc_method_list for class's methods if needed
6552
6553 /* struct {
6554 struct _objc_method_list *next_method;
6555 int method_count;
6556 struct _objc_method method_list[];
6557 }
6558 */
6559 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006560 Result += "\n";
6561 if (LangOpts.MicrosoftExt) {
6562 if (IsInstanceMethod)
6563 Result += "__declspec(allocate(\".inst_meth$B\")) ";
6564 else
6565 Result += "__declspec(allocate(\".cls_meth$B\")) ";
6566 }
6567 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006568 Result += "\tstruct _objc_method_list *next_method;\n";
6569 Result += "\tint method_count;\n";
6570 Result += "\tstruct _objc_method method_list[";
6571 Result += utostr(NumMethods);
6572 Result += "];\n} _OBJC_";
6573 Result += prefix;
6574 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
6575 Result += "_METHODS_";
6576 Result += ClassName;
6577 Result += " __attribute__ ((used, section (\"__OBJC, __";
6578 Result += IsInstanceMethod ? "inst" : "cls";
6579 Result += "_meth\")))= ";
6580 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
6581
6582 Result += "\t,{{(SEL)\"";
6583 Result += (*MethodBegin)->getSelector().getAsString().c_str();
6584 std::string MethodTypeString;
6585 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
6586 Result += "\", \"";
6587 Result += MethodTypeString;
6588 Result += "\", (void *)";
6589 Result += MethodInternalNames[*MethodBegin];
6590 Result += "}\n";
6591 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
6592 Result += "\t ,{(SEL)\"";
6593 Result += (*MethodBegin)->getSelector().getAsString().c_str();
6594 std::string MethodTypeString;
6595 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
6596 Result += "\", \"";
6597 Result += MethodTypeString;
6598 Result += "\", (void *)";
6599 Result += MethodInternalNames[*MethodBegin];
6600 Result += "}\n";
6601 }
6602 Result += "\t }\n};\n";
6603}
6604
6605Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
6606 SourceRange OldRange = IV->getSourceRange();
6607 Expr *BaseExpr = IV->getBase();
6608
6609 // Rewrite the base, but without actually doing replaces.
6610 {
6611 DisableReplaceStmtScope S(*this);
6612 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
6613 IV->setBase(BaseExpr);
6614 }
6615
6616 ObjCIvarDecl *D = IV->getDecl();
6617
6618 Expr *Replacement = IV;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006619
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006620 if (BaseExpr->getType()->isObjCObjectPointerType()) {
6621 const ObjCInterfaceType *iFaceDecl =
6622 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
6623 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
6624 // lookup which class implements the instance variable.
6625 ObjCInterfaceDecl *clsDeclared = 0;
6626 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
6627 clsDeclared);
6628 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
6629
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006630 // Build name of symbol holding ivar offset.
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006631 std::string IvarOffsetName;
6632 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
6633
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00006634 ReferencedIvars[clsDeclared].insert(D);
6635
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006636 // cast offset to "char *".
6637 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
6638 Context->getPointerType(Context->CharTy),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006639 CK_BitCast,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006640 BaseExpr);
6641 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
6642 SourceLocation(), &Context->Idents.get(IvarOffsetName),
6643 Context->UnsignedLongTy, 0, SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00006644 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
6645 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006646 SourceLocation());
6647 BinaryOperator *addExpr =
6648 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
6649 Context->getPointerType(Context->CharTy),
6650 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006651 // Don't forget the parens to enforce the proper binding.
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006652 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
6653 SourceLocation(),
6654 addExpr);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00006655 QualType IvarT = D->getType();
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00006656 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00006657 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006658
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006659 castExpr = NoTypeInfoCStyleCastExpr(Context,
6660 castT,
6661 CK_BitCast,
6662 PE);
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00006663 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006664 VK_LValue, OK_Ordinary,
6665 SourceLocation());
6666 PE = new (Context) ParenExpr(OldRange.getBegin(),
6667 OldRange.getEnd(),
6668 Exp);
6669
6670 Replacement = PE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006671 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006672
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006673 ReplaceStmtWithRange(IV, Replacement, OldRange);
6674 return Replacement;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006675}