blob: c4f721f8c29f500c640e924ec8cb9ff3f4f1ab54 [file] [log] [blame]
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Rewrite/ASTConsumers.h"
15#include "clang/Rewrite/Rewriter.h"
16#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ParentMap.h"
19#include "clang/Basic/SourceManager.h"
20#include "clang/Basic/IdentifierTable.h"
21#include "clang/Basic/Diagnostic.h"
22#include "clang/Lex/Lexer.h"
23#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
25#include "llvm/ADT/StringExtras.h"
26#include "llvm/ADT/SmallPtrSet.h"
27#include "llvm/ADT/OwningPtr.h"
28#include "llvm/ADT/DenseSet.h"
29
30using namespace clang;
31using llvm::utostr;
32
33namespace {
34 class RewriteModernObjC : public ASTConsumer {
35 protected:
36
37 enum {
38 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
39 block, ... */
40 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
41 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
42 __block variable */
43 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
44 helpers */
45 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
46 support routines */
47 BLOCK_BYREF_CURRENT_MAX = 256
48 };
49
50 enum {
51 BLOCK_NEEDS_FREE = (1 << 24),
52 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
53 BLOCK_HAS_CXX_OBJ = (1 << 26),
54 BLOCK_IS_GC = (1 << 27),
55 BLOCK_IS_GLOBAL = (1 << 28),
56 BLOCK_HAS_DESCRIPTOR = (1 << 29)
57 };
58 static const int OBJC_ABI_VERSION = 7;
59
60 Rewriter Rewrite;
61 DiagnosticsEngine &Diags;
62 const LangOptions &LangOpts;
63 ASTContext *Context;
64 SourceManager *SM;
65 TranslationUnitDecl *TUDecl;
66 FileID MainFileID;
67 const char *MainFileStart, *MainFileEnd;
68 Stmt *CurrentBody;
69 ParentMap *PropParentMap; // created lazily.
70 std::string InFileName;
71 raw_ostream* OutFile;
72 std::string Preamble;
73
74 TypeDecl *ProtocolTypeDecl;
75 VarDecl *GlobalVarDecl;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +000076 Expr *GlobalConstructionExp;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000077 unsigned RewriteFailedDiag;
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +000078 unsigned GlobalBlockRewriteFailedDiag;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000079 // ObjC string constant support.
80 unsigned NumObjCStringLiterals;
81 VarDecl *ConstantStringClassReference;
82 RecordDecl *NSStringRecord;
83
84 // ObjC foreach break/continue generation support.
85 int BcLabelCount;
86
87 unsigned TryFinallyContainsReturnDiag;
88 // Needed for super.
89 ObjCMethodDecl *CurMethodDef;
90 RecordDecl *SuperStructDecl;
91 RecordDecl *ConstantStringDecl;
92
93 FunctionDecl *MsgSendFunctionDecl;
94 FunctionDecl *MsgSendSuperFunctionDecl;
95 FunctionDecl *MsgSendStretFunctionDecl;
96 FunctionDecl *MsgSendSuperStretFunctionDecl;
97 FunctionDecl *MsgSendFpretFunctionDecl;
98 FunctionDecl *GetClassFunctionDecl;
99 FunctionDecl *GetMetaClassFunctionDecl;
100 FunctionDecl *GetSuperClassFunctionDecl;
101 FunctionDecl *SelGetUidFunctionDecl;
102 FunctionDecl *CFStringFunctionDecl;
103 FunctionDecl *SuperContructorFunctionDecl;
104 FunctionDecl *CurFunctionDef;
105 FunctionDecl *CurFunctionDeclToDeclareForBlock;
106
107 /* Misc. containers needed for meta-data rewrite. */
108 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
109 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
110 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
111 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000112 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000113 llvm::SmallPtrSet<TagDecl*, 8> TagsDefinedInIvarDecls;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000114 SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000115 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
116 SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
117
118 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
119 llvm::SmallVector<ObjCCategoryDecl*, 8> DefinedNonLazyCategories;
120
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000121 SmallVector<Stmt *, 32> Stmts;
122 SmallVector<int, 8> ObjCBcLabelNo;
123 // Remember all the @protocol(<expr>) expressions.
124 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
125
126 llvm::DenseSet<uint64_t> CopyDestroyCache;
127
128 // Block expressions.
129 SmallVector<BlockExpr *, 32> Blocks;
130 SmallVector<int, 32> InnerDeclRefsCount;
John McCallf4b88a42012-03-10 09:33:50 +0000131 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000132
John McCallf4b88a42012-03-10 09:33:50 +0000133 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000134
135 // Block related declarations.
136 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
137 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
138 SmallVector<ValueDecl *, 8> BlockByRefDecls;
139 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
140 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
141 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
142 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
143
144 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000145 llvm::DenseMap<ObjCInterfaceDecl *,
146 llvm::SmallPtrSet<ObjCIvarDecl *, 8> > ReferencedIvars;
147
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000148 // This maps an original source AST to it's rewritten form. This allows
149 // us to avoid rewriting the same node twice (which is very uncommon).
150 // This is needed to support some of the exotic property rewriting.
151 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
152
153 // Needed for header files being rewritten
154 bool IsHeader;
155 bool SilenceRewriteMacroWarning;
156 bool objc_impl_method;
157
158 bool DisableReplaceStmt;
159 class DisableReplaceStmtScope {
160 RewriteModernObjC &R;
161 bool SavedValue;
162
163 public:
164 DisableReplaceStmtScope(RewriteModernObjC &R)
165 : R(R), SavedValue(R.DisableReplaceStmt) {
166 R.DisableReplaceStmt = true;
167 }
168 ~DisableReplaceStmtScope() {
169 R.DisableReplaceStmt = SavedValue;
170 }
171 };
172 void InitializeCommon(ASTContext &context);
173
174 public:
Fariborz Jahanian90af4e22012-02-14 17:19:02 +0000175 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000176 // Top Level Driver code.
177 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
178 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
179 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
180 if (!Class->isThisDeclarationADefinition()) {
181 RewriteForwardClassDecl(D);
182 break;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000183 } else {
184 // Keep track of all interface declarations seen.
Fariborz Jahanianf3295272012-02-24 21:42:38 +0000185 ObjCInterfacesSeen.push_back(Class);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000186 break;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000187 }
188 }
189
190 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
191 if (!Proto->isThisDeclarationADefinition()) {
192 RewriteForwardProtocolDecl(D);
193 break;
194 }
195 }
196
197 HandleTopLevelSingleDecl(*I);
198 }
199 return true;
200 }
201 void HandleTopLevelSingleDecl(Decl *D);
202 void HandleDeclInMainFile(Decl *D);
203 RewriteModernObjC(std::string inFile, raw_ostream *OS,
204 DiagnosticsEngine &D, const LangOptions &LOpts,
205 bool silenceMacroWarn);
206
207 ~RewriteModernObjC() {}
208
209 virtual void HandleTranslationUnit(ASTContext &C);
210
211 void ReplaceStmt(Stmt *Old, Stmt *New) {
212 Stmt *ReplacingStmt = ReplacedNodes[Old];
213
214 if (ReplacingStmt)
215 return; // We can't rewrite the same node twice.
216
217 if (DisableReplaceStmt)
218 return;
219
220 // If replacement succeeded or warning disabled return with no warning.
221 if (!Rewrite.ReplaceStmt(Old, New)) {
222 ReplacedNodes[Old] = New;
223 return;
224 }
225 if (SilenceRewriteMacroWarning)
226 return;
227 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
228 << Old->getSourceRange();
229 }
230
231 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
232 if (DisableReplaceStmt)
233 return;
234
235 // Measure the old text.
236 int Size = Rewrite.getRangeSize(SrcRange);
237 if (Size == -1) {
238 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
239 << Old->getSourceRange();
240 return;
241 }
242 // Get the new text.
243 std::string SStr;
244 llvm::raw_string_ostream S(SStr);
245 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
246 const std::string &Str = S.str();
247
248 // If replacement succeeded or warning disabled return with no warning.
249 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
250 ReplacedNodes[Old] = New;
251 return;
252 }
253 if (SilenceRewriteMacroWarning)
254 return;
255 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
256 << Old->getSourceRange();
257 }
258
259 void InsertText(SourceLocation Loc, StringRef Str,
260 bool InsertAfter = true) {
261 // If insertion succeeded or warning disabled return with no warning.
262 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
263 SilenceRewriteMacroWarning)
264 return;
265
266 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
267 }
268
269 void ReplaceText(SourceLocation Start, unsigned OrigLength,
270 StringRef Str) {
271 // If removal succeeded or warning disabled return with no warning.
272 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
273 SilenceRewriteMacroWarning)
274 return;
275
276 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
277 }
278
279 // Syntactic Rewriting.
280 void RewriteRecordBody(RecordDecl *RD);
281 void RewriteInclude();
282 void RewriteForwardClassDecl(DeclGroupRef D);
283 void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG);
284 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
285 const std::string &typedefString);
286 void RewriteImplementations();
287 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
288 ObjCImplementationDecl *IMD,
289 ObjCCategoryImplDecl *CID);
290 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
291 void RewriteImplementationDecl(Decl *Dcl);
292 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
293 ObjCMethodDecl *MDecl, std::string &ResultStr);
294 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
295 const FunctionType *&FPRetType);
296 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
297 ValueDecl *VD, bool def=false);
298 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
299 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
300 void RewriteForwardProtocolDecl(DeclGroupRef D);
301 void RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG);
302 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
303 void RewriteProperty(ObjCPropertyDecl *prop);
304 void RewriteFunctionDecl(FunctionDecl *FD);
305 void RewriteBlockPointerType(std::string& Str, QualType Type);
306 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
307 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
308 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
309 void RewriteTypeOfDecl(VarDecl *VD);
310 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
311
312 // Expression Rewriting.
313 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
314 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
315 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
316 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
317 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
318 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
319 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
320 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000321 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
322 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
323 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
324 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
325 SourceLocation OrigEnd);
326 Stmt *RewriteBreakStmt(BreakStmt *S);
327 Stmt *RewriteContinueStmt(ContinueStmt *S);
328 void RewriteCastExpr(CStyleCastExpr *CE);
329
330 // Block rewriting.
331 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
332
333 // Block specific rewrite rules.
334 void RewriteBlockPointerDecl(NamedDecl *VD);
335 void RewriteByRefVar(VarDecl *VD);
John McCallf4b88a42012-03-10 09:33:50 +0000336 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000337 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
338 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
339
340 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
341 std::string &Result);
342
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000343 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
344
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +0000345 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
346
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000347 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
348 std::string &Result);
349
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000350 virtual void Initialize(ASTContext &context);
351
352 // Misc. AST transformation routines. Somtimes they end up calling
353 // rewriting routines on the new ASTs.
354 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
355 Expr **args, unsigned nargs,
356 SourceLocation StartLoc=SourceLocation(),
357 SourceLocation EndLoc=SourceLocation());
358
359 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
360 SourceLocation StartLoc=SourceLocation(),
361 SourceLocation EndLoc=SourceLocation());
362
363 void SynthCountByEnumWithState(std::string &buf);
364 void SynthMsgSendFunctionDecl();
365 void SynthMsgSendSuperFunctionDecl();
366 void SynthMsgSendStretFunctionDecl();
367 void SynthMsgSendFpretFunctionDecl();
368 void SynthMsgSendSuperStretFunctionDecl();
369 void SynthGetClassFunctionDecl();
370 void SynthGetMetaClassFunctionDecl();
371 void SynthGetSuperClassFunctionDecl();
372 void SynthSelGetUidFunctionDecl();
373 void SynthSuperContructorFunctionDecl();
374
375 // Rewriting metadata
376 template<typename MethodIterator>
377 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
378 MethodIterator MethodEnd,
379 bool IsInstanceMethod,
380 StringRef prefix,
381 StringRef ClassName,
382 std::string &Result);
Fariborz Jahanianda9624a2012-02-08 19:53:58 +0000383 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
384 std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000385 virtual void RewriteObjCProtocolListMetaData(
386 const ObjCList<ObjCProtocolDecl> &Prots,
387 StringRef prefix, StringRef ClassName, std::string &Result);
388 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
389 std::string &Result);
390 virtual void RewriteMetaDataIntoBuffer(std::string &Result);
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +0000391 virtual void WriteImageInfo(std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000392 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
393 std::string &Result);
394
395 // Rewriting ivar
396 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
397 std::string &Result);
398 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
399
400
401 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
402 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
403 StringRef funcName, std::string Tag);
404 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
405 StringRef funcName, std::string Tag);
406 std::string SynthesizeBlockImpl(BlockExpr *CE,
407 std::string Tag, std::string Desc);
408 std::string SynthesizeBlockDescriptor(std::string DescTag,
409 std::string ImplTag,
410 int i, StringRef funcName,
411 unsigned hasCopy);
412 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
413 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
414 StringRef FunName);
415 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
416 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +0000417 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000418
419 // Misc. helper routines.
420 QualType getProtocolType();
421 void WarnAboutReturnGotoStmts(Stmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000422 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
423 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
424 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
425
426 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
427 void CollectBlockDeclRefInfo(BlockExpr *Exp);
428 void GetBlockDeclRefExprs(Stmt *S);
429 void GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +0000430 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000431 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
432
433 // We avoid calling Type::isBlockPointerType(), since it operates on the
434 // canonical type. We only care if the top-level type is a closure pointer.
435 bool isTopLevelBlockPointerType(QualType T) {
436 return isa<BlockPointerType>(T);
437 }
438
439 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
440 /// to a function pointer type and upon success, returns true; false
441 /// otherwise.
442 bool convertBlockPointerToFunctionPointer(QualType &T) {
443 if (isTopLevelBlockPointerType(T)) {
444 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
445 T = Context->getPointerType(BPT->getPointeeType());
446 return true;
447 }
448 return false;
449 }
450
Fariborz Jahanian164d6f82012-02-13 18:57:49 +0000451 bool convertObjCTypeToCStyleType(QualType &T);
452
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000453 bool needToScanForQualifiers(QualType T);
454 QualType getSuperStructType();
455 QualType getConstantStringStructType();
456 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
457 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
458
459 void convertToUnqualifiedObjCType(QualType &T) {
460 if (T->isObjCQualifiedIdType())
461 T = Context->getObjCIdType();
462 else if (T->isObjCQualifiedClassType())
463 T = Context->getObjCClassType();
464 else if (T->isObjCObjectPointerType() &&
465 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
466 if (const ObjCObjectPointerType * OBJPT =
467 T->getAsObjCInterfacePointerType()) {
468 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
469 T = QualType(IFaceT, 0);
470 T = Context->getPointerType(T);
471 }
472 }
473 }
474
475 // FIXME: This predicate seems like it would be useful to add to ASTContext.
476 bool isObjCType(QualType T) {
477 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
478 return false;
479
480 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
481
482 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
483 OCT == Context->getCanonicalType(Context->getObjCClassType()))
484 return true;
485
486 if (const PointerType *PT = OCT->getAs<PointerType>()) {
487 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
488 PT->getPointeeType()->isObjCQualifiedIdType())
489 return true;
490 }
491 return false;
492 }
493 bool PointerTypeTakesAnyBlockArguments(QualType QT);
494 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
495 void GetExtentOfArgList(const char *Name, const char *&LParen,
496 const char *&RParen);
497
498 void QuoteDoublequotes(std::string &From, std::string &To) {
499 for (unsigned i = 0; i < From.length(); i++) {
500 if (From[i] == '"')
501 To += "\\\"";
502 else
503 To += From[i];
504 }
505 }
506
507 QualType getSimpleFunctionType(QualType result,
508 const QualType *args,
509 unsigned numArgs,
510 bool variadic = false) {
511 if (result == Context->getObjCInstanceType())
512 result = Context->getObjCIdType();
513 FunctionProtoType::ExtProtoInfo fpi;
514 fpi.Variadic = variadic;
515 return Context->getFunctionType(result, args, numArgs, fpi);
516 }
517
518 // Helper function: create a CStyleCastExpr with trivial type source info.
519 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
520 CastKind Kind, Expr *E) {
521 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
522 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
523 SourceLocation(), SourceLocation());
524 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000525
526 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
527 IdentifierInfo* II = &Context->Idents.get("load");
528 Selector LoadSel = Context->Selectors.getSelector(0, &II);
529 return OD->getClassMethod(LoadSel) != 0;
530 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000531 };
532
533}
534
535void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
536 NamedDecl *D) {
537 if (const FunctionProtoType *fproto
538 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
539 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
540 E = fproto->arg_type_end(); I && (I != E); ++I)
541 if (isTopLevelBlockPointerType(*I)) {
542 // All the args are checked/rewritten. Don't call twice!
543 RewriteBlockPointerDecl(D);
544 break;
545 }
546 }
547}
548
549void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
550 const PointerType *PT = funcType->getAs<PointerType>();
551 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
552 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
553}
554
555static bool IsHeaderFile(const std::string &Filename) {
556 std::string::size_type DotPos = Filename.rfind('.');
557
558 if (DotPos == std::string::npos) {
559 // no file extension
560 return false;
561 }
562
563 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
564 // C header: .h
565 // C++ header: .hh or .H;
566 return Ext == "h" || Ext == "hh" || Ext == "H";
567}
568
569RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
570 DiagnosticsEngine &D, const LangOptions &LOpts,
571 bool silenceMacroWarn)
572 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
573 SilenceRewriteMacroWarning(silenceMacroWarn) {
574 IsHeader = IsHeaderFile(inFile);
575 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
576 "rewriting sub-expression within a macro (may not be correct)");
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +0000577 // FIXME. This should be an error. But if block is not called, it is OK. And it
578 // may break including some headers.
579 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
580 "rewriting block literal declared in global scope is not implemented");
581
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000582 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
583 DiagnosticsEngine::Warning,
584 "rewriter doesn't support user-specified control flow semantics "
585 "for @try/@finally (code may not execute properly)");
586}
587
588ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
589 raw_ostream* OS,
590 DiagnosticsEngine &Diags,
591 const LangOptions &LOpts,
592 bool SilenceRewriteMacroWarning) {
593 return new RewriteModernObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
594}
595
596void RewriteModernObjC::InitializeCommon(ASTContext &context) {
597 Context = &context;
598 SM = &Context->getSourceManager();
599 TUDecl = Context->getTranslationUnitDecl();
600 MsgSendFunctionDecl = 0;
601 MsgSendSuperFunctionDecl = 0;
602 MsgSendStretFunctionDecl = 0;
603 MsgSendSuperStretFunctionDecl = 0;
604 MsgSendFpretFunctionDecl = 0;
605 GetClassFunctionDecl = 0;
606 GetMetaClassFunctionDecl = 0;
607 GetSuperClassFunctionDecl = 0;
608 SelGetUidFunctionDecl = 0;
609 CFStringFunctionDecl = 0;
610 ConstantStringClassReference = 0;
611 NSStringRecord = 0;
612 CurMethodDef = 0;
613 CurFunctionDef = 0;
614 CurFunctionDeclToDeclareForBlock = 0;
615 GlobalVarDecl = 0;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +0000616 GlobalConstructionExp = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000617 SuperStructDecl = 0;
618 ProtocolTypeDecl = 0;
619 ConstantStringDecl = 0;
620 BcLabelCount = 0;
621 SuperContructorFunctionDecl = 0;
622 NumObjCStringLiterals = 0;
623 PropParentMap = 0;
624 CurrentBody = 0;
625 DisableReplaceStmt = false;
626 objc_impl_method = false;
627
628 // Get the ID and start/end of the main file.
629 MainFileID = SM->getMainFileID();
630 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
631 MainFileStart = MainBuf->getBufferStart();
632 MainFileEnd = MainBuf->getBufferEnd();
633
David Blaikie4e4d0842012-03-11 07:00:24 +0000634 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000635}
636
637//===----------------------------------------------------------------------===//
638// Top Level Driver Code
639//===----------------------------------------------------------------------===//
640
641void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
642 if (Diags.hasErrorOccurred())
643 return;
644
645 // Two cases: either the decl could be in the main file, or it could be in a
646 // #included file. If the former, rewrite it now. If the later, check to see
647 // if we rewrote the #include/#import.
648 SourceLocation Loc = D->getLocation();
649 Loc = SM->getExpansionLoc(Loc);
650
651 // If this is for a builtin, ignore it.
652 if (Loc.isInvalid()) return;
653
654 // Look for built-in declarations that we need to refer during the rewrite.
655 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
656 RewriteFunctionDecl(FD);
657 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
658 // declared in <Foundation/NSString.h>
659 if (FVD->getName() == "_NSConstantStringClassReference") {
660 ConstantStringClassReference = FVD;
661 return;
662 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000663 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
664 RewriteCategoryDecl(CD);
665 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
666 if (PD->isThisDeclarationADefinition())
667 RewriteProtocolDecl(PD);
668 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
669 // Recurse into linkage specifications
670 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
671 DIEnd = LSD->decls_end();
672 DI != DIEnd; ) {
673 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
674 if (!IFace->isThisDeclarationADefinition()) {
675 SmallVector<Decl *, 8> DG;
676 SourceLocation StartLoc = IFace->getLocStart();
677 do {
678 if (isa<ObjCInterfaceDecl>(*DI) &&
679 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
680 StartLoc == (*DI)->getLocStart())
681 DG.push_back(*DI);
682 else
683 break;
684
685 ++DI;
686 } while (DI != DIEnd);
687 RewriteForwardClassDecl(DG);
688 continue;
689 }
690 }
691
692 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
693 if (!Proto->isThisDeclarationADefinition()) {
694 SmallVector<Decl *, 8> DG;
695 SourceLocation StartLoc = Proto->getLocStart();
696 do {
697 if (isa<ObjCProtocolDecl>(*DI) &&
698 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
699 StartLoc == (*DI)->getLocStart())
700 DG.push_back(*DI);
701 else
702 break;
703
704 ++DI;
705 } while (DI != DIEnd);
706 RewriteForwardProtocolDecl(DG);
707 continue;
708 }
709 }
710
711 HandleTopLevelSingleDecl(*DI);
712 ++DI;
713 }
714 }
715 // If we have a decl in the main file, see if we should rewrite it.
716 if (SM->isFromMainFile(Loc))
717 return HandleDeclInMainFile(D);
718}
719
720//===----------------------------------------------------------------------===//
721// Syntactic (non-AST) Rewriting Code
722//===----------------------------------------------------------------------===//
723
724void RewriteModernObjC::RewriteInclude() {
725 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
726 StringRef MainBuf = SM->getBufferData(MainFileID);
727 const char *MainBufStart = MainBuf.begin();
728 const char *MainBufEnd = MainBuf.end();
729 size_t ImportLen = strlen("import");
730
731 // Loop over the whole file, looking for includes.
732 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
733 if (*BufPtr == '#') {
734 if (++BufPtr == MainBufEnd)
735 return;
736 while (*BufPtr == ' ' || *BufPtr == '\t')
737 if (++BufPtr == MainBufEnd)
738 return;
739 if (!strncmp(BufPtr, "import", ImportLen)) {
740 // replace import with include
741 SourceLocation ImportLoc =
742 LocStart.getLocWithOffset(BufPtr-MainBufStart);
743 ReplaceText(ImportLoc, ImportLen, "include");
744 BufPtr += ImportLen;
745 }
746 }
747 }
748}
749
750static std::string getIvarAccessString(ObjCIvarDecl *OID) {
751 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
752 std::string S;
753 S = "((struct ";
754 S += ClassDecl->getIdentifier()->getName();
755 S += "_IMPL *)self)->";
756 S += OID->getName();
757 return S;
758}
759
760void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
761 ObjCImplementationDecl *IMD,
762 ObjCCategoryImplDecl *CID) {
763 static bool objcGetPropertyDefined = false;
764 static bool objcSetPropertyDefined = false;
765 SourceLocation startLoc = PID->getLocStart();
766 InsertText(startLoc, "// ");
767 const char *startBuf = SM->getCharacterData(startLoc);
768 assert((*startBuf == '@') && "bogus @synthesize location");
769 const char *semiBuf = strchr(startBuf, ';');
770 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
771 SourceLocation onePastSemiLoc =
772 startLoc.getLocWithOffset(semiBuf-startBuf+1);
773
774 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
775 return; // FIXME: is this correct?
776
777 // Generate the 'getter' function.
778 ObjCPropertyDecl *PD = PID->getPropertyDecl();
779 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
780
781 if (!OID)
782 return;
783 unsigned Attributes = PD->getPropertyAttributes();
784 if (!PD->getGetterMethodDecl()->isDefined()) {
785 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
786 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
787 ObjCPropertyDecl::OBJC_PR_copy));
788 std::string Getr;
789 if (GenGetProperty && !objcGetPropertyDefined) {
790 objcGetPropertyDefined = true;
791 // FIXME. Is this attribute correct in all cases?
792 Getr = "\nextern \"C\" __declspec(dllimport) "
793 "id objc_getProperty(id, SEL, long, bool);\n";
794 }
795 RewriteObjCMethodDecl(OID->getContainingInterface(),
796 PD->getGetterMethodDecl(), Getr);
797 Getr += "{ ";
798 // Synthesize an explicit cast to gain access to the ivar.
799 // See objc-act.c:objc_synthesize_new_getter() for details.
800 if (GenGetProperty) {
801 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
802 Getr += "typedef ";
803 const FunctionType *FPRetType = 0;
804 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
805 FPRetType);
806 Getr += " _TYPE";
807 if (FPRetType) {
808 Getr += ")"; // close the precedence "scope" for "*".
809
810 // Now, emit the argument types (if any).
811 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
812 Getr += "(";
813 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
814 if (i) Getr += ", ";
815 std::string ParamStr = FT->getArgType(i).getAsString(
816 Context->getPrintingPolicy());
817 Getr += ParamStr;
818 }
819 if (FT->isVariadic()) {
820 if (FT->getNumArgs()) Getr += ", ";
821 Getr += "...";
822 }
823 Getr += ")";
824 } else
825 Getr += "()";
826 }
827 Getr += ";\n";
828 Getr += "return (_TYPE)";
829 Getr += "objc_getProperty(self, _cmd, ";
830 RewriteIvarOffsetComputation(OID, Getr);
831 Getr += ", 1)";
832 }
833 else
834 Getr += "return " + getIvarAccessString(OID);
835 Getr += "; }";
836 InsertText(onePastSemiLoc, Getr);
837 }
838
839 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
840 return;
841
842 // Generate the 'setter' function.
843 std::string Setr;
844 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
845 ObjCPropertyDecl::OBJC_PR_copy);
846 if (GenSetProperty && !objcSetPropertyDefined) {
847 objcSetPropertyDefined = true;
848 // FIXME. Is this attribute correct in all cases?
849 Setr = "\nextern \"C\" __declspec(dllimport) "
850 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
851 }
852
853 RewriteObjCMethodDecl(OID->getContainingInterface(),
854 PD->getSetterMethodDecl(), Setr);
855 Setr += "{ ";
856 // Synthesize an explicit cast to initialize the ivar.
857 // See objc-act.c:objc_synthesize_new_setter() for details.
858 if (GenSetProperty) {
859 Setr += "objc_setProperty (self, _cmd, ";
860 RewriteIvarOffsetComputation(OID, Setr);
861 Setr += ", (id)";
862 Setr += PD->getName();
863 Setr += ", ";
864 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
865 Setr += "0, ";
866 else
867 Setr += "1, ";
868 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
869 Setr += "1)";
870 else
871 Setr += "0)";
872 }
873 else {
874 Setr += getIvarAccessString(OID) + " = ";
875 Setr += PD->getName();
876 }
877 Setr += "; }";
878 InsertText(onePastSemiLoc, Setr);
879}
880
881static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
882 std::string &typedefString) {
883 typedefString += "#ifndef _REWRITER_typedef_";
884 typedefString += ForwardDecl->getNameAsString();
885 typedefString += "\n";
886 typedefString += "#define _REWRITER_typedef_";
887 typedefString += ForwardDecl->getNameAsString();
888 typedefString += "\n";
889 typedefString += "typedef struct objc_object ";
890 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +0000891 // typedef struct { } _objc_exc_Classname;
892 typedefString += ";\ntypedef struct {} _objc_exc_";
893 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000894 typedefString += ";\n#endif\n";
895}
896
897void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
898 const std::string &typedefString) {
899 SourceLocation startLoc = ClassDecl->getLocStart();
900 const char *startBuf = SM->getCharacterData(startLoc);
901 const char *semiPtr = strchr(startBuf, ';');
902 // Replace the @class with typedefs corresponding to the classes.
903 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
904}
905
906void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
907 std::string typedefString;
908 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
909 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
910 if (I == D.begin()) {
911 // Translate to typedef's that forward reference structs with the same name
912 // as the class. As a convenience, we include the original declaration
913 // as a comment.
914 typedefString += "// @class ";
915 typedefString += ForwardDecl->getNameAsString();
916 typedefString += ";\n";
917 }
918 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
919 }
920 DeclGroupRef::iterator I = D.begin();
921 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
922}
923
924void RewriteModernObjC::RewriteForwardClassDecl(
925 const llvm::SmallVector<Decl*, 8> &D) {
926 std::string typedefString;
927 for (unsigned i = 0; i < D.size(); i++) {
928 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
929 if (i == 0) {
930 typedefString += "// @class ";
931 typedefString += ForwardDecl->getNameAsString();
932 typedefString += ";\n";
933 }
934 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
935 }
936 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
937}
938
939void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
940 // When method is a synthesized one, such as a getter/setter there is
941 // nothing to rewrite.
942 if (Method->isImplicit())
943 return;
944 SourceLocation LocStart = Method->getLocStart();
945 SourceLocation LocEnd = Method->getLocEnd();
946
947 if (SM->getExpansionLineNumber(LocEnd) >
948 SM->getExpansionLineNumber(LocStart)) {
949 InsertText(LocStart, "#if 0\n");
950 ReplaceText(LocEnd, 1, ";\n#endif\n");
951 } else {
952 InsertText(LocStart, "// ");
953 }
954}
955
956void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
957 SourceLocation Loc = prop->getAtLoc();
958
959 ReplaceText(Loc, 0, "// ");
960 // FIXME: handle properties that are declared across multiple lines.
961}
962
963void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
964 SourceLocation LocStart = CatDecl->getLocStart();
965
966 // FIXME: handle category headers that are declared across multiple lines.
967 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianaf300292012-02-20 20:09:20 +0000968 if (CatDecl->getIvarLBraceLoc().isValid())
969 InsertText(CatDecl->getIvarLBraceLoc(), "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +0000970 for (ObjCCategoryDecl::ivar_iterator
971 I = CatDecl->ivar_begin(), E = CatDecl->ivar_end(); I != E; ++I) {
972 ObjCIvarDecl *Ivar = (*I);
973 SourceLocation LocStart = Ivar->getLocStart();
974 ReplaceText(LocStart, 0, "// ");
975 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +0000976 if (CatDecl->getIvarRBraceLoc().isValid())
977 InsertText(CatDecl->getIvarRBraceLoc(), "// ");
978
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000979 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
980 E = CatDecl->prop_end(); I != E; ++I)
981 RewriteProperty(*I);
982
983 for (ObjCCategoryDecl::instmeth_iterator
984 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
985 I != E; ++I)
986 RewriteMethodDeclaration(*I);
987 for (ObjCCategoryDecl::classmeth_iterator
988 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
989 I != E; ++I)
990 RewriteMethodDeclaration(*I);
991
992 // Lastly, comment out the @end.
993 ReplaceText(CatDecl->getAtEndRange().getBegin(),
994 strlen("@end"), "/* @end */");
995}
996
997void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
998 SourceLocation LocStart = PDecl->getLocStart();
999 assert(PDecl->isThisDeclarationADefinition());
1000
1001 // FIXME: handle protocol headers that are declared across multiple lines.
1002 ReplaceText(LocStart, 0, "// ");
1003
1004 for (ObjCProtocolDecl::instmeth_iterator
1005 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
1006 I != E; ++I)
1007 RewriteMethodDeclaration(*I);
1008 for (ObjCProtocolDecl::classmeth_iterator
1009 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1010 I != E; ++I)
1011 RewriteMethodDeclaration(*I);
1012
1013 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1014 E = PDecl->prop_end(); I != E; ++I)
1015 RewriteProperty(*I);
1016
1017 // Lastly, comment out the @end.
1018 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1019 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
1020
1021 // Must comment out @optional/@required
1022 const char *startBuf = SM->getCharacterData(LocStart);
1023 const char *endBuf = SM->getCharacterData(LocEnd);
1024 for (const char *p = startBuf; p < endBuf; p++) {
1025 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1026 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1027 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1028
1029 }
1030 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1031 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1032 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1033
1034 }
1035 }
1036}
1037
1038void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1039 SourceLocation LocStart = (*D.begin())->getLocStart();
1040 if (LocStart.isInvalid())
1041 llvm_unreachable("Invalid SourceLocation");
1042 // FIXME: handle forward protocol that are declared across multiple lines.
1043 ReplaceText(LocStart, 0, "// ");
1044}
1045
1046void
1047RewriteModernObjC::RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG) {
1048 SourceLocation LocStart = DG[0]->getLocStart();
1049 if (LocStart.isInvalid())
1050 llvm_unreachable("Invalid SourceLocation");
1051 // FIXME: handle forward protocol that are declared across multiple lines.
1052 ReplaceText(LocStart, 0, "// ");
1053}
1054
1055void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1056 const FunctionType *&FPRetType) {
1057 if (T->isObjCQualifiedIdType())
1058 ResultStr += "id";
1059 else if (T->isFunctionPointerType() ||
1060 T->isBlockPointerType()) {
1061 // needs special handling, since pointer-to-functions have special
1062 // syntax (where a decaration models use).
1063 QualType retType = T;
1064 QualType PointeeTy;
1065 if (const PointerType* PT = retType->getAs<PointerType>())
1066 PointeeTy = PT->getPointeeType();
1067 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1068 PointeeTy = BPT->getPointeeType();
1069 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1070 ResultStr += FPRetType->getResultType().getAsString(
1071 Context->getPrintingPolicy());
1072 ResultStr += "(*";
1073 }
1074 } else
1075 ResultStr += T.getAsString(Context->getPrintingPolicy());
1076}
1077
1078void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1079 ObjCMethodDecl *OMD,
1080 std::string &ResultStr) {
1081 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1082 const FunctionType *FPRetType = 0;
1083 ResultStr += "\nstatic ";
1084 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1085 ResultStr += " ";
1086
1087 // Unique method name
1088 std::string NameStr;
1089
1090 if (OMD->isInstanceMethod())
1091 NameStr += "_I_";
1092 else
1093 NameStr += "_C_";
1094
1095 NameStr += IDecl->getNameAsString();
1096 NameStr += "_";
1097
1098 if (ObjCCategoryImplDecl *CID =
1099 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1100 NameStr += CID->getNameAsString();
1101 NameStr += "_";
1102 }
1103 // Append selector names, replacing ':' with '_'
1104 {
1105 std::string selString = OMD->getSelector().getAsString();
1106 int len = selString.size();
1107 for (int i = 0; i < len; i++)
1108 if (selString[i] == ':')
1109 selString[i] = '_';
1110 NameStr += selString;
1111 }
1112 // Remember this name for metadata emission
1113 MethodInternalNames[OMD] = NameStr;
1114 ResultStr += NameStr;
1115
1116 // Rewrite arguments
1117 ResultStr += "(";
1118
1119 // invisible arguments
1120 if (OMD->isInstanceMethod()) {
1121 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1122 selfTy = Context->getPointerType(selfTy);
1123 if (!LangOpts.MicrosoftExt) {
1124 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1125 ResultStr += "struct ";
1126 }
1127 // When rewriting for Microsoft, explicitly omit the structure name.
1128 ResultStr += IDecl->getNameAsString();
1129 ResultStr += " *";
1130 }
1131 else
1132 ResultStr += Context->getObjCClassType().getAsString(
1133 Context->getPrintingPolicy());
1134
1135 ResultStr += " self, ";
1136 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1137 ResultStr += " _cmd";
1138
1139 // Method arguments.
1140 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1141 E = OMD->param_end(); PI != E; ++PI) {
1142 ParmVarDecl *PDecl = *PI;
1143 ResultStr += ", ";
1144 if (PDecl->getType()->isObjCQualifiedIdType()) {
1145 ResultStr += "id ";
1146 ResultStr += PDecl->getNameAsString();
1147 } else {
1148 std::string Name = PDecl->getNameAsString();
1149 QualType QT = PDecl->getType();
1150 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1151 if (convertBlockPointerToFunctionPointer(QT))
1152 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
1153 else
1154 PDecl->getType().getAsStringInternal(Name, Context->getPrintingPolicy());
1155 ResultStr += Name;
1156 }
1157 }
1158 if (OMD->isVariadic())
1159 ResultStr += ", ...";
1160 ResultStr += ") ";
1161
1162 if (FPRetType) {
1163 ResultStr += ")"; // close the precedence "scope" for "*".
1164
1165 // Now, emit the argument types (if any).
1166 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1167 ResultStr += "(";
1168 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1169 if (i) ResultStr += ", ";
1170 std::string ParamStr = FT->getArgType(i).getAsString(
1171 Context->getPrintingPolicy());
1172 ResultStr += ParamStr;
1173 }
1174 if (FT->isVariadic()) {
1175 if (FT->getNumArgs()) ResultStr += ", ";
1176 ResultStr += "...";
1177 }
1178 ResultStr += ")";
1179 } else {
1180 ResultStr += "()";
1181 }
1182 }
1183}
1184void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1185 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1186 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1187
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001188 if (IMD) {
1189 InsertText(IMD->getLocStart(), "// ");
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001190 if (IMD->getIvarLBraceLoc().isValid())
1191 InsertText(IMD->getIvarLBraceLoc(), "// ");
1192 for (ObjCImplementationDecl::ivar_iterator
1193 I = IMD->ivar_begin(), E = IMD->ivar_end(); I != E; ++I) {
1194 ObjCIvarDecl *Ivar = (*I);
1195 SourceLocation LocStart = Ivar->getLocStart();
1196 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001197 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001198 if (IMD->getIvarRBraceLoc().isValid())
1199 InsertText(IMD->getIvarRBraceLoc(), "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001200 }
1201 else
1202 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001203
1204 for (ObjCCategoryImplDecl::instmeth_iterator
1205 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1206 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1207 I != E; ++I) {
1208 std::string ResultStr;
1209 ObjCMethodDecl *OMD = *I;
1210 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1211 SourceLocation LocStart = OMD->getLocStart();
1212 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1213
1214 const char *startBuf = SM->getCharacterData(LocStart);
1215 const char *endBuf = SM->getCharacterData(LocEnd);
1216 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1217 }
1218
1219 for (ObjCCategoryImplDecl::classmeth_iterator
1220 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1221 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1222 I != E; ++I) {
1223 std::string ResultStr;
1224 ObjCMethodDecl *OMD = *I;
1225 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1226 SourceLocation LocStart = OMD->getLocStart();
1227 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1228
1229 const char *startBuf = SM->getCharacterData(LocStart);
1230 const char *endBuf = SM->getCharacterData(LocEnd);
1231 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1232 }
1233 for (ObjCCategoryImplDecl::propimpl_iterator
1234 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1235 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1236 I != E; ++I) {
1237 RewritePropertyImplDecl(*I, IMD, CID);
1238 }
1239
1240 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1241}
1242
1243void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00001244 // Do not synthesize more than once.
1245 if (ObjCSynthesizedStructs.count(ClassDecl))
1246 return;
1247 // Make sure super class's are written before current class is written.
1248 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1249 while (SuperClass) {
1250 RewriteInterfaceDecl(SuperClass);
1251 SuperClass = SuperClass->getSuperClass();
1252 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001253 std::string ResultStr;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001254 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001255 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001256 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00001257 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1258
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001259 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001260 // Mark this typedef as having been written into its c++ equivalent.
1261 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001262
1263 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001264 E = ClassDecl->prop_end(); I != E; ++I)
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001265 RewriteProperty(*I);
1266 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001267 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001268 I != E; ++I)
1269 RewriteMethodDeclaration(*I);
1270 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001271 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001272 I != E; ++I)
1273 RewriteMethodDeclaration(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001274
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001275 // Lastly, comment out the @end.
1276 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1277 "/* @end */");
1278 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001279}
1280
1281Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1282 SourceRange OldRange = PseudoOp->getSourceRange();
1283
1284 // We just magically know some things about the structure of this
1285 // expression.
1286 ObjCMessageExpr *OldMsg =
1287 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1288 PseudoOp->getNumSemanticExprs() - 1));
1289
1290 // Because the rewriter doesn't allow us to rewrite rewritten code,
1291 // we need to suppress rewriting the sub-statements.
1292 Expr *Base, *RHS;
1293 {
1294 DisableReplaceStmtScope S(*this);
1295
1296 // Rebuild the base expression if we have one.
1297 Base = 0;
1298 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1299 Base = OldMsg->getInstanceReceiver();
1300 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1301 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1302 }
1303
1304 // Rebuild the RHS.
1305 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1306 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1307 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1308 }
1309
1310 // TODO: avoid this copy.
1311 SmallVector<SourceLocation, 1> SelLocs;
1312 OldMsg->getSelectorLocs(SelLocs);
1313
1314 ObjCMessageExpr *NewMsg = 0;
1315 switch (OldMsg->getReceiverKind()) {
1316 case ObjCMessageExpr::Class:
1317 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1318 OldMsg->getValueKind(),
1319 OldMsg->getLeftLoc(),
1320 OldMsg->getClassReceiverTypeInfo(),
1321 OldMsg->getSelector(),
1322 SelLocs,
1323 OldMsg->getMethodDecl(),
1324 RHS,
1325 OldMsg->getRightLoc(),
1326 OldMsg->isImplicit());
1327 break;
1328
1329 case ObjCMessageExpr::Instance:
1330 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1331 OldMsg->getValueKind(),
1332 OldMsg->getLeftLoc(),
1333 Base,
1334 OldMsg->getSelector(),
1335 SelLocs,
1336 OldMsg->getMethodDecl(),
1337 RHS,
1338 OldMsg->getRightLoc(),
1339 OldMsg->isImplicit());
1340 break;
1341
1342 case ObjCMessageExpr::SuperClass:
1343 case ObjCMessageExpr::SuperInstance:
1344 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1345 OldMsg->getValueKind(),
1346 OldMsg->getLeftLoc(),
1347 OldMsg->getSuperLoc(),
1348 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1349 OldMsg->getSuperType(),
1350 OldMsg->getSelector(),
1351 SelLocs,
1352 OldMsg->getMethodDecl(),
1353 RHS,
1354 OldMsg->getRightLoc(),
1355 OldMsg->isImplicit());
1356 break;
1357 }
1358
1359 Stmt *Replacement = SynthMessageExpr(NewMsg);
1360 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1361 return Replacement;
1362}
1363
1364Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1365 SourceRange OldRange = PseudoOp->getSourceRange();
1366
1367 // We just magically know some things about the structure of this
1368 // expression.
1369 ObjCMessageExpr *OldMsg =
1370 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1371
1372 // Because the rewriter doesn't allow us to rewrite rewritten code,
1373 // we need to suppress rewriting the sub-statements.
1374 Expr *Base = 0;
1375 {
1376 DisableReplaceStmtScope S(*this);
1377
1378 // Rebuild the base expression if we have one.
1379 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1380 Base = OldMsg->getInstanceReceiver();
1381 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1382 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1383 }
1384 }
1385
1386 // Intentionally empty.
1387 SmallVector<SourceLocation, 1> SelLocs;
1388 SmallVector<Expr*, 1> Args;
1389
1390 ObjCMessageExpr *NewMsg = 0;
1391 switch (OldMsg->getReceiverKind()) {
1392 case ObjCMessageExpr::Class:
1393 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1394 OldMsg->getValueKind(),
1395 OldMsg->getLeftLoc(),
1396 OldMsg->getClassReceiverTypeInfo(),
1397 OldMsg->getSelector(),
1398 SelLocs,
1399 OldMsg->getMethodDecl(),
1400 Args,
1401 OldMsg->getRightLoc(),
1402 OldMsg->isImplicit());
1403 break;
1404
1405 case ObjCMessageExpr::Instance:
1406 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1407 OldMsg->getValueKind(),
1408 OldMsg->getLeftLoc(),
1409 Base,
1410 OldMsg->getSelector(),
1411 SelLocs,
1412 OldMsg->getMethodDecl(),
1413 Args,
1414 OldMsg->getRightLoc(),
1415 OldMsg->isImplicit());
1416 break;
1417
1418 case ObjCMessageExpr::SuperClass:
1419 case ObjCMessageExpr::SuperInstance:
1420 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1421 OldMsg->getValueKind(),
1422 OldMsg->getLeftLoc(),
1423 OldMsg->getSuperLoc(),
1424 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1425 OldMsg->getSuperType(),
1426 OldMsg->getSelector(),
1427 SelLocs,
1428 OldMsg->getMethodDecl(),
1429 Args,
1430 OldMsg->getRightLoc(),
1431 OldMsg->isImplicit());
1432 break;
1433 }
1434
1435 Stmt *Replacement = SynthMessageExpr(NewMsg);
1436 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1437 return Replacement;
1438}
1439
1440/// SynthCountByEnumWithState - To print:
1441/// ((unsigned int (*)
1442/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1443/// (void *)objc_msgSend)((id)l_collection,
1444/// sel_registerName(
1445/// "countByEnumeratingWithState:objects:count:"),
1446/// &enumState,
1447/// (id *)__rw_items, (unsigned int)16)
1448///
1449void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1450 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1451 "id *, unsigned int))(void *)objc_msgSend)";
1452 buf += "\n\t\t";
1453 buf += "((id)l_collection,\n\t\t";
1454 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1455 buf += "\n\t\t";
1456 buf += "&enumState, "
1457 "(id *)__rw_items, (unsigned int)16)";
1458}
1459
1460/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1461/// statement to exit to its outer synthesized loop.
1462///
1463Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1464 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1465 return S;
1466 // replace break with goto __break_label
1467 std::string buf;
1468
1469 SourceLocation startLoc = S->getLocStart();
1470 buf = "goto __break_label_";
1471 buf += utostr(ObjCBcLabelNo.back());
1472 ReplaceText(startLoc, strlen("break"), buf);
1473
1474 return 0;
1475}
1476
1477/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1478/// statement to continue with its inner synthesized loop.
1479///
1480Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1481 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1482 return S;
1483 // replace continue with goto __continue_label
1484 std::string buf;
1485
1486 SourceLocation startLoc = S->getLocStart();
1487 buf = "goto __continue_label_";
1488 buf += utostr(ObjCBcLabelNo.back());
1489 ReplaceText(startLoc, strlen("continue"), buf);
1490
1491 return 0;
1492}
1493
1494/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1495/// It rewrites:
1496/// for ( type elem in collection) { stmts; }
1497
1498/// Into:
1499/// {
1500/// type elem;
1501/// struct __objcFastEnumerationState enumState = { 0 };
1502/// id __rw_items[16];
1503/// id l_collection = (id)collection;
1504/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1505/// objects:__rw_items count:16];
1506/// if (limit) {
1507/// unsigned long startMutations = *enumState.mutationsPtr;
1508/// do {
1509/// unsigned long counter = 0;
1510/// do {
1511/// if (startMutations != *enumState.mutationsPtr)
1512/// objc_enumerationMutation(l_collection);
1513/// elem = (type)enumState.itemsPtr[counter++];
1514/// stmts;
1515/// __continue_label: ;
1516/// } while (counter < limit);
1517/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1518/// objects:__rw_items count:16]);
1519/// elem = nil;
1520/// __break_label: ;
1521/// }
1522/// else
1523/// elem = nil;
1524/// }
1525///
1526Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1527 SourceLocation OrigEnd) {
1528 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1529 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1530 "ObjCForCollectionStmt Statement stack mismatch");
1531 assert(!ObjCBcLabelNo.empty() &&
1532 "ObjCForCollectionStmt - Label No stack empty");
1533
1534 SourceLocation startLoc = S->getLocStart();
1535 const char *startBuf = SM->getCharacterData(startLoc);
1536 StringRef elementName;
1537 std::string elementTypeAsString;
1538 std::string buf;
1539 buf = "\n{\n\t";
1540 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1541 // type elem;
1542 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1543 QualType ElementType = cast<ValueDecl>(D)->getType();
1544 if (ElementType->isObjCQualifiedIdType() ||
1545 ElementType->isObjCQualifiedInterfaceType())
1546 // Simply use 'id' for all qualified types.
1547 elementTypeAsString = "id";
1548 else
1549 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1550 buf += elementTypeAsString;
1551 buf += " ";
1552 elementName = D->getName();
1553 buf += elementName;
1554 buf += ";\n\t";
1555 }
1556 else {
1557 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1558 elementName = DR->getDecl()->getName();
1559 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1560 if (VD->getType()->isObjCQualifiedIdType() ||
1561 VD->getType()->isObjCQualifiedInterfaceType())
1562 // Simply use 'id' for all qualified types.
1563 elementTypeAsString = "id";
1564 else
1565 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1566 }
1567
1568 // struct __objcFastEnumerationState enumState = { 0 };
1569 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1570 // id __rw_items[16];
1571 buf += "id __rw_items[16];\n\t";
1572 // id l_collection = (id)
1573 buf += "id l_collection = (id)";
1574 // Find start location of 'collection' the hard way!
1575 const char *startCollectionBuf = startBuf;
1576 startCollectionBuf += 3; // skip 'for'
1577 startCollectionBuf = strchr(startCollectionBuf, '(');
1578 startCollectionBuf++; // skip '('
1579 // find 'in' and skip it.
1580 while (*startCollectionBuf != ' ' ||
1581 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1582 (*(startCollectionBuf+3) != ' ' &&
1583 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1584 startCollectionBuf++;
1585 startCollectionBuf += 3;
1586
1587 // Replace: "for (type element in" with string constructed thus far.
1588 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1589 // Replace ')' in for '(' type elem in collection ')' with ';'
1590 SourceLocation rightParenLoc = S->getRParenLoc();
1591 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1592 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1593 buf = ";\n\t";
1594
1595 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1596 // objects:__rw_items count:16];
1597 // which is synthesized into:
1598 // unsigned int limit =
1599 // ((unsigned int (*)
1600 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1601 // (void *)objc_msgSend)((id)l_collection,
1602 // sel_registerName(
1603 // "countByEnumeratingWithState:objects:count:"),
1604 // (struct __objcFastEnumerationState *)&state,
1605 // (id *)__rw_items, (unsigned int)16);
1606 buf += "unsigned long limit =\n\t\t";
1607 SynthCountByEnumWithState(buf);
1608 buf += ";\n\t";
1609 /// if (limit) {
1610 /// unsigned long startMutations = *enumState.mutationsPtr;
1611 /// do {
1612 /// unsigned long counter = 0;
1613 /// do {
1614 /// if (startMutations != *enumState.mutationsPtr)
1615 /// objc_enumerationMutation(l_collection);
1616 /// elem = (type)enumState.itemsPtr[counter++];
1617 buf += "if (limit) {\n\t";
1618 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1619 buf += "do {\n\t\t";
1620 buf += "unsigned long counter = 0;\n\t\t";
1621 buf += "do {\n\t\t\t";
1622 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1623 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1624 buf += elementName;
1625 buf += " = (";
1626 buf += elementTypeAsString;
1627 buf += ")enumState.itemsPtr[counter++];";
1628 // Replace ')' in for '(' type elem in collection ')' with all of these.
1629 ReplaceText(lparenLoc, 1, buf);
1630
1631 /// __continue_label: ;
1632 /// } while (counter < limit);
1633 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1634 /// objects:__rw_items count:16]);
1635 /// elem = nil;
1636 /// __break_label: ;
1637 /// }
1638 /// else
1639 /// elem = nil;
1640 /// }
1641 ///
1642 buf = ";\n\t";
1643 buf += "__continue_label_";
1644 buf += utostr(ObjCBcLabelNo.back());
1645 buf += ": ;";
1646 buf += "\n\t\t";
1647 buf += "} while (counter < limit);\n\t";
1648 buf += "} while (limit = ";
1649 SynthCountByEnumWithState(buf);
1650 buf += ");\n\t";
1651 buf += elementName;
1652 buf += " = ((";
1653 buf += elementTypeAsString;
1654 buf += ")0);\n\t";
1655 buf += "__break_label_";
1656 buf += utostr(ObjCBcLabelNo.back());
1657 buf += ": ;\n\t";
1658 buf += "}\n\t";
1659 buf += "else\n\t\t";
1660 buf += elementName;
1661 buf += " = ((";
1662 buf += elementTypeAsString;
1663 buf += ")0);\n\t";
1664 buf += "}\n";
1665
1666 // Insert all these *after* the statement body.
1667 // FIXME: If this should support Obj-C++, support CXXTryStmt
1668 if (isa<CompoundStmt>(S->getBody())) {
1669 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1670 InsertText(endBodyLoc, buf);
1671 } else {
1672 /* Need to treat single statements specially. For example:
1673 *
1674 * for (A *a in b) if (stuff()) break;
1675 * for (A *a in b) xxxyy;
1676 *
1677 * The following code simply scans ahead to the semi to find the actual end.
1678 */
1679 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1680 const char *semiBuf = strchr(stmtBuf, ';');
1681 assert(semiBuf && "Can't find ';'");
1682 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1683 InsertText(endBodyLoc, buf);
1684 }
1685 Stmts.pop_back();
1686 ObjCBcLabelNo.pop_back();
1687 return 0;
1688}
1689
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001690static void Write_RethrowObject(std::string &buf) {
1691 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1692 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1693 buf += "\tid rethrow;\n";
1694 buf += "\t} _fin_force_rethow(_rethrow);";
1695}
1696
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001697/// RewriteObjCSynchronizedStmt -
1698/// This routine rewrites @synchronized(expr) stmt;
1699/// into:
1700/// objc_sync_enter(expr);
1701/// @try stmt @finally { objc_sync_exit(expr); }
1702///
1703Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1704 // Get the start location and compute the semi location.
1705 SourceLocation startLoc = S->getLocStart();
1706 const char *startBuf = SM->getCharacterData(startLoc);
1707
1708 assert((*startBuf == '@') && "bogus @synchronized location");
1709
1710 std::string buf;
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001711 buf = "{ id _rethrow = 0; id _sync_obj = ";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001712
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001713 const char *lparenBuf = startBuf;
1714 while (*lparenBuf != '(') lparenBuf++;
1715 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001716
1717 buf = "; objc_sync_enter(_sync_obj);\n";
1718 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1719 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1720 buf += "\n\tid sync_exit;";
1721 buf += "\n\t} _sync_exit(_sync_obj);\n";
1722
1723 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1724 // the sync expression is typically a message expression that's already
1725 // been rewritten! (which implies the SourceLocation's are invalid).
1726 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1727 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1728 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1729 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1730
1731 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1732 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1733 assert (*LBraceLocBuf == '{');
1734 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001735
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001736 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay9ab511c2012-03-16 22:20:39 +00001737 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1738 "bogus @synchronized block");
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001739
1740 buf = "} catch (id e) {_rethrow = e;}\n";
1741 Write_RethrowObject(buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001742 buf += "}\n";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001743 buf += "}\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001744
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001745 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001746
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001747 return 0;
1748}
1749
1750void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1751{
1752 // Perform a bottom up traversal of all children.
1753 for (Stmt::child_range CI = S->children(); CI; ++CI)
1754 if (*CI)
1755 WarnAboutReturnGotoStmts(*CI);
1756
1757 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1758 Diags.Report(Context->getFullLoc(S->getLocStart()),
1759 TryFinallyContainsReturnDiag);
1760 }
1761 return;
1762}
1763
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001764Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001765 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001766 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001767 std::string buf;
1768
1769 if (finalStmt) {
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001770 if (noCatch)
1771 buf = "{ id volatile _rethrow = 0;\n";
1772 else {
1773 buf = "{ id volatile _rethrow = 0;\ntry {\n";
1774 }
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001775 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001776 // Get the start location and compute the semi location.
1777 SourceLocation startLoc = S->getLocStart();
1778 const char *startBuf = SM->getCharacterData(startLoc);
1779
1780 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001781 if (finalStmt)
1782 ReplaceText(startLoc, 1, buf);
1783 else
1784 // @try -> try
1785 ReplaceText(startLoc, 1, "");
1786
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001787 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1788 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001789 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001790
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001791 startLoc = Catch->getLocStart();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001792 bool AtRemoved = false;
1793 if (catchDecl) {
1794 QualType t = catchDecl->getType();
1795 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1796 // Should be a pointer to a class.
1797 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1798 if (IDecl) {
1799 std::string Result;
1800 startBuf = SM->getCharacterData(startLoc);
1801 assert((*startBuf == '@') && "bogus @catch location");
1802 SourceLocation rParenLoc = Catch->getRParenLoc();
1803 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1804
1805 // _objc_exc_Foo *_e as argument to catch.
1806 Result = "catch (_objc_exc_"; Result += IDecl->getNameAsString();
1807 Result += " *_"; Result += catchDecl->getNameAsString();
1808 Result += ")";
1809 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1810 // Foo *e = (Foo *)_e;
1811 Result.clear();
1812 Result = "{ ";
1813 Result += IDecl->getNameAsString();
1814 Result += " *"; Result += catchDecl->getNameAsString();
1815 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1816 Result += "_"; Result += catchDecl->getNameAsString();
1817
1818 Result += "; ";
1819 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
1820 ReplaceText(lBraceLoc, 1, Result);
1821 AtRemoved = true;
1822 }
1823 }
1824 }
1825 if (!AtRemoved)
1826 // @catch -> catch
1827 ReplaceText(startLoc, 1, "");
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001828
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001829 }
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001830 if (finalStmt) {
1831 buf.clear();
1832 if (noCatch)
1833 buf = "catch (id e) {_rethrow = e;}\n";
1834 else
1835 buf = "}\ncatch (id e) {_rethrow = e;}\n";
1836
1837 SourceLocation startFinalLoc = finalStmt->getLocStart();
1838 ReplaceText(startFinalLoc, 8, buf);
1839 Stmt *body = finalStmt->getFinallyBody();
1840 SourceLocation startFinalBodyLoc = body->getLocStart();
1841 buf.clear();
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001842 Write_RethrowObject(buf);
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001843 ReplaceText(startFinalBodyLoc, 1, buf);
1844
1845 SourceLocation endFinalBodyLoc = body->getLocEnd();
1846 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001847 // Now check for any return/continue/go statements within the @try.
1848 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001849 }
1850
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001851 return 0;
1852}
1853
1854// This can't be done with ReplaceStmt(S, ThrowExpr), since
1855// the throw expression is typically a message expression that's already
1856// been rewritten! (which implies the SourceLocation's are invalid).
1857Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
1858 // Get the start location and compute the semi location.
1859 SourceLocation startLoc = S->getLocStart();
1860 const char *startBuf = SM->getCharacterData(startLoc);
1861
1862 assert((*startBuf == '@') && "bogus @throw location");
1863
1864 std::string buf;
1865 /* void objc_exception_throw(id) __attribute__((noreturn)); */
1866 if (S->getThrowExpr())
1867 buf = "objc_exception_throw(";
Fariborz Jahanian40539462012-03-16 16:52:06 +00001868 else
1869 buf = "throw";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001870
1871 // handle "@ throw" correctly.
1872 const char *wBuf = strchr(startBuf, 'w');
1873 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1874 ReplaceText(startLoc, wBuf-startBuf+1, buf);
1875
1876 const char *semiBuf = strchr(startBuf, ';');
1877 assert((*semiBuf == ';') && "@throw: can't find ';'");
1878 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian40539462012-03-16 16:52:06 +00001879 if (S->getThrowExpr())
1880 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001881 return 0;
1882}
1883
1884Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
1885 // Create a new string expression.
1886 QualType StrType = Context->getPointerType(Context->CharTy);
1887 std::string StrEncoding;
1888 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
1889 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
1890 StringLiteral::Ascii, false,
1891 StrType, SourceLocation());
1892 ReplaceStmt(Exp, Replacement);
1893
1894 // Replace this subexpr in the parent.
1895 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1896 return Replacement;
1897}
1898
1899Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1900 if (!SelGetUidFunctionDecl)
1901 SynthSelGetUidFunctionDecl();
1902 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1903 // Create a call to sel_registerName("selName").
1904 SmallVector<Expr*, 8> SelExprs;
1905 QualType argType = Context->getPointerType(Context->CharTy);
1906 SelExprs.push_back(StringLiteral::Create(*Context,
1907 Exp->getSelector().getAsString(),
1908 StringLiteral::Ascii, false,
1909 argType, SourceLocation()));
1910 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1911 &SelExprs[0], SelExprs.size());
1912 ReplaceStmt(Exp, SelExp);
1913 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1914 return SelExp;
1915}
1916
1917CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
1918 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
1919 SourceLocation EndLoc) {
1920 // Get the type, we will need to reference it in a couple spots.
1921 QualType msgSendType = FD->getType();
1922
1923 // Create a reference to the objc_msgSend() declaration.
1924 DeclRefExpr *DRE =
John McCallf4b88a42012-03-10 09:33:50 +00001925 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001926
1927 // Now, we cast the reference to a pointer to the objc_msgSend type.
1928 QualType pToFunc = Context->getPointerType(msgSendType);
1929 ImplicitCastExpr *ICE =
1930 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
1931 DRE, 0, VK_RValue);
1932
1933 const FunctionType *FT = msgSendType->getAs<FunctionType>();
1934
1935 CallExpr *Exp =
1936 new (Context) CallExpr(*Context, ICE, args, nargs,
1937 FT->getCallResultType(*Context),
1938 VK_RValue, EndLoc);
1939 return Exp;
1940}
1941
1942static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1943 const char *&startRef, const char *&endRef) {
1944 while (startBuf < endBuf) {
1945 if (*startBuf == '<')
1946 startRef = startBuf; // mark the start.
1947 if (*startBuf == '>') {
1948 if (startRef && *startRef == '<') {
1949 endRef = startBuf; // mark the end.
1950 return true;
1951 }
1952 return false;
1953 }
1954 startBuf++;
1955 }
1956 return false;
1957}
1958
1959static void scanToNextArgument(const char *&argRef) {
1960 int angle = 0;
1961 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1962 if (*argRef == '<')
1963 angle++;
1964 else if (*argRef == '>')
1965 angle--;
1966 argRef++;
1967 }
1968 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1969}
1970
1971bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
1972 if (T->isObjCQualifiedIdType())
1973 return true;
1974 if (const PointerType *PT = T->getAs<PointerType>()) {
1975 if (PT->getPointeeType()->isObjCQualifiedIdType())
1976 return true;
1977 }
1978 if (T->isObjCObjectPointerType()) {
1979 T = T->getPointeeType();
1980 return T->isObjCQualifiedInterfaceType();
1981 }
1982 if (T->isArrayType()) {
1983 QualType ElemTy = Context->getBaseElementType(T);
1984 return needToScanForQualifiers(ElemTy);
1985 }
1986 return false;
1987}
1988
1989void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1990 QualType Type = E->getType();
1991 if (needToScanForQualifiers(Type)) {
1992 SourceLocation Loc, EndLoc;
1993
1994 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1995 Loc = ECE->getLParenLoc();
1996 EndLoc = ECE->getRParenLoc();
1997 } else {
1998 Loc = E->getLocStart();
1999 EndLoc = E->getLocEnd();
2000 }
2001 // This will defend against trying to rewrite synthesized expressions.
2002 if (Loc.isInvalid() || EndLoc.isInvalid())
2003 return;
2004
2005 const char *startBuf = SM->getCharacterData(Loc);
2006 const char *endBuf = SM->getCharacterData(EndLoc);
2007 const char *startRef = 0, *endRef = 0;
2008 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2009 // Get the locations of the startRef, endRef.
2010 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2011 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2012 // Comment out the protocol references.
2013 InsertText(LessLoc, "/*");
2014 InsertText(GreaterLoc, "*/");
2015 }
2016 }
2017}
2018
2019void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2020 SourceLocation Loc;
2021 QualType Type;
2022 const FunctionProtoType *proto = 0;
2023 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2024 Loc = VD->getLocation();
2025 Type = VD->getType();
2026 }
2027 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2028 Loc = FD->getLocation();
2029 // Check for ObjC 'id' and class types that have been adorned with protocol
2030 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2031 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2032 assert(funcType && "missing function type");
2033 proto = dyn_cast<FunctionProtoType>(funcType);
2034 if (!proto)
2035 return;
2036 Type = proto->getResultType();
2037 }
2038 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2039 Loc = FD->getLocation();
2040 Type = FD->getType();
2041 }
2042 else
2043 return;
2044
2045 if (needToScanForQualifiers(Type)) {
2046 // Since types are unique, we need to scan the buffer.
2047
2048 const char *endBuf = SM->getCharacterData(Loc);
2049 const char *startBuf = endBuf;
2050 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2051 startBuf--; // scan backward (from the decl location) for return type.
2052 const char *startRef = 0, *endRef = 0;
2053 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2054 // Get the locations of the startRef, endRef.
2055 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2056 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2057 // Comment out the protocol references.
2058 InsertText(LessLoc, "/*");
2059 InsertText(GreaterLoc, "*/");
2060 }
2061 }
2062 if (!proto)
2063 return; // most likely, was a variable
2064 // Now check arguments.
2065 const char *startBuf = SM->getCharacterData(Loc);
2066 const char *startFuncBuf = startBuf;
2067 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2068 if (needToScanForQualifiers(proto->getArgType(i))) {
2069 // Since types are unique, we need to scan the buffer.
2070
2071 const char *endBuf = startBuf;
2072 // scan forward (from the decl location) for argument types.
2073 scanToNextArgument(endBuf);
2074 const char *startRef = 0, *endRef = 0;
2075 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2076 // Get the locations of the startRef, endRef.
2077 SourceLocation LessLoc =
2078 Loc.getLocWithOffset(startRef-startFuncBuf);
2079 SourceLocation GreaterLoc =
2080 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2081 // Comment out the protocol references.
2082 InsertText(LessLoc, "/*");
2083 InsertText(GreaterLoc, "*/");
2084 }
2085 startBuf = ++endBuf;
2086 }
2087 else {
2088 // If the function name is derived from a macro expansion, then the
2089 // argument buffer will not follow the name. Need to speak with Chris.
2090 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2091 startBuf++; // scan forward (from the decl location) for argument types.
2092 startBuf++;
2093 }
2094 }
2095}
2096
2097void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2098 QualType QT = ND->getType();
2099 const Type* TypePtr = QT->getAs<Type>();
2100 if (!isa<TypeOfExprType>(TypePtr))
2101 return;
2102 while (isa<TypeOfExprType>(TypePtr)) {
2103 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2104 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2105 TypePtr = QT->getAs<Type>();
2106 }
2107 // FIXME. This will not work for multiple declarators; as in:
2108 // __typeof__(a) b,c,d;
2109 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2110 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2111 const char *startBuf = SM->getCharacterData(DeclLoc);
2112 if (ND->getInit()) {
2113 std::string Name(ND->getNameAsString());
2114 TypeAsString += " " + Name + " = ";
2115 Expr *E = ND->getInit();
2116 SourceLocation startLoc;
2117 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2118 startLoc = ECE->getLParenLoc();
2119 else
2120 startLoc = E->getLocStart();
2121 startLoc = SM->getExpansionLoc(startLoc);
2122 const char *endBuf = SM->getCharacterData(startLoc);
2123 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2124 }
2125 else {
2126 SourceLocation X = ND->getLocEnd();
2127 X = SM->getExpansionLoc(X);
2128 const char *endBuf = SM->getCharacterData(X);
2129 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2130 }
2131}
2132
2133// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2134void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2135 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2136 SmallVector<QualType, 16> ArgTys;
2137 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2138 QualType getFuncType =
2139 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
2140 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2141 SourceLocation(),
2142 SourceLocation(),
2143 SelGetUidIdent, getFuncType, 0,
2144 SC_Extern,
2145 SC_None, false);
2146}
2147
2148void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2149 // declared in <objc/objc.h>
2150 if (FD->getIdentifier() &&
2151 FD->getName() == "sel_registerName") {
2152 SelGetUidFunctionDecl = FD;
2153 return;
2154 }
2155 RewriteObjCQualifiedInterfaceTypes(FD);
2156}
2157
2158void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2159 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2160 const char *argPtr = TypeString.c_str();
2161 if (!strchr(argPtr, '^')) {
2162 Str += TypeString;
2163 return;
2164 }
2165 while (*argPtr) {
2166 Str += (*argPtr == '^' ? '*' : *argPtr);
2167 argPtr++;
2168 }
2169}
2170
2171// FIXME. Consolidate this routine with RewriteBlockPointerType.
2172void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2173 ValueDecl *VD) {
2174 QualType Type = VD->getType();
2175 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2176 const char *argPtr = TypeString.c_str();
2177 int paren = 0;
2178 while (*argPtr) {
2179 switch (*argPtr) {
2180 case '(':
2181 Str += *argPtr;
2182 paren++;
2183 break;
2184 case ')':
2185 Str += *argPtr;
2186 paren--;
2187 break;
2188 case '^':
2189 Str += '*';
2190 if (paren == 1)
2191 Str += VD->getNameAsString();
2192 break;
2193 default:
2194 Str += *argPtr;
2195 break;
2196 }
2197 argPtr++;
2198 }
2199}
2200
2201
2202void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2203 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2204 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2205 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2206 if (!proto)
2207 return;
2208 QualType Type = proto->getResultType();
2209 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2210 FdStr += " ";
2211 FdStr += FD->getName();
2212 FdStr += "(";
2213 unsigned numArgs = proto->getNumArgs();
2214 for (unsigned i = 0; i < numArgs; i++) {
2215 QualType ArgType = proto->getArgType(i);
2216 RewriteBlockPointerType(FdStr, ArgType);
2217 if (i+1 < numArgs)
2218 FdStr += ", ";
2219 }
2220 FdStr += ");\n";
2221 InsertText(FunLocStart, FdStr);
2222 CurFunctionDeclToDeclareForBlock = 0;
2223}
2224
2225// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
2226void RewriteModernObjC::SynthSuperContructorFunctionDecl() {
2227 if (SuperContructorFunctionDecl)
2228 return;
2229 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2230 SmallVector<QualType, 16> ArgTys;
2231 QualType argT = Context->getObjCIdType();
2232 assert(!argT.isNull() && "Can't find 'id' type");
2233 ArgTys.push_back(argT);
2234 ArgTys.push_back(argT);
2235 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2236 &ArgTys[0], ArgTys.size());
2237 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2238 SourceLocation(),
2239 SourceLocation(),
2240 msgSendIdent, msgSendType, 0,
2241 SC_Extern,
2242 SC_None, false);
2243}
2244
2245// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2246void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2247 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2248 SmallVector<QualType, 16> ArgTys;
2249 QualType argT = Context->getObjCIdType();
2250 assert(!argT.isNull() && "Can't find 'id' type");
2251 ArgTys.push_back(argT);
2252 argT = Context->getObjCSelType();
2253 assert(!argT.isNull() && "Can't find 'SEL' type");
2254 ArgTys.push_back(argT);
2255 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2256 &ArgTys[0], ArgTys.size(),
2257 true /*isVariadic*/);
2258 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2259 SourceLocation(),
2260 SourceLocation(),
2261 msgSendIdent, msgSendType, 0,
2262 SC_Extern,
2263 SC_None, false);
2264}
2265
2266// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
2267void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2268 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2269 SmallVector<QualType, 16> ArgTys;
2270 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2271 SourceLocation(), SourceLocation(),
2272 &Context->Idents.get("objc_super"));
2273 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2274 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2275 ArgTys.push_back(argT);
2276 argT = Context->getObjCSelType();
2277 assert(!argT.isNull() && "Can't find 'SEL' type");
2278 ArgTys.push_back(argT);
2279 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2280 &ArgTys[0], ArgTys.size(),
2281 true /*isVariadic*/);
2282 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2283 SourceLocation(),
2284 SourceLocation(),
2285 msgSendIdent, msgSendType, 0,
2286 SC_Extern,
2287 SC_None, false);
2288}
2289
2290// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2291void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2292 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2293 SmallVector<QualType, 16> ArgTys;
2294 QualType argT = Context->getObjCIdType();
2295 assert(!argT.isNull() && "Can't find 'id' type");
2296 ArgTys.push_back(argT);
2297 argT = Context->getObjCSelType();
2298 assert(!argT.isNull() && "Can't find 'SEL' type");
2299 ArgTys.push_back(argT);
2300 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2301 &ArgTys[0], ArgTys.size(),
2302 true /*isVariadic*/);
2303 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2304 SourceLocation(),
2305 SourceLocation(),
2306 msgSendIdent, msgSendType, 0,
2307 SC_Extern,
2308 SC_None, false);
2309}
2310
2311// SynthMsgSendSuperStretFunctionDecl -
2312// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
2313void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2314 IdentifierInfo *msgSendIdent =
2315 &Context->Idents.get("objc_msgSendSuper_stret");
2316 SmallVector<QualType, 16> ArgTys;
2317 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2318 SourceLocation(), SourceLocation(),
2319 &Context->Idents.get("objc_super"));
2320 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2321 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2322 ArgTys.push_back(argT);
2323 argT = Context->getObjCSelType();
2324 assert(!argT.isNull() && "Can't find 'SEL' type");
2325 ArgTys.push_back(argT);
2326 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2327 &ArgTys[0], ArgTys.size(),
2328 true /*isVariadic*/);
2329 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2330 SourceLocation(),
2331 SourceLocation(),
2332 msgSendIdent, msgSendType, 0,
2333 SC_Extern,
2334 SC_None, false);
2335}
2336
2337// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2338void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2339 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2340 SmallVector<QualType, 16> ArgTys;
2341 QualType argT = Context->getObjCIdType();
2342 assert(!argT.isNull() && "Can't find 'id' type");
2343 ArgTys.push_back(argT);
2344 argT = Context->getObjCSelType();
2345 assert(!argT.isNull() && "Can't find 'SEL' type");
2346 ArgTys.push_back(argT);
2347 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2348 &ArgTys[0], ArgTys.size(),
2349 true /*isVariadic*/);
2350 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2351 SourceLocation(),
2352 SourceLocation(),
2353 msgSendIdent, msgSendType, 0,
2354 SC_Extern,
2355 SC_None, false);
2356}
2357
2358// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
2359void RewriteModernObjC::SynthGetClassFunctionDecl() {
2360 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2361 SmallVector<QualType, 16> ArgTys;
2362 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2363 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2364 &ArgTys[0], ArgTys.size());
2365 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2366 SourceLocation(),
2367 SourceLocation(),
2368 getClassIdent, getClassType, 0,
2369 SC_Extern,
2370 SC_None, false);
2371}
2372
2373// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2374void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2375 IdentifierInfo *getSuperClassIdent =
2376 &Context->Idents.get("class_getSuperclass");
2377 SmallVector<QualType, 16> ArgTys;
2378 ArgTys.push_back(Context->getObjCClassType());
2379 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2380 &ArgTys[0], ArgTys.size());
2381 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2382 SourceLocation(),
2383 SourceLocation(),
2384 getSuperClassIdent,
2385 getClassType, 0,
2386 SC_Extern,
2387 SC_None,
2388 false);
2389}
2390
2391// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
2392void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2393 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2394 SmallVector<QualType, 16> ArgTys;
2395 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2396 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2397 &ArgTys[0], ArgTys.size());
2398 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2399 SourceLocation(),
2400 SourceLocation(),
2401 getClassIdent, getClassType, 0,
2402 SC_Extern,
2403 SC_None, false);
2404}
2405
2406Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2407 QualType strType = getConstantStringStructType();
2408
2409 std::string S = "__NSConstantStringImpl_";
2410
2411 std::string tmpName = InFileName;
2412 unsigned i;
2413 for (i=0; i < tmpName.length(); i++) {
2414 char c = tmpName.at(i);
2415 // replace any non alphanumeric characters with '_'.
2416 if (!isalpha(c) && (c < '0' || c > '9'))
2417 tmpName[i] = '_';
2418 }
2419 S += tmpName;
2420 S += "_";
2421 S += utostr(NumObjCStringLiterals++);
2422
2423 Preamble += "static __NSConstantStringImpl " + S;
2424 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2425 Preamble += "0x000007c8,"; // utf8_str
2426 // The pretty printer for StringLiteral handles escape characters properly.
2427 std::string prettyBufS;
2428 llvm::raw_string_ostream prettyBuf(prettyBufS);
2429 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2430 PrintingPolicy(LangOpts));
2431 Preamble += prettyBuf.str();
2432 Preamble += ",";
2433 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2434
2435 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2436 SourceLocation(), &Context->Idents.get(S),
2437 strType, 0, SC_Static, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002438 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002439 SourceLocation());
2440 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2441 Context->getPointerType(DRE->getType()),
2442 VK_RValue, OK_Ordinary,
2443 SourceLocation());
2444 // cast to NSConstantString *
2445 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2446 CK_CPointerToObjCPointerCast, Unop);
2447 ReplaceStmt(Exp, cast);
2448 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2449 return cast;
2450}
2451
2452// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
2453QualType RewriteModernObjC::getSuperStructType() {
2454 if (!SuperStructDecl) {
2455 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2456 SourceLocation(), SourceLocation(),
2457 &Context->Idents.get("objc_super"));
2458 QualType FieldTypes[2];
2459
2460 // struct objc_object *receiver;
2461 FieldTypes[0] = Context->getObjCIdType();
2462 // struct objc_class *super;
2463 FieldTypes[1] = Context->getObjCClassType();
2464
2465 // Create fields
2466 for (unsigned i = 0; i < 2; ++i) {
2467 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2468 SourceLocation(),
2469 SourceLocation(), 0,
2470 FieldTypes[i], 0,
2471 /*BitWidth=*/0,
2472 /*Mutable=*/false,
2473 /*HasInit=*/false));
2474 }
2475
2476 SuperStructDecl->completeDefinition();
2477 }
2478 return Context->getTagDeclType(SuperStructDecl);
2479}
2480
2481QualType RewriteModernObjC::getConstantStringStructType() {
2482 if (!ConstantStringDecl) {
2483 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2484 SourceLocation(), SourceLocation(),
2485 &Context->Idents.get("__NSConstantStringImpl"));
2486 QualType FieldTypes[4];
2487
2488 // struct objc_object *receiver;
2489 FieldTypes[0] = Context->getObjCIdType();
2490 // int flags;
2491 FieldTypes[1] = Context->IntTy;
2492 // char *str;
2493 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2494 // long length;
2495 FieldTypes[3] = Context->LongTy;
2496
2497 // Create fields
2498 for (unsigned i = 0; i < 4; ++i) {
2499 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2500 ConstantStringDecl,
2501 SourceLocation(),
2502 SourceLocation(), 0,
2503 FieldTypes[i], 0,
2504 /*BitWidth=*/0,
2505 /*Mutable=*/true,
2506 /*HasInit=*/false));
2507 }
2508
2509 ConstantStringDecl->completeDefinition();
2510 }
2511 return Context->getTagDeclType(ConstantStringDecl);
2512}
2513
2514Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2515 SourceLocation StartLoc,
2516 SourceLocation EndLoc) {
2517 if (!SelGetUidFunctionDecl)
2518 SynthSelGetUidFunctionDecl();
2519 if (!MsgSendFunctionDecl)
2520 SynthMsgSendFunctionDecl();
2521 if (!MsgSendSuperFunctionDecl)
2522 SynthMsgSendSuperFunctionDecl();
2523 if (!MsgSendStretFunctionDecl)
2524 SynthMsgSendStretFunctionDecl();
2525 if (!MsgSendSuperStretFunctionDecl)
2526 SynthMsgSendSuperStretFunctionDecl();
2527 if (!MsgSendFpretFunctionDecl)
2528 SynthMsgSendFpretFunctionDecl();
2529 if (!GetClassFunctionDecl)
2530 SynthGetClassFunctionDecl();
2531 if (!GetSuperClassFunctionDecl)
2532 SynthGetSuperClassFunctionDecl();
2533 if (!GetMetaClassFunctionDecl)
2534 SynthGetMetaClassFunctionDecl();
2535
2536 // default to objc_msgSend().
2537 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2538 // May need to use objc_msgSend_stret() as well.
2539 FunctionDecl *MsgSendStretFlavor = 0;
2540 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2541 QualType resultType = mDecl->getResultType();
2542 if (resultType->isRecordType())
2543 MsgSendStretFlavor = MsgSendStretFunctionDecl;
2544 else if (resultType->isRealFloatingType())
2545 MsgSendFlavor = MsgSendFpretFunctionDecl;
2546 }
2547
2548 // Synthesize a call to objc_msgSend().
2549 SmallVector<Expr*, 8> MsgExprs;
2550 switch (Exp->getReceiverKind()) {
2551 case ObjCMessageExpr::SuperClass: {
2552 MsgSendFlavor = MsgSendSuperFunctionDecl;
2553 if (MsgSendStretFlavor)
2554 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2555 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2556
2557 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2558
2559 SmallVector<Expr*, 4> InitExprs;
2560
2561 // set the receiver to self, the first argument to all methods.
2562 InitExprs.push_back(
2563 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2564 CK_BitCast,
2565 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00002566 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002567 Context->getObjCIdType(),
2568 VK_RValue,
2569 SourceLocation()))
2570 ); // set the 'receiver'.
2571
2572 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2573 SmallVector<Expr*, 8> ClsExprs;
2574 QualType argType = Context->getPointerType(Context->CharTy);
2575 ClsExprs.push_back(StringLiteral::Create(*Context,
2576 ClassDecl->getIdentifier()->getName(),
2577 StringLiteral::Ascii, false,
2578 argType, SourceLocation()));
2579 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2580 &ClsExprs[0],
2581 ClsExprs.size(),
2582 StartLoc,
2583 EndLoc);
2584 // (Class)objc_getClass("CurrentClass")
2585 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2586 Context->getObjCClassType(),
2587 CK_BitCast, Cls);
2588 ClsExprs.clear();
2589 ClsExprs.push_back(ArgExpr);
2590 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2591 &ClsExprs[0], ClsExprs.size(),
2592 StartLoc, EndLoc);
2593
2594 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2595 // To turn off a warning, type-cast to 'id'
2596 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2597 NoTypeInfoCStyleCastExpr(Context,
2598 Context->getObjCIdType(),
2599 CK_BitCast, Cls));
2600 // struct objc_super
2601 QualType superType = getSuperStructType();
2602 Expr *SuperRep;
2603
2604 if (LangOpts.MicrosoftExt) {
2605 SynthSuperContructorFunctionDecl();
2606 // Simulate a contructor call...
2607 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00002608 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002609 SourceLocation());
2610 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2611 InitExprs.size(),
2612 superType, VK_LValue,
2613 SourceLocation());
2614 // The code for super is a little tricky to prevent collision with
2615 // the structure definition in the header. The rewriter has it's own
2616 // internal definition (__rw_objc_super) that is uses. This is why
2617 // we need the cast below. For example:
2618 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2619 //
2620 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2621 Context->getPointerType(SuperRep->getType()),
2622 VK_RValue, OK_Ordinary,
2623 SourceLocation());
2624 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2625 Context->getPointerType(superType),
2626 CK_BitCast, SuperRep);
2627 } else {
2628 // (struct objc_super) { <exprs from above> }
2629 InitListExpr *ILE =
2630 new (Context) InitListExpr(*Context, SourceLocation(),
2631 &InitExprs[0], InitExprs.size(),
2632 SourceLocation());
2633 TypeSourceInfo *superTInfo
2634 = Context->getTrivialTypeSourceInfo(superType);
2635 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2636 superType, VK_LValue,
2637 ILE, false);
2638 // struct objc_super *
2639 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2640 Context->getPointerType(SuperRep->getType()),
2641 VK_RValue, OK_Ordinary,
2642 SourceLocation());
2643 }
2644 MsgExprs.push_back(SuperRep);
2645 break;
2646 }
2647
2648 case ObjCMessageExpr::Class: {
2649 SmallVector<Expr*, 8> ClsExprs;
2650 QualType argType = Context->getPointerType(Context->CharTy);
2651 ObjCInterfaceDecl *Class
2652 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
2653 IdentifierInfo *clsName = Class->getIdentifier();
2654 ClsExprs.push_back(StringLiteral::Create(*Context,
2655 clsName->getName(),
2656 StringLiteral::Ascii, false,
2657 argType, SourceLocation()));
2658 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2659 &ClsExprs[0],
2660 ClsExprs.size(),
2661 StartLoc, EndLoc);
2662 MsgExprs.push_back(Cls);
2663 break;
2664 }
2665
2666 case ObjCMessageExpr::SuperInstance:{
2667 MsgSendFlavor = MsgSendSuperFunctionDecl;
2668 if (MsgSendStretFlavor)
2669 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2670 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2671 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2672 SmallVector<Expr*, 4> InitExprs;
2673
2674 InitExprs.push_back(
2675 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2676 CK_BitCast,
2677 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00002678 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002679 Context->getObjCIdType(),
2680 VK_RValue, SourceLocation()))
2681 ); // set the 'receiver'.
2682
2683 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2684 SmallVector<Expr*, 8> ClsExprs;
2685 QualType argType = Context->getPointerType(Context->CharTy);
2686 ClsExprs.push_back(StringLiteral::Create(*Context,
2687 ClassDecl->getIdentifier()->getName(),
2688 StringLiteral::Ascii, false, argType,
2689 SourceLocation()));
2690 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2691 &ClsExprs[0],
2692 ClsExprs.size(),
2693 StartLoc, EndLoc);
2694 // (Class)objc_getClass("CurrentClass")
2695 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2696 Context->getObjCClassType(),
2697 CK_BitCast, Cls);
2698 ClsExprs.clear();
2699 ClsExprs.push_back(ArgExpr);
2700 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2701 &ClsExprs[0], ClsExprs.size(),
2702 StartLoc, EndLoc);
2703
2704 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2705 // To turn off a warning, type-cast to 'id'
2706 InitExprs.push_back(
2707 // set 'super class', using class_getSuperclass().
2708 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2709 CK_BitCast, Cls));
2710 // struct objc_super
2711 QualType superType = getSuperStructType();
2712 Expr *SuperRep;
2713
2714 if (LangOpts.MicrosoftExt) {
2715 SynthSuperContructorFunctionDecl();
2716 // Simulate a contructor call...
2717 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00002718 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002719 SourceLocation());
2720 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2721 InitExprs.size(),
2722 superType, VK_LValue, SourceLocation());
2723 // The code for super is a little tricky to prevent collision with
2724 // the structure definition in the header. The rewriter has it's own
2725 // internal definition (__rw_objc_super) that is uses. This is why
2726 // we need the cast below. For example:
2727 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2728 //
2729 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2730 Context->getPointerType(SuperRep->getType()),
2731 VK_RValue, OK_Ordinary,
2732 SourceLocation());
2733 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2734 Context->getPointerType(superType),
2735 CK_BitCast, SuperRep);
2736 } else {
2737 // (struct objc_super) { <exprs from above> }
2738 InitListExpr *ILE =
2739 new (Context) InitListExpr(*Context, SourceLocation(),
2740 &InitExprs[0], InitExprs.size(),
2741 SourceLocation());
2742 TypeSourceInfo *superTInfo
2743 = Context->getTrivialTypeSourceInfo(superType);
2744 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2745 superType, VK_RValue, ILE,
2746 false);
2747 }
2748 MsgExprs.push_back(SuperRep);
2749 break;
2750 }
2751
2752 case ObjCMessageExpr::Instance: {
2753 // Remove all type-casts because it may contain objc-style types; e.g.
2754 // Foo<Proto> *.
2755 Expr *recExpr = Exp->getInstanceReceiver();
2756 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2757 recExpr = CE->getSubExpr();
2758 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
2759 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
2760 ? CK_BlockPointerToObjCPointerCast
2761 : CK_CPointerToObjCPointerCast;
2762
2763 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2764 CK, recExpr);
2765 MsgExprs.push_back(recExpr);
2766 break;
2767 }
2768 }
2769
2770 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
2771 SmallVector<Expr*, 8> SelExprs;
2772 QualType argType = Context->getPointerType(Context->CharTy);
2773 SelExprs.push_back(StringLiteral::Create(*Context,
2774 Exp->getSelector().getAsString(),
2775 StringLiteral::Ascii, false,
2776 argType, SourceLocation()));
2777 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2778 &SelExprs[0], SelExprs.size(),
2779 StartLoc,
2780 EndLoc);
2781 MsgExprs.push_back(SelExp);
2782
2783 // Now push any user supplied arguments.
2784 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
2785 Expr *userExpr = Exp->getArg(i);
2786 // Make all implicit casts explicit...ICE comes in handy:-)
2787 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2788 // Reuse the ICE type, it is exactly what the doctor ordered.
2789 QualType type = ICE->getType();
2790 if (needToScanForQualifiers(type))
2791 type = Context->getObjCIdType();
2792 // Make sure we convert "type (^)(...)" to "type (*)(...)".
2793 (void)convertBlockPointerToFunctionPointer(type);
2794 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2795 CastKind CK;
2796 if (SubExpr->getType()->isIntegralType(*Context) &&
2797 type->isBooleanType()) {
2798 CK = CK_IntegralToBoolean;
2799 } else if (type->isObjCObjectPointerType()) {
2800 if (SubExpr->getType()->isBlockPointerType()) {
2801 CK = CK_BlockPointerToObjCPointerCast;
2802 } else if (SubExpr->getType()->isPointerType()) {
2803 CK = CK_CPointerToObjCPointerCast;
2804 } else {
2805 CK = CK_BitCast;
2806 }
2807 } else {
2808 CK = CK_BitCast;
2809 }
2810
2811 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
2812 }
2813 // Make id<P...> cast into an 'id' cast.
2814 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
2815 if (CE->getType()->isObjCQualifiedIdType()) {
2816 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
2817 userExpr = CE->getSubExpr();
2818 CastKind CK;
2819 if (userExpr->getType()->isIntegralType(*Context)) {
2820 CK = CK_IntegralToPointer;
2821 } else if (userExpr->getType()->isBlockPointerType()) {
2822 CK = CK_BlockPointerToObjCPointerCast;
2823 } else if (userExpr->getType()->isPointerType()) {
2824 CK = CK_CPointerToObjCPointerCast;
2825 } else {
2826 CK = CK_BitCast;
2827 }
2828 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2829 CK, userExpr);
2830 }
2831 }
2832 MsgExprs.push_back(userExpr);
2833 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2834 // out the argument in the original expression (since we aren't deleting
2835 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
2836 //Exp->setArg(i, 0);
2837 }
2838 // Generate the funky cast.
2839 CastExpr *cast;
2840 SmallVector<QualType, 8> ArgTypes;
2841 QualType returnType;
2842
2843 // Push 'id' and 'SEL', the 2 implicit arguments.
2844 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2845 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2846 else
2847 ArgTypes.push_back(Context->getObjCIdType());
2848 ArgTypes.push_back(Context->getObjCSelType());
2849 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
2850 // Push any user argument types.
2851 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2852 E = OMD->param_end(); PI != E; ++PI) {
2853 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
2854 ? Context->getObjCIdType()
2855 : (*PI)->getType();
2856 // Make sure we convert "t (^)(...)" to "t (*)(...)".
2857 (void)convertBlockPointerToFunctionPointer(t);
2858 ArgTypes.push_back(t);
2859 }
2860 returnType = Exp->getType();
2861 convertToUnqualifiedObjCType(returnType);
2862 (void)convertBlockPointerToFunctionPointer(returnType);
2863 } else {
2864 returnType = Context->getObjCIdType();
2865 }
2866 // Get the type, we will need to reference it in a couple spots.
2867 QualType msgSendType = MsgSendFlavor->getType();
2868
2869 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00002870 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002871 VK_LValue, SourceLocation());
2872
2873 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2874 // If we don't do this cast, we get the following bizarre warning/note:
2875 // xx.m:13: warning: function called through a non-compatible type
2876 // xx.m:13: note: if this code is reached, the program will abort
2877 cast = NoTypeInfoCStyleCastExpr(Context,
2878 Context->getPointerType(Context->VoidTy),
2879 CK_BitCast, DRE);
2880
2881 // Now do the "normal" pointer to function cast.
2882 QualType castType =
2883 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2884 // If we don't have a method decl, force a variadic cast.
2885 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
2886 castType = Context->getPointerType(castType);
2887 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2888 cast);
2889
2890 // Don't forget the parens to enforce the proper binding.
2891 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2892
2893 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2894 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2895 MsgExprs.size(),
2896 FT->getResultType(), VK_RValue,
2897 EndLoc);
2898 Stmt *ReplacingStmt = CE;
2899 if (MsgSendStretFlavor) {
2900 // We have the method which returns a struct/union. Must also generate
2901 // call to objc_msgSend_stret and hang both varieties on a conditional
2902 // expression which dictate which one to envoke depending on size of
2903 // method's return type.
2904
2905 // Create a reference to the objc_msgSend_stret() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00002906 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
2907 false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002908 VK_LValue, SourceLocation());
2909 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2910 cast = NoTypeInfoCStyleCastExpr(Context,
2911 Context->getPointerType(Context->VoidTy),
2912 CK_BitCast, STDRE);
2913 // Now do the "normal" pointer to function cast.
2914 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2915 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
2916 castType = Context->getPointerType(castType);
2917 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2918 cast);
2919
2920 // Don't forget the parens to enforce the proper binding.
2921 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
2922
2923 FT = msgSendType->getAs<FunctionType>();
2924 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2925 MsgExprs.size(),
2926 FT->getResultType(), VK_RValue,
2927 SourceLocation());
2928
2929 // Build sizeof(returnType)
2930 UnaryExprOrTypeTraitExpr *sizeofExpr =
2931 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
2932 Context->getTrivialTypeSourceInfo(returnType),
2933 Context->getSizeType(), SourceLocation(),
2934 SourceLocation());
2935 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2936 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2937 // For X86 it is more complicated and some kind of target specific routine
2938 // is needed to decide what to do.
2939 unsigned IntSize =
2940 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2941 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
2942 llvm::APInt(IntSize, 8),
2943 Context->IntTy,
2944 SourceLocation());
2945 BinaryOperator *lessThanExpr =
2946 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
2947 VK_RValue, OK_Ordinary, SourceLocation());
2948 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2949 ConditionalOperator *CondExpr =
2950 new (Context) ConditionalOperator(lessThanExpr,
2951 SourceLocation(), CE,
2952 SourceLocation(), STCE,
2953 returnType, VK_RValue, OK_Ordinary);
2954 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
2955 CondExpr);
2956 }
2957 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2958 return ReplacingStmt;
2959}
2960
2961Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
2962 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
2963 Exp->getLocEnd());
2964
2965 // Now do the actual rewrite.
2966 ReplaceStmt(Exp, ReplacingStmt);
2967
2968 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2969 return ReplacingStmt;
2970}
2971
2972// typedef struct objc_object Protocol;
2973QualType RewriteModernObjC::getProtocolType() {
2974 if (!ProtocolTypeDecl) {
2975 TypeSourceInfo *TInfo
2976 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
2977 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
2978 SourceLocation(), SourceLocation(),
2979 &Context->Idents.get("Protocol"),
2980 TInfo);
2981 }
2982 return Context->getTypeDeclType(ProtocolTypeDecl);
2983}
2984
2985/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2986/// a synthesized/forward data reference (to the protocol's metadata).
2987/// The forward references (and metadata) are generated in
2988/// RewriteModernObjC::HandleTranslationUnit().
2989Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00002990 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
2991 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002992 IdentifierInfo *ID = &Context->Idents.get(Name);
2993 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2994 SourceLocation(), ID, getProtocolType(), 0,
2995 SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002996 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
2997 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002998 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
2999 Context->getPointerType(DRE->getType()),
3000 VK_RValue, OK_Ordinary, SourceLocation());
3001 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3002 CK_BitCast,
3003 DerefExpr);
3004 ReplaceStmt(Exp, castExpr);
3005 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3006 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3007 return castExpr;
3008
3009}
3010
3011bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3012 const char *endBuf) {
3013 while (startBuf < endBuf) {
3014 if (*startBuf == '#') {
3015 // Skip whitespace.
3016 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3017 ;
3018 if (!strncmp(startBuf, "if", strlen("if")) ||
3019 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3020 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3021 !strncmp(startBuf, "define", strlen("define")) ||
3022 !strncmp(startBuf, "undef", strlen("undef")) ||
3023 !strncmp(startBuf, "else", strlen("else")) ||
3024 !strncmp(startBuf, "elif", strlen("elif")) ||
3025 !strncmp(startBuf, "endif", strlen("endif")) ||
3026 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3027 !strncmp(startBuf, "include", strlen("include")) ||
3028 !strncmp(startBuf, "import", strlen("import")) ||
3029 !strncmp(startBuf, "include_next", strlen("include_next")))
3030 return true;
3031 }
3032 startBuf++;
3033 }
3034 return false;
3035}
3036
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003037/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003038/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003039bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3040 std::string &Result) {
3041 if (Type->isArrayType()) {
3042 QualType ElemTy = Context->getBaseElementType(Type);
3043 return RewriteObjCFieldDeclType(ElemTy, Result);
3044 }
3045 else if (Type->isRecordType()) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003046 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3047 if (RD->isCompleteDefinition()) {
3048 if (RD->isStruct())
3049 Result += "\n\tstruct ";
3050 else if (RD->isUnion())
3051 Result += "\n\tunion ";
3052 else
3053 assert(false && "class not allowed as an ivar type");
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003054
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003055 Result += RD->getName();
3056 if (TagsDefinedInIvarDecls.count(RD)) {
3057 // This struct is already defined. Do not write its definition again.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003058 Result += " ";
3059 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003060 }
3061 TagsDefinedInIvarDecls.insert(RD);
3062 Result += " {\n";
3063 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003064 e = RD->field_end(); i != e; ++i) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003065 FieldDecl *FD = *i;
3066 RewriteObjCFieldDecl(FD, Result);
3067 }
3068 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003069 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003070 }
3071 }
3072 else if (Type->isEnumeralType()) {
3073 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3074 if (ED->isCompleteDefinition()) {
3075 Result += "\n\tenum ";
3076 Result += ED->getName();
3077 if (TagsDefinedInIvarDecls.count(ED)) {
3078 // This enum is already defined. Do not write its definition again.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003079 Result += " ";
3080 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003081 }
3082 TagsDefinedInIvarDecls.insert(ED);
3083
3084 Result += " {\n";
3085 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3086 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3087 Result += "\t"; Result += EC->getName(); Result += " = ";
3088 llvm::APSInt Val = EC->getInitVal();
3089 Result += Val.toString(10);
3090 Result += ",\n";
3091 }
3092 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003093 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003094 }
3095 }
3096
3097 Result += "\t";
3098 convertObjCTypeToCStyleType(Type);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003099 return false;
3100}
3101
3102
3103/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3104/// It handles elaborated types, as well as enum types in the process.
3105void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3106 std::string &Result) {
3107 QualType Type = fieldDecl->getType();
3108 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003109
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003110 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3111 if (!EleboratedType)
3112 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003113 Result += Name;
3114 if (fieldDecl->isBitField()) {
3115 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3116 }
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003117 else if (EleboratedType && Type->isArrayType()) {
3118 CanQualType CType = Context->getCanonicalType(Type);
3119 while (isa<ArrayType>(CType)) {
3120 if (const ConstantArrayType *CAT = Context->getAsConstantArrayType(CType)) {
3121 Result += "[";
3122 llvm::APInt Dim = CAT->getSize();
3123 Result += utostr(Dim.getZExtValue());
3124 Result += "]";
3125 }
3126 CType = CType->getAs<ArrayType>()->getElementType();
3127 }
3128 }
3129
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003130 Result += ";\n";
3131}
3132
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003133/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3134/// an objective-c class with ivars.
3135void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3136 std::string &Result) {
3137 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3138 assert(CDecl->getName() != "" &&
3139 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003140 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003141 SmallVector<ObjCIvarDecl *, 8> IVars;
3142 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003143 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003144 IVars.push_back(IVD);
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003145
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003146 SourceLocation LocStart = CDecl->getLocStart();
3147 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003148
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003149 const char *startBuf = SM->getCharacterData(LocStart);
3150 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003151
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003152 // If no ivars and no root or if its root, directly or indirectly,
3153 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003154 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003155 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3156 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3157 ReplaceText(LocStart, endBuf-startBuf, Result);
3158 return;
3159 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003160
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003161 Result += "\nstruct ";
3162 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003163 Result += "_IMPL {\n";
3164
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003165 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003166 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3167 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3168 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003169 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003170 TagsDefinedInIvarDecls.clear();
3171 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3172 RewriteObjCFieldDecl(IVars[i], Result);
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00003173
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003174 Result += "};\n";
3175 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3176 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003177 // Mark this struct as having been generated.
3178 if (!ObjCSynthesizedStructs.insert(CDecl))
3179 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003180}
3181
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003182static void WriteInternalIvarName(ObjCInterfaceDecl *IDecl,
3183 ObjCIvarDecl *IvarDecl, std::string &Result) {
3184 Result += "OBJC_IVAR_$_";
3185 Result += IDecl->getName();
3186 Result += "$";
3187 Result += IvarDecl->getName();
3188}
3189
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003190/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3191/// have been referenced in an ivar access expression.
3192void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3193 std::string &Result) {
3194 // write out ivar offset symbols which have been referenced in an ivar
3195 // access expression.
3196 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3197 if (Ivars.empty())
3198 return;
3199 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
3200 e = Ivars.end(); i != e; i++) {
3201 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003202 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00003203 Result += "extern \"C\" ";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003204 if (LangOpts.MicrosoftExt)
3205 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
3206 if (LangOpts.MicrosoftExt &&
3207 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
3208 IvarDecl->getAccessControl() != ObjCIvarDecl::Package) {
3209 const ObjCInterfaceDecl *CDecl = IvarDecl->getContainingInterface();
3210 if (CDecl->getImplementation())
3211 Result += "__declspec(dllexport) ";
3212 }
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00003213 Result += "unsigned long ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003214 WriteInternalIvarName(CDecl, IvarDecl, Result);
3215 Result += ";";
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003216 }
3217}
3218
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003219//===----------------------------------------------------------------------===//
3220// Meta Data Emission
3221//===----------------------------------------------------------------------===//
3222
3223
3224/// RewriteImplementations - This routine rewrites all method implementations
3225/// and emits meta-data.
3226
3227void RewriteModernObjC::RewriteImplementations() {
3228 int ClsDefCount = ClassImplementation.size();
3229 int CatDefCount = CategoryImplementation.size();
3230
3231 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003232 for (int i = 0; i < ClsDefCount; i++) {
3233 ObjCImplementationDecl *OIMP = ClassImplementation[i];
3234 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
3235 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00003236 assert(false &&
3237 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003238 RewriteImplementationDecl(OIMP);
3239 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003240
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003241 for (int i = 0; i < CatDefCount; i++) {
3242 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
3243 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
3244 if (CDecl->isImplicitInterfaceDecl())
3245 assert(false &&
3246 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003247 RewriteImplementationDecl(CIMP);
3248 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003249}
3250
3251void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
3252 const std::string &Name,
3253 ValueDecl *VD, bool def) {
3254 assert(BlockByRefDeclNo.count(VD) &&
3255 "RewriteByRefString: ByRef decl missing");
3256 if (def)
3257 ResultStr += "struct ";
3258 ResultStr += "__Block_byref_" + Name +
3259 "_" + utostr(BlockByRefDeclNo[VD]) ;
3260}
3261
3262static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3263 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3264 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3265 return false;
3266}
3267
3268std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3269 StringRef funcName,
3270 std::string Tag) {
3271 const FunctionType *AFT = CE->getFunctionType();
3272 QualType RT = AFT->getResultType();
3273 std::string StructRef = "struct " + Tag;
3274 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00003275 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003276
3277 BlockDecl *BD = CE->getBlockDecl();
3278
3279 if (isa<FunctionNoProtoType>(AFT)) {
3280 // No user-supplied arguments. Still need to pass in a pointer to the
3281 // block (to reference imported block decl refs).
3282 S += "(" + StructRef + " *__cself)";
3283 } else if (BD->param_empty()) {
3284 S += "(" + StructRef + " *__cself)";
3285 } else {
3286 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
3287 assert(FT && "SynthesizeBlockFunc: No function proto");
3288 S += '(';
3289 // first add the implicit argument.
3290 S += StructRef + " *__cself, ";
3291 std::string ParamStr;
3292 for (BlockDecl::param_iterator AI = BD->param_begin(),
3293 E = BD->param_end(); AI != E; ++AI) {
3294 if (AI != BD->param_begin()) S += ", ";
3295 ParamStr = (*AI)->getNameAsString();
3296 QualType QT = (*AI)->getType();
3297 if (convertBlockPointerToFunctionPointer(QT))
3298 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
3299 else
3300 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
3301 S += ParamStr;
3302 }
3303 if (FT->isVariadic()) {
3304 if (!BD->param_empty()) S += ", ";
3305 S += "...";
3306 }
3307 S += ')';
3308 }
3309 S += " {\n";
3310
3311 // Create local declarations to avoid rewriting all closure decl ref exprs.
3312 // First, emit a declaration for all "by ref" decls.
3313 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3314 E = BlockByRefDecls.end(); I != E; ++I) {
3315 S += " ";
3316 std::string Name = (*I)->getNameAsString();
3317 std::string TypeString;
3318 RewriteByRefString(TypeString, Name, (*I));
3319 TypeString += " *";
3320 Name = TypeString + Name;
3321 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
3322 }
3323 // Next, emit a declaration for all "by copy" declarations.
3324 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3325 E = BlockByCopyDecls.end(); I != E; ++I) {
3326 S += " ";
3327 // Handle nested closure invocation. For example:
3328 //
3329 // void (^myImportedClosure)(void);
3330 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3331 //
3332 // void (^anotherClosure)(void);
3333 // anotherClosure = ^(void) {
3334 // myImportedClosure(); // import and invoke the closure
3335 // };
3336 //
3337 if (isTopLevelBlockPointerType((*I)->getType())) {
3338 RewriteBlockPointerTypeVariable(S, (*I));
3339 S += " = (";
3340 RewriteBlockPointerType(S, (*I)->getType());
3341 S += ")";
3342 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3343 }
3344 else {
3345 std::string Name = (*I)->getNameAsString();
3346 QualType QT = (*I)->getType();
3347 if (HasLocalVariableExternalStorage(*I))
3348 QT = Context->getPointerType(QT);
3349 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
3350 S += Name + " = __cself->" +
3351 (*I)->getNameAsString() + "; // bound by copy\n";
3352 }
3353 }
3354 std::string RewrittenStr = RewrittenBlockExprs[CE];
3355 const char *cstr = RewrittenStr.c_str();
3356 while (*cstr++ != '{') ;
3357 S += cstr;
3358 S += "\n";
3359 return S;
3360}
3361
3362std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3363 StringRef funcName,
3364 std::string Tag) {
3365 std::string StructRef = "struct " + Tag;
3366 std::string S = "static void __";
3367
3368 S += funcName;
3369 S += "_block_copy_" + utostr(i);
3370 S += "(" + StructRef;
3371 S += "*dst, " + StructRef;
3372 S += "*src) {";
3373 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3374 E = ImportedBlockDecls.end(); I != E; ++I) {
3375 ValueDecl *VD = (*I);
3376 S += "_Block_object_assign((void*)&dst->";
3377 S += (*I)->getNameAsString();
3378 S += ", (void*)src->";
3379 S += (*I)->getNameAsString();
3380 if (BlockByRefDeclsPtrSet.count((*I)))
3381 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3382 else if (VD->getType()->isBlockPointerType())
3383 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3384 else
3385 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3386 }
3387 S += "}\n";
3388
3389 S += "\nstatic void __";
3390 S += funcName;
3391 S += "_block_dispose_" + utostr(i);
3392 S += "(" + StructRef;
3393 S += "*src) {";
3394 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3395 E = ImportedBlockDecls.end(); I != E; ++I) {
3396 ValueDecl *VD = (*I);
3397 S += "_Block_object_dispose((void*)src->";
3398 S += (*I)->getNameAsString();
3399 if (BlockByRefDeclsPtrSet.count((*I)))
3400 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3401 else if (VD->getType()->isBlockPointerType())
3402 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3403 else
3404 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3405 }
3406 S += "}\n";
3407 return S;
3408}
3409
3410std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3411 std::string Desc) {
3412 std::string S = "\nstruct " + Tag;
3413 std::string Constructor = " " + Tag;
3414
3415 S += " {\n struct __block_impl impl;\n";
3416 S += " struct " + Desc;
3417 S += "* Desc;\n";
3418
3419 Constructor += "(void *fp, "; // Invoke function pointer.
3420 Constructor += "struct " + Desc; // Descriptor pointer.
3421 Constructor += " *desc";
3422
3423 if (BlockDeclRefs.size()) {
3424 // Output all "by copy" declarations.
3425 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3426 E = BlockByCopyDecls.end(); I != E; ++I) {
3427 S += " ";
3428 std::string FieldName = (*I)->getNameAsString();
3429 std::string ArgName = "_" + FieldName;
3430 // Handle nested closure invocation. For example:
3431 //
3432 // void (^myImportedBlock)(void);
3433 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3434 //
3435 // void (^anotherBlock)(void);
3436 // anotherBlock = ^(void) {
3437 // myImportedBlock(); // import and invoke the closure
3438 // };
3439 //
3440 if (isTopLevelBlockPointerType((*I)->getType())) {
3441 S += "struct __block_impl *";
3442 Constructor += ", void *" + ArgName;
3443 } else {
3444 QualType QT = (*I)->getType();
3445 if (HasLocalVariableExternalStorage(*I))
3446 QT = Context->getPointerType(QT);
3447 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3448 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
3449 Constructor += ", " + ArgName;
3450 }
3451 S += FieldName + ";\n";
3452 }
3453 // Output all "by ref" declarations.
3454 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3455 E = BlockByRefDecls.end(); I != E; ++I) {
3456 S += " ";
3457 std::string FieldName = (*I)->getNameAsString();
3458 std::string ArgName = "_" + FieldName;
3459 {
3460 std::string TypeString;
3461 RewriteByRefString(TypeString, FieldName, (*I));
3462 TypeString += " *";
3463 FieldName = TypeString + FieldName;
3464 ArgName = TypeString + ArgName;
3465 Constructor += ", " + ArgName;
3466 }
3467 S += FieldName + "; // by ref\n";
3468 }
3469 // Finish writing the constructor.
3470 Constructor += ", int flags=0)";
3471 // Initialize all "by copy" arguments.
3472 bool firsTime = true;
3473 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3474 E = BlockByCopyDecls.end(); I != E; ++I) {
3475 std::string Name = (*I)->getNameAsString();
3476 if (firsTime) {
3477 Constructor += " : ";
3478 firsTime = false;
3479 }
3480 else
3481 Constructor += ", ";
3482 if (isTopLevelBlockPointerType((*I)->getType()))
3483 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3484 else
3485 Constructor += Name + "(_" + Name + ")";
3486 }
3487 // Initialize all "by ref" arguments.
3488 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3489 E = BlockByRefDecls.end(); I != E; ++I) {
3490 std::string Name = (*I)->getNameAsString();
3491 if (firsTime) {
3492 Constructor += " : ";
3493 firsTime = false;
3494 }
3495 else
3496 Constructor += ", ";
3497 Constructor += Name + "(_" + Name + "->__forwarding)";
3498 }
3499
3500 Constructor += " {\n";
3501 if (GlobalVarDecl)
3502 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3503 else
3504 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3505 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3506
3507 Constructor += " Desc = desc;\n";
3508 } else {
3509 // Finish writing the constructor.
3510 Constructor += ", int flags=0) {\n";
3511 if (GlobalVarDecl)
3512 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3513 else
3514 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3515 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3516 Constructor += " Desc = desc;\n";
3517 }
3518 Constructor += " ";
3519 Constructor += "}\n";
3520 S += Constructor;
3521 S += "};\n";
3522 return S;
3523}
3524
3525std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
3526 std::string ImplTag, int i,
3527 StringRef FunName,
3528 unsigned hasCopy) {
3529 std::string S = "\nstatic struct " + DescTag;
3530
3531 S += " {\n unsigned long reserved;\n";
3532 S += " unsigned long Block_size;\n";
3533 if (hasCopy) {
3534 S += " void (*copy)(struct ";
3535 S += ImplTag; S += "*, struct ";
3536 S += ImplTag; S += "*);\n";
3537
3538 S += " void (*dispose)(struct ";
3539 S += ImplTag; S += "*);\n";
3540 }
3541 S += "} ";
3542
3543 S += DescTag + "_DATA = { 0, sizeof(struct ";
3544 S += ImplTag + ")";
3545 if (hasCopy) {
3546 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3547 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
3548 }
3549 S += "};\n";
3550 return S;
3551}
3552
3553void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3554 StringRef FunName) {
3555 // Insert declaration for the function in which block literal is used.
3556 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
3557 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
3558 bool RewriteSC = (GlobalVarDecl &&
3559 !Blocks.empty() &&
3560 GlobalVarDecl->getStorageClass() == SC_Static &&
3561 GlobalVarDecl->getType().getCVRQualifiers());
3562 if (RewriteSC) {
3563 std::string SC(" void __");
3564 SC += GlobalVarDecl->getNameAsString();
3565 SC += "() {}";
3566 InsertText(FunLocStart, SC);
3567 }
3568
3569 // Insert closures that were part of the function.
3570 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3571 CollectBlockDeclRefInfo(Blocks[i]);
3572 // Need to copy-in the inner copied-in variables not actually used in this
3573 // block.
3574 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00003575 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003576 ValueDecl *VD = Exp->getDecl();
3577 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00003578 if (!VD->hasAttr<BlocksAttr>()) {
3579 if (!BlockByCopyDeclsPtrSet.count(VD)) {
3580 BlockByCopyDeclsPtrSet.insert(VD);
3581 BlockByCopyDecls.push_back(VD);
3582 }
3583 continue;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003584 }
John McCallf4b88a42012-03-10 09:33:50 +00003585
3586 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003587 BlockByRefDeclsPtrSet.insert(VD);
3588 BlockByRefDecls.push_back(VD);
3589 }
John McCallf4b88a42012-03-10 09:33:50 +00003590
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003591 // imported objects in the inner blocks not used in the outer
3592 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00003593 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003594 VD->getType()->isBlockPointerType())
3595 ImportedBlockDecls.insert(VD);
3596 }
3597
3598 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3599 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
3600
3601 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
3602
3603 InsertText(FunLocStart, CI);
3604
3605 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
3606
3607 InsertText(FunLocStart, CF);
3608
3609 if (ImportedBlockDecls.size()) {
3610 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
3611 InsertText(FunLocStart, HF);
3612 }
3613 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3614 ImportedBlockDecls.size() > 0);
3615 InsertText(FunLocStart, BD);
3616
3617 BlockDeclRefs.clear();
3618 BlockByRefDecls.clear();
3619 BlockByRefDeclsPtrSet.clear();
3620 BlockByCopyDecls.clear();
3621 BlockByCopyDeclsPtrSet.clear();
3622 ImportedBlockDecls.clear();
3623 }
3624 if (RewriteSC) {
3625 // Must insert any 'const/volatile/static here. Since it has been
3626 // removed as result of rewriting of block literals.
3627 std::string SC;
3628 if (GlobalVarDecl->getStorageClass() == SC_Static)
3629 SC = "static ";
3630 if (GlobalVarDecl->getType().isConstQualified())
3631 SC += "const ";
3632 if (GlobalVarDecl->getType().isVolatileQualified())
3633 SC += "volatile ";
3634 if (GlobalVarDecl->getType().isRestrictQualified())
3635 SC += "restrict ";
3636 InsertText(FunLocStart, SC);
3637 }
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00003638 if (GlobalConstructionExp) {
3639 // extra fancy dance for global literal expression.
3640
3641 // Always the latest block expression on the block stack.
3642 std::string Tag = "__";
3643 Tag += FunName;
3644 Tag += "_block_impl_";
3645 Tag += utostr(Blocks.size()-1);
3646 std::string globalBuf = "static ";
3647 globalBuf += Tag; globalBuf += " ";
3648 std::string SStr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003649
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00003650 llvm::raw_string_ostream constructorExprBuf(SStr);
3651 GlobalConstructionExp->printPretty(constructorExprBuf, *Context, 0,
3652 PrintingPolicy(LangOpts));
3653 globalBuf += constructorExprBuf.str();
3654 globalBuf += ";\n";
3655 InsertText(FunLocStart, globalBuf);
3656 GlobalConstructionExp = 0;
3657 }
3658
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003659 Blocks.clear();
3660 InnerDeclRefsCount.clear();
3661 InnerDeclRefs.clear();
3662 RewrittenBlockExprs.clear();
3663}
3664
3665void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3666 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
3667 StringRef FuncName = FD->getName();
3668
3669 SynthesizeBlockLiterals(FunLocStart, FuncName);
3670}
3671
3672static void BuildUniqueMethodName(std::string &Name,
3673 ObjCMethodDecl *MD) {
3674 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3675 Name = IFace->getName();
3676 Name += "__" + MD->getSelector().getAsString();
3677 // Convert colons to underscores.
3678 std::string::size_type loc = 0;
3679 while ((loc = Name.find(":", loc)) != std::string::npos)
3680 Name.replace(loc, 1, "_");
3681}
3682
3683void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
3684 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3685 //SourceLocation FunLocStart = MD->getLocStart();
3686 SourceLocation FunLocStart = MD->getLocStart();
3687 std::string FuncName;
3688 BuildUniqueMethodName(FuncName, MD);
3689 SynthesizeBlockLiterals(FunLocStart, FuncName);
3690}
3691
3692void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
3693 for (Stmt::child_range CI = S->children(); CI; ++CI)
3694 if (*CI) {
3695 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3696 GetBlockDeclRefExprs(CBE->getBody());
3697 else
3698 GetBlockDeclRefExprs(*CI);
3699 }
3700 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00003701 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
3702 if (DRE->refersToEnclosingLocal() &&
3703 HasLocalVariableExternalStorage(DRE->getDecl())) {
3704 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003705 }
3706
3707 return;
3708}
3709
3710void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +00003711 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003712 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
3713 for (Stmt::child_range CI = S->children(); CI; ++CI)
3714 if (*CI) {
3715 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
3716 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
3717 GetInnerBlockDeclRefExprs(CBE->getBody(),
3718 InnerBlockDeclRefs,
3719 InnerContexts);
3720 }
3721 else
3722 GetInnerBlockDeclRefExprs(*CI,
3723 InnerBlockDeclRefs,
3724 InnerContexts);
3725
3726 }
3727 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00003728 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3729 if (DRE->refersToEnclosingLocal()) {
3730 if (!isa<FunctionDecl>(DRE->getDecl()) &&
3731 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
3732 InnerBlockDeclRefs.push_back(DRE);
3733 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
3734 if (Var->isFunctionOrMethodVarDecl())
3735 ImportedLocalExternalDecls.insert(Var);
3736 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003737 }
3738
3739 return;
3740}
3741
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003742/// convertObjCTypeToCStyleType - This routine converts such objc types
3743/// as qualified objects, and blocks to their closest c/c++ types that
3744/// it can. It returns true if input type was modified.
3745bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
3746 QualType oldT = T;
3747 convertBlockPointerToFunctionPointer(T);
3748 if (T->isFunctionPointerType()) {
3749 QualType PointeeTy;
3750 if (const PointerType* PT = T->getAs<PointerType>()) {
3751 PointeeTy = PT->getPointeeType();
3752 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
3753 T = convertFunctionTypeOfBlocks(FT);
3754 T = Context->getPointerType(T);
3755 }
3756 }
3757 }
3758
3759 convertToUnqualifiedObjCType(T);
3760 return T != oldT;
3761}
3762
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003763/// convertFunctionTypeOfBlocks - This routine converts a function type
3764/// whose result type may be a block pointer or whose argument type(s)
3765/// might be block pointers to an equivalent function type replacing
3766/// all block pointers to function pointers.
3767QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3768 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3769 // FTP will be null for closures that don't take arguments.
3770 // Generate a funky cast.
3771 SmallVector<QualType, 8> ArgTypes;
3772 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003773 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003774
3775 if (FTP) {
3776 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3777 E = FTP->arg_type_end(); I && (I != E); ++I) {
3778 QualType t = *I;
3779 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003780 if (convertObjCTypeToCStyleType(t))
3781 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003782 ArgTypes.push_back(t);
3783 }
3784 }
3785 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003786 if (modified)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003787 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
3788 else FuncType = QualType(FT, 0);
3789 return FuncType;
3790}
3791
3792Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
3793 // Navigate to relevant type information.
3794 const BlockPointerType *CPT = 0;
3795
3796 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
3797 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003798 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
3799 CPT = MExpr->getType()->getAs<BlockPointerType>();
3800 }
3801 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3802 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3803 }
3804 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3805 CPT = IEXPR->getType()->getAs<BlockPointerType>();
3806 else if (const ConditionalOperator *CEXPR =
3807 dyn_cast<ConditionalOperator>(BlockExp)) {
3808 Expr *LHSExp = CEXPR->getLHS();
3809 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3810 Expr *RHSExp = CEXPR->getRHS();
3811 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3812 Expr *CONDExp = CEXPR->getCond();
3813 ConditionalOperator *CondExpr =
3814 new (Context) ConditionalOperator(CONDExp,
3815 SourceLocation(), cast<Expr>(LHSStmt),
3816 SourceLocation(), cast<Expr>(RHSStmt),
3817 Exp->getType(), VK_RValue, OK_Ordinary);
3818 return CondExpr;
3819 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3820 CPT = IRE->getType()->getAs<BlockPointerType>();
3821 } else if (const PseudoObjectExpr *POE
3822 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3823 CPT = POE->getType()->castAs<BlockPointerType>();
3824 } else {
3825 assert(1 && "RewriteBlockClass: Bad type");
3826 }
3827 assert(CPT && "RewriteBlockClass: Bad type");
3828 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
3829 assert(FT && "RewriteBlockClass: Bad type");
3830 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3831 // FTP will be null for closures that don't take arguments.
3832
3833 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3834 SourceLocation(), SourceLocation(),
3835 &Context->Idents.get("__block_impl"));
3836 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
3837
3838 // Generate a funky cast.
3839 SmallVector<QualType, 8> ArgTypes;
3840
3841 // Push the block argument type.
3842 ArgTypes.push_back(PtrBlock);
3843 if (FTP) {
3844 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3845 E = FTP->arg_type_end(); I && (I != E); ++I) {
3846 QualType t = *I;
3847 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3848 if (!convertBlockPointerToFunctionPointer(t))
3849 convertToUnqualifiedObjCType(t);
3850 ArgTypes.push_back(t);
3851 }
3852 }
3853 // Now do the pointer to function cast.
3854 QualType PtrToFuncCastType
3855 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
3856
3857 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
3858
3859 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
3860 CK_BitCast,
3861 const_cast<Expr*>(BlockExp));
3862 // Don't forget the parens to enforce the proper binding.
3863 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3864 BlkCast);
3865 //PE->dump();
3866
3867 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3868 SourceLocation(),
3869 &Context->Idents.get("FuncPtr"),
3870 Context->VoidPtrTy, 0,
3871 /*BitWidth=*/0, /*Mutable=*/true,
3872 /*HasInit=*/false);
3873 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
3874 FD->getType(), VK_LValue,
3875 OK_Ordinary);
3876
3877
3878 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
3879 CK_BitCast, ME);
3880 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3881
3882 SmallVector<Expr*, 8> BlkExprs;
3883 // Add the implicit argument.
3884 BlkExprs.push_back(BlkCast);
3885 // Add the user arguments.
3886 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3887 E = Exp->arg_end(); I != E; ++I) {
3888 BlkExprs.push_back(*I);
3889 }
3890 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
3891 BlkExprs.size(),
3892 Exp->getType(), VK_RValue,
3893 SourceLocation());
3894 return CE;
3895}
3896
3897// We need to return the rewritten expression to handle cases where the
John McCallf4b88a42012-03-10 09:33:50 +00003898// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003899// For example:
3900//
3901// int main() {
3902// __block Foo *f;
3903// __block int i;
3904//
3905// void (^myblock)() = ^() {
John McCallf4b88a42012-03-10 09:33:50 +00003906// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003907// i = 77;
3908// };
3909//}
John McCallf4b88a42012-03-10 09:33:50 +00003910Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003911 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
3912 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00003913 ValueDecl *VD = DeclRefExp->getDecl();
3914 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003915
3916 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3917 SourceLocation(),
3918 &Context->Idents.get("__forwarding"),
3919 Context->VoidPtrTy, 0,
3920 /*BitWidth=*/0, /*Mutable=*/true,
3921 /*HasInit=*/false);
3922 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
3923 FD, SourceLocation(),
3924 FD->getType(), VK_LValue,
3925 OK_Ordinary);
3926
3927 StringRef Name = VD->getName();
3928 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
3929 &Context->Idents.get(Name),
3930 Context->VoidPtrTy, 0,
3931 /*BitWidth=*/0, /*Mutable=*/true,
3932 /*HasInit=*/false);
3933 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
3934 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
3935
3936
3937
3938 // Need parens to enforce precedence.
3939 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
3940 DeclRefExp->getExprLoc(),
3941 ME);
3942 ReplaceStmt(DeclRefExp, PE);
3943 return PE;
3944}
3945
3946// Rewrites the imported local variable V with external storage
3947// (static, extern, etc.) as *V
3948//
3949Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
3950 ValueDecl *VD = DRE->getDecl();
3951 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3952 if (!ImportedLocalExternalDecls.count(Var))
3953 return DRE;
3954 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
3955 VK_LValue, OK_Ordinary,
3956 DRE->getLocation());
3957 // Need parens to enforce precedence.
3958 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3959 Exp);
3960 ReplaceStmt(DRE, PE);
3961 return PE;
3962}
3963
3964void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3965 SourceLocation LocStart = CE->getLParenLoc();
3966 SourceLocation LocEnd = CE->getRParenLoc();
3967
3968 // Need to avoid trying to rewrite synthesized casts.
3969 if (LocStart.isInvalid())
3970 return;
3971 // Need to avoid trying to rewrite casts contained in macros.
3972 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3973 return;
3974
3975 const char *startBuf = SM->getCharacterData(LocStart);
3976 const char *endBuf = SM->getCharacterData(LocEnd);
3977 QualType QT = CE->getType();
3978 const Type* TypePtr = QT->getAs<Type>();
3979 if (isa<TypeOfExprType>(TypePtr)) {
3980 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
3981 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
3982 std::string TypeAsString = "(";
3983 RewriteBlockPointerType(TypeAsString, QT);
3984 TypeAsString += ")";
3985 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
3986 return;
3987 }
3988 // advance the location to startArgList.
3989 const char *argPtr = startBuf;
3990
3991 while (*argPtr++ && (argPtr < endBuf)) {
3992 switch (*argPtr) {
3993 case '^':
3994 // Replace the '^' with '*'.
3995 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
3996 ReplaceText(LocStart, 1, "*");
3997 break;
3998 }
3999 }
4000 return;
4001}
4002
4003void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4004 SourceLocation DeclLoc = FD->getLocation();
4005 unsigned parenCount = 0;
4006
4007 // We have 1 or more arguments that have closure pointers.
4008 const char *startBuf = SM->getCharacterData(DeclLoc);
4009 const char *startArgList = strchr(startBuf, '(');
4010
4011 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4012
4013 parenCount++;
4014 // advance the location to startArgList.
4015 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4016 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4017
4018 const char *argPtr = startArgList;
4019
4020 while (*argPtr++ && parenCount) {
4021 switch (*argPtr) {
4022 case '^':
4023 // Replace the '^' with '*'.
4024 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4025 ReplaceText(DeclLoc, 1, "*");
4026 break;
4027 case '(':
4028 parenCount++;
4029 break;
4030 case ')':
4031 parenCount--;
4032 break;
4033 }
4034 }
4035 return;
4036}
4037
4038bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4039 const FunctionProtoType *FTP;
4040 const PointerType *PT = QT->getAs<PointerType>();
4041 if (PT) {
4042 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4043 } else {
4044 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4045 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4046 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4047 }
4048 if (FTP) {
4049 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4050 E = FTP->arg_type_end(); I != E; ++I)
4051 if (isTopLevelBlockPointerType(*I))
4052 return true;
4053 }
4054 return false;
4055}
4056
4057bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4058 const FunctionProtoType *FTP;
4059 const PointerType *PT = QT->getAs<PointerType>();
4060 if (PT) {
4061 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4062 } else {
4063 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4064 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4065 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4066 }
4067 if (FTP) {
4068 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4069 E = FTP->arg_type_end(); I != E; ++I) {
4070 if ((*I)->isObjCQualifiedIdType())
4071 return true;
4072 if ((*I)->isObjCObjectPointerType() &&
4073 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4074 return true;
4075 }
4076
4077 }
4078 return false;
4079}
4080
4081void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4082 const char *&RParen) {
4083 const char *argPtr = strchr(Name, '(');
4084 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4085
4086 LParen = argPtr; // output the start.
4087 argPtr++; // skip past the left paren.
4088 unsigned parenCount = 1;
4089
4090 while (*argPtr && parenCount) {
4091 switch (*argPtr) {
4092 case '(': parenCount++; break;
4093 case ')': parenCount--; break;
4094 default: break;
4095 }
4096 if (parenCount) argPtr++;
4097 }
4098 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4099 RParen = argPtr; // output the end
4100}
4101
4102void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4103 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4104 RewriteBlockPointerFunctionArgs(FD);
4105 return;
4106 }
4107 // Handle Variables and Typedefs.
4108 SourceLocation DeclLoc = ND->getLocation();
4109 QualType DeclT;
4110 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4111 DeclT = VD->getType();
4112 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4113 DeclT = TDD->getUnderlyingType();
4114 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4115 DeclT = FD->getType();
4116 else
4117 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4118
4119 const char *startBuf = SM->getCharacterData(DeclLoc);
4120 const char *endBuf = startBuf;
4121 // scan backward (from the decl location) for the end of the previous decl.
4122 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4123 startBuf--;
4124 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4125 std::string buf;
4126 unsigned OrigLength=0;
4127 // *startBuf != '^' if we are dealing with a pointer to function that
4128 // may take block argument types (which will be handled below).
4129 if (*startBuf == '^') {
4130 // Replace the '^' with '*', computing a negative offset.
4131 buf = '*';
4132 startBuf++;
4133 OrigLength++;
4134 }
4135 while (*startBuf != ')') {
4136 buf += *startBuf;
4137 startBuf++;
4138 OrigLength++;
4139 }
4140 buf += ')';
4141 OrigLength++;
4142
4143 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4144 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4145 // Replace the '^' with '*' for arguments.
4146 // Replace id<P> with id/*<>*/
4147 DeclLoc = ND->getLocation();
4148 startBuf = SM->getCharacterData(DeclLoc);
4149 const char *argListBegin, *argListEnd;
4150 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4151 while (argListBegin < argListEnd) {
4152 if (*argListBegin == '^')
4153 buf += '*';
4154 else if (*argListBegin == '<') {
4155 buf += "/*";
4156 buf += *argListBegin++;
4157 OrigLength++;;
4158 while (*argListBegin != '>') {
4159 buf += *argListBegin++;
4160 OrigLength++;
4161 }
4162 buf += *argListBegin;
4163 buf += "*/";
4164 }
4165 else
4166 buf += *argListBegin;
4167 argListBegin++;
4168 OrigLength++;
4169 }
4170 buf += ')';
4171 OrigLength++;
4172 }
4173 ReplaceText(Start, OrigLength, buf);
4174
4175 return;
4176}
4177
4178
4179/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4180/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4181/// struct Block_byref_id_object *src) {
4182/// _Block_object_assign (&_dest->object, _src->object,
4183/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4184/// [|BLOCK_FIELD_IS_WEAK]) // object
4185/// _Block_object_assign(&_dest->object, _src->object,
4186/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4187/// [|BLOCK_FIELD_IS_WEAK]) // block
4188/// }
4189/// And:
4190/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4191/// _Block_object_dispose(_src->object,
4192/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4193/// [|BLOCK_FIELD_IS_WEAK]) // object
4194/// _Block_object_dispose(_src->object,
4195/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4196/// [|BLOCK_FIELD_IS_WEAK]) // block
4197/// }
4198
4199std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4200 int flag) {
4201 std::string S;
4202 if (CopyDestroyCache.count(flag))
4203 return S;
4204 CopyDestroyCache.insert(flag);
4205 S = "static void __Block_byref_id_object_copy_";
4206 S += utostr(flag);
4207 S += "(void *dst, void *src) {\n";
4208
4209 // offset into the object pointer is computed as:
4210 // void * + void* + int + int + void* + void *
4211 unsigned IntSize =
4212 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4213 unsigned VoidPtrSize =
4214 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4215
4216 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4217 S += " _Block_object_assign((char*)dst + ";
4218 S += utostr(offset);
4219 S += ", *(void * *) ((char*)src + ";
4220 S += utostr(offset);
4221 S += "), ";
4222 S += utostr(flag);
4223 S += ");\n}\n";
4224
4225 S += "static void __Block_byref_id_object_dispose_";
4226 S += utostr(flag);
4227 S += "(void *src) {\n";
4228 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4229 S += utostr(offset);
4230 S += "), ";
4231 S += utostr(flag);
4232 S += ");\n}\n";
4233 return S;
4234}
4235
4236/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4237/// the declaration into:
4238/// struct __Block_byref_ND {
4239/// void *__isa; // NULL for everything except __weak pointers
4240/// struct __Block_byref_ND *__forwarding;
4241/// int32_t __flags;
4242/// int32_t __size;
4243/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4244/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4245/// typex ND;
4246/// };
4247///
4248/// It then replaces declaration of ND variable with:
4249/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4250/// __size=sizeof(struct __Block_byref_ND),
4251/// ND=initializer-if-any};
4252///
4253///
4254void RewriteModernObjC::RewriteByRefVar(VarDecl *ND) {
4255 // Insert declaration for the function in which block literal is
4256 // used.
4257 if (CurFunctionDeclToDeclareForBlock)
4258 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
4259 int flag = 0;
4260 int isa = 0;
4261 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4262 if (DeclLoc.isInvalid())
4263 // If type location is missing, it is because of missing type (a warning).
4264 // Use variable's location which is good for this case.
4265 DeclLoc = ND->getLocation();
4266 const char *startBuf = SM->getCharacterData(DeclLoc);
4267 SourceLocation X = ND->getLocEnd();
4268 X = SM->getExpansionLoc(X);
4269 const char *endBuf = SM->getCharacterData(X);
4270 std::string Name(ND->getNameAsString());
4271 std::string ByrefType;
4272 RewriteByRefString(ByrefType, Name, ND, true);
4273 ByrefType += " {\n";
4274 ByrefType += " void *__isa;\n";
4275 RewriteByRefString(ByrefType, Name, ND);
4276 ByrefType += " *__forwarding;\n";
4277 ByrefType += " int __flags;\n";
4278 ByrefType += " int __size;\n";
4279 // Add void *__Block_byref_id_object_copy;
4280 // void *__Block_byref_id_object_dispose; if needed.
4281 QualType Ty = ND->getType();
4282 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4283 if (HasCopyAndDispose) {
4284 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4285 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4286 }
4287
4288 QualType T = Ty;
4289 (void)convertBlockPointerToFunctionPointer(T);
4290 T.getAsStringInternal(Name, Context->getPrintingPolicy());
4291
4292 ByrefType += " " + Name + ";\n";
4293 ByrefType += "};\n";
4294 // Insert this type in global scope. It is needed by helper function.
4295 SourceLocation FunLocStart;
4296 if (CurFunctionDef)
4297 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4298 else {
4299 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4300 FunLocStart = CurMethodDef->getLocStart();
4301 }
4302 InsertText(FunLocStart, ByrefType);
4303 if (Ty.isObjCGCWeak()) {
4304 flag |= BLOCK_FIELD_IS_WEAK;
4305 isa = 1;
4306 }
4307
4308 if (HasCopyAndDispose) {
4309 flag = BLOCK_BYREF_CALLER;
4310 QualType Ty = ND->getType();
4311 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4312 if (Ty->isBlockPointerType())
4313 flag |= BLOCK_FIELD_IS_BLOCK;
4314 else
4315 flag |= BLOCK_FIELD_IS_OBJECT;
4316 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
4317 if (!HF.empty())
4318 InsertText(FunLocStart, HF);
4319 }
4320
4321 // struct __Block_byref_ND ND =
4322 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4323 // initializer-if-any};
4324 bool hasInit = (ND->getInit() != 0);
4325 unsigned flags = 0;
4326 if (HasCopyAndDispose)
4327 flags |= BLOCK_HAS_COPY_DISPOSE;
4328 Name = ND->getNameAsString();
4329 ByrefType.clear();
4330 RewriteByRefString(ByrefType, Name, ND);
4331 std::string ForwardingCastType("(");
4332 ForwardingCastType += ByrefType + " *)";
4333 if (!hasInit) {
4334 ByrefType += " " + Name + " = {(void*)";
4335 ByrefType += utostr(isa);
4336 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4337 ByrefType += utostr(flags);
4338 ByrefType += ", ";
4339 ByrefType += "sizeof(";
4340 RewriteByRefString(ByrefType, Name, ND);
4341 ByrefType += ")";
4342 if (HasCopyAndDispose) {
4343 ByrefType += ", __Block_byref_id_object_copy_";
4344 ByrefType += utostr(flag);
4345 ByrefType += ", __Block_byref_id_object_dispose_";
4346 ByrefType += utostr(flag);
4347 }
4348 ByrefType += "};\n";
4349 unsigned nameSize = Name.size();
4350 // for block or function pointer declaration. Name is aleady
4351 // part of the declaration.
4352 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4353 nameSize = 1;
4354 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
4355 }
4356 else {
4357 SourceLocation startLoc;
4358 Expr *E = ND->getInit();
4359 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4360 startLoc = ECE->getLParenLoc();
4361 else
4362 startLoc = E->getLocStart();
4363 startLoc = SM->getExpansionLoc(startLoc);
4364 endBuf = SM->getCharacterData(startLoc);
4365 ByrefType += " " + Name;
4366 ByrefType += " = {(void*)";
4367 ByrefType += utostr(isa);
4368 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4369 ByrefType += utostr(flags);
4370 ByrefType += ", ";
4371 ByrefType += "sizeof(";
4372 RewriteByRefString(ByrefType, Name, ND);
4373 ByrefType += "), ";
4374 if (HasCopyAndDispose) {
4375 ByrefType += "__Block_byref_id_object_copy_";
4376 ByrefType += utostr(flag);
4377 ByrefType += ", __Block_byref_id_object_dispose_";
4378 ByrefType += utostr(flag);
4379 ByrefType += ", ";
4380 }
4381 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
4382
4383 // Complete the newly synthesized compound expression by inserting a right
4384 // curly brace before the end of the declaration.
4385 // FIXME: This approach avoids rewriting the initializer expression. It
4386 // also assumes there is only one declarator. For example, the following
4387 // isn't currently supported by this routine (in general):
4388 //
4389 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4390 //
4391 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4392 const char *semiBuf = strchr(startInitializerBuf, ';');
4393 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4394 SourceLocation semiLoc =
4395 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
4396
4397 InsertText(semiLoc, "}");
4398 }
4399 return;
4400}
4401
4402void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4403 // Add initializers for any closure decl refs.
4404 GetBlockDeclRefExprs(Exp->getBody());
4405 if (BlockDeclRefs.size()) {
4406 // Unique all "by copy" declarations.
4407 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004408 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004409 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4410 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4411 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4412 }
4413 }
4414 // Unique all "by ref" declarations.
4415 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004416 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004417 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4418 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4419 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4420 }
4421 }
4422 // Find any imported blocks...they will need special attention.
4423 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004424 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004425 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4426 BlockDeclRefs[i]->getType()->isBlockPointerType())
4427 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4428 }
4429}
4430
4431FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
4432 IdentifierInfo *ID = &Context->Idents.get(name);
4433 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
4434 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4435 SourceLocation(), ID, FType, 0, SC_Extern,
4436 SC_None, false, false);
4437}
4438
4439Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +00004440 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00004441
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004442 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00004443
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004444 Blocks.push_back(Exp);
4445
4446 CollectBlockDeclRefInfo(Exp);
4447
4448 // Add inner imported variables now used in current block.
4449 int countOfInnerDecls = 0;
4450 if (!InnerBlockDeclRefs.empty()) {
4451 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00004452 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004453 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00004454 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004455 // We need to save the copied-in variables in nested
4456 // blocks because it is needed at the end for some of the API generations.
4457 // See SynthesizeBlockLiterals routine.
4458 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4459 BlockDeclRefs.push_back(Exp);
4460 BlockByCopyDeclsPtrSet.insert(VD);
4461 BlockByCopyDecls.push_back(VD);
4462 }
John McCallf4b88a42012-03-10 09:33:50 +00004463 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004464 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4465 BlockDeclRefs.push_back(Exp);
4466 BlockByRefDeclsPtrSet.insert(VD);
4467 BlockByRefDecls.push_back(VD);
4468 }
4469 }
4470 // Find any imported blocks...they will need special attention.
4471 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004472 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004473 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4474 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4475 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
4476 }
4477 InnerDeclRefsCount.push_back(countOfInnerDecls);
4478
4479 std::string FuncName;
4480
4481 if (CurFunctionDef)
4482 FuncName = CurFunctionDef->getNameAsString();
4483 else if (CurMethodDef)
4484 BuildUniqueMethodName(FuncName, CurMethodDef);
4485 else if (GlobalVarDecl)
4486 FuncName = std::string(GlobalVarDecl->getNameAsString());
4487
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004488 bool GlobalBlockExpr =
4489 block->getDeclContext()->getRedeclContext()->isFileContext();
4490
4491 if (GlobalBlockExpr && !GlobalVarDecl) {
4492 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
4493 GlobalBlockExpr = false;
4494 }
4495
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004496 std::string BlockNumber = utostr(Blocks.size()-1);
4497
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004498 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4499
4500 // Get a pointer to the function type so we can cast appropriately.
4501 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4502 QualType FType = Context->getPointerType(BFT);
4503
4504 FunctionDecl *FD;
4505 Expr *NewRep;
4506
4507 // Simulate a contructor call...
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004508 std::string Tag;
4509
4510 if (GlobalBlockExpr)
4511 Tag = "__global_";
4512 else
4513 Tag = "__";
4514 Tag += FuncName + "_block_impl_" + BlockNumber;
4515
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004516 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00004517 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004518 SourceLocation());
4519
4520 SmallVector<Expr*, 4> InitExprs;
4521
4522 // Initialize the block function.
4523 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00004524 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4525 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004526 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4527 CK_BitCast, Arg);
4528 InitExprs.push_back(castExpr);
4529
4530 // Initialize the block descriptor.
4531 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
4532
4533 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
4534 SourceLocation(), SourceLocation(),
4535 &Context->Idents.get(DescData.c_str()),
4536 Context->VoidPtrTy, 0,
4537 SC_Static, SC_None);
4538 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00004539 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004540 Context->VoidPtrTy,
4541 VK_LValue,
4542 SourceLocation()),
4543 UO_AddrOf,
4544 Context->getPointerType(Context->VoidPtrTy),
4545 VK_RValue, OK_Ordinary,
4546 SourceLocation());
4547 InitExprs.push_back(DescRefExpr);
4548
4549 // Add initializers for any closure decl refs.
4550 if (BlockDeclRefs.size()) {
4551 Expr *Exp;
4552 // Output all "by copy" declarations.
4553 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4554 E = BlockByCopyDecls.end(); I != E; ++I) {
4555 if (isObjCType((*I)->getType())) {
4556 // FIXME: Conform to ABI ([[obj retain] autorelease]).
4557 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004558 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
4559 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004560 if (HasLocalVariableExternalStorage(*I)) {
4561 QualType QT = (*I)->getType();
4562 QT = Context->getPointerType(QT);
4563 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4564 OK_Ordinary, SourceLocation());
4565 }
4566 } else if (isTopLevelBlockPointerType((*I)->getType())) {
4567 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004568 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4569 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004570 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4571 CK_BitCast, Arg);
4572 } else {
4573 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004574 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
4575 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004576 if (HasLocalVariableExternalStorage(*I)) {
4577 QualType QT = (*I)->getType();
4578 QT = Context->getPointerType(QT);
4579 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4580 OK_Ordinary, SourceLocation());
4581 }
4582
4583 }
4584 InitExprs.push_back(Exp);
4585 }
4586 // Output all "by ref" declarations.
4587 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4588 E = BlockByRefDecls.end(); I != E; ++I) {
4589 ValueDecl *ND = (*I);
4590 std::string Name(ND->getNameAsString());
4591 std::string RecName;
4592 RewriteByRefString(RecName, Name, ND, true);
4593 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4594 + sizeof("struct"));
4595 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4596 SourceLocation(), SourceLocation(),
4597 II);
4598 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4599 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4600
4601 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004602 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004603 SourceLocation());
4604 bool isNestedCapturedVar = false;
4605 if (block)
4606 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
4607 ce = block->capture_end(); ci != ce; ++ci) {
4608 const VarDecl *variable = ci->getVariable();
4609 if (variable == ND && ci->isNested()) {
4610 assert (ci->isByRef() &&
4611 "SynthBlockInitExpr - captured block variable is not byref");
4612 isNestedCapturedVar = true;
4613 break;
4614 }
4615 }
4616 // captured nested byref variable has its address passed. Do not take
4617 // its address again.
4618 if (!isNestedCapturedVar)
4619 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
4620 Context->getPointerType(Exp->getType()),
4621 VK_RValue, OK_Ordinary, SourceLocation());
4622 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
4623 InitExprs.push_back(Exp);
4624 }
4625 }
4626 if (ImportedBlockDecls.size()) {
4627 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4628 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
4629 unsigned IntSize =
4630 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4631 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4632 Context->IntTy, SourceLocation());
4633 InitExprs.push_back(FlagExp);
4634 }
4635 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4636 FType, VK_LValue, SourceLocation());
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004637
4638 if (GlobalBlockExpr) {
4639 assert (GlobalConstructionExp == 0 &&
4640 "SynthBlockInitExpr - GlobalConstructionExp must be null");
4641 GlobalConstructionExp = NewRep;
4642 NewRep = DRE;
4643 }
4644
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004645 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
4646 Context->getPointerType(NewRep->getType()),
4647 VK_RValue, OK_Ordinary, SourceLocation());
4648 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
4649 NewRep);
4650 BlockDeclRefs.clear();
4651 BlockByRefDecls.clear();
4652 BlockByRefDeclsPtrSet.clear();
4653 BlockByCopyDecls.clear();
4654 BlockByCopyDeclsPtrSet.clear();
4655 ImportedBlockDecls.clear();
4656 return NewRep;
4657}
4658
4659bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4660 if (const ObjCForCollectionStmt * CS =
4661 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4662 return CS->getElement() == DS;
4663 return false;
4664}
4665
4666//===----------------------------------------------------------------------===//
4667// Function Body / Expression rewriting
4668//===----------------------------------------------------------------------===//
4669
4670Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4671 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4672 isa<DoStmt>(S) || isa<ForStmt>(S))
4673 Stmts.push_back(S);
4674 else if (isa<ObjCForCollectionStmt>(S)) {
4675 Stmts.push_back(S);
4676 ObjCBcLabelNo.push_back(++BcLabelCount);
4677 }
4678
4679 // Pseudo-object operations and ivar references need special
4680 // treatment because we're going to recursively rewrite them.
4681 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4682 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4683 return RewritePropertyOrImplicitSetter(PseudoOp);
4684 } else {
4685 return RewritePropertyOrImplicitGetter(PseudoOp);
4686 }
4687 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4688 return RewriteObjCIvarRefExpr(IvarRefExpr);
4689 }
4690
4691 SourceRange OrigStmtRange = S->getSourceRange();
4692
4693 // Perform a bottom up rewrite of all children.
4694 for (Stmt::child_range CI = S->children(); CI; ++CI)
4695 if (*CI) {
4696 Stmt *childStmt = (*CI);
4697 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
4698 if (newStmt) {
4699 *CI = newStmt;
4700 }
4701 }
4702
4703 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00004704 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004705 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4706 InnerContexts.insert(BE->getBlockDecl());
4707 ImportedLocalExternalDecls.clear();
4708 GetInnerBlockDeclRefExprs(BE->getBody(),
4709 InnerBlockDeclRefs, InnerContexts);
4710 // Rewrite the block body in place.
4711 Stmt *SaveCurrentBody = CurrentBody;
4712 CurrentBody = BE->getBody();
4713 PropParentMap = 0;
4714 // block literal on rhs of a property-dot-sytax assignment
4715 // must be replaced by its synthesize ast so getRewrittenText
4716 // works as expected. In this case, what actually ends up on RHS
4717 // is the blockTranscribed which is the helper function for the
4718 // block literal; as in: self.c = ^() {[ace ARR];};
4719 bool saveDisableReplaceStmt = DisableReplaceStmt;
4720 DisableReplaceStmt = false;
4721 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4722 DisableReplaceStmt = saveDisableReplaceStmt;
4723 CurrentBody = SaveCurrentBody;
4724 PropParentMap = 0;
4725 ImportedLocalExternalDecls.clear();
4726 // Now we snarf the rewritten text and stash it away for later use.
4727 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
4728 RewrittenBlockExprs[BE] = Str;
4729
4730 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4731
4732 //blockTranscribed->dump();
4733 ReplaceStmt(S, blockTranscribed);
4734 return blockTranscribed;
4735 }
4736 // Handle specific things.
4737 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4738 return RewriteAtEncode(AtEncode);
4739
4740 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4741 return RewriteAtSelector(AtSelector);
4742
4743 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4744 return RewriteObjCStringLiteral(AtString);
4745
4746 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
4747#if 0
4748 // Before we rewrite it, put the original message expression in a comment.
4749 SourceLocation startLoc = MessExpr->getLocStart();
4750 SourceLocation endLoc = MessExpr->getLocEnd();
4751
4752 const char *startBuf = SM->getCharacterData(startLoc);
4753 const char *endBuf = SM->getCharacterData(endLoc);
4754
4755 std::string messString;
4756 messString += "// ";
4757 messString.append(startBuf, endBuf-startBuf+1);
4758 messString += "\n";
4759
4760 // FIXME: Missing definition of
4761 // InsertText(clang::SourceLocation, char const*, unsigned int).
4762 // InsertText(startLoc, messString.c_str(), messString.size());
4763 // Tried this, but it didn't work either...
4764 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
4765#endif
4766 return RewriteMessageExpr(MessExpr);
4767 }
4768
4769 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4770 return RewriteObjCTryStmt(StmtTry);
4771
4772 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4773 return RewriteObjCSynchronizedStmt(StmtTry);
4774
4775 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4776 return RewriteObjCThrowStmt(StmtThrow);
4777
4778 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4779 return RewriteObjCProtocolExpr(ProtocolExp);
4780
4781 if (ObjCForCollectionStmt *StmtForCollection =
4782 dyn_cast<ObjCForCollectionStmt>(S))
4783 return RewriteObjCForCollectionStmt(StmtForCollection,
4784 OrigStmtRange.getEnd());
4785 if (BreakStmt *StmtBreakStmt =
4786 dyn_cast<BreakStmt>(S))
4787 return RewriteBreakStmt(StmtBreakStmt);
4788 if (ContinueStmt *StmtContinueStmt =
4789 dyn_cast<ContinueStmt>(S))
4790 return RewriteContinueStmt(StmtContinueStmt);
4791
4792 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4793 // and cast exprs.
4794 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4795 // FIXME: What we're doing here is modifying the type-specifier that
4796 // precedes the first Decl. In the future the DeclGroup should have
4797 // a separate type-specifier that we can rewrite.
4798 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4799 // the context of an ObjCForCollectionStmt. For example:
4800 // NSArray *someArray;
4801 // for (id <FooProtocol> index in someArray) ;
4802 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4803 // and it depends on the original text locations/positions.
4804 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
4805 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4806
4807 // Blocks rewrite rules.
4808 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4809 DI != DE; ++DI) {
4810 Decl *SD = *DI;
4811 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
4812 if (isTopLevelBlockPointerType(ND->getType()))
4813 RewriteBlockPointerDecl(ND);
4814 else if (ND->getType()->isFunctionPointerType())
4815 CheckFunctionPointerDecl(ND->getType(), ND);
4816 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
4817 if (VD->hasAttr<BlocksAttr>()) {
4818 static unsigned uniqueByrefDeclCount = 0;
4819 assert(!BlockByRefDeclNo.count(ND) &&
4820 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4821 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
4822 RewriteByRefVar(VD);
4823 }
4824 else
4825 RewriteTypeOfDecl(VD);
4826 }
4827 }
4828 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
4829 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4830 RewriteBlockPointerDecl(TD);
4831 else if (TD->getUnderlyingType()->isFunctionPointerType())
4832 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4833 }
4834 }
4835 }
4836
4837 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4838 RewriteObjCQualifiedInterfaceTypes(CE);
4839
4840 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4841 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4842 assert(!Stmts.empty() && "Statement stack is empty");
4843 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4844 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4845 && "Statement stack mismatch");
4846 Stmts.pop_back();
4847 }
4848 // Handle blocks rewriting.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004849 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4850 ValueDecl *VD = DRE->getDecl();
4851 if (VD->hasAttr<BlocksAttr>())
4852 return RewriteBlockDeclRefExpr(DRE);
4853 if (HasLocalVariableExternalStorage(VD))
4854 return RewriteLocalVariableExternalStorage(DRE);
4855 }
4856
4857 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4858 if (CE->getCallee()->getType()->isBlockPointerType()) {
4859 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
4860 ReplaceStmt(S, BlockCall);
4861 return BlockCall;
4862 }
4863 }
4864 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
4865 RewriteCastExpr(CE);
4866 }
4867#if 0
4868 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4869 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4870 ICE->getSubExpr(),
4871 SourceLocation());
4872 // Get the new text.
4873 std::string SStr;
4874 llvm::raw_string_ostream Buf(SStr);
4875 Replacement->printPretty(Buf, *Context);
4876 const std::string &Str = Buf.str();
4877
4878 printf("CAST = %s\n", &Str[0]);
4879 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4880 delete S;
4881 return Replacement;
4882 }
4883#endif
4884 // Return this stmt unmodified.
4885 return S;
4886}
4887
4888void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
4889 for (RecordDecl::field_iterator i = RD->field_begin(),
4890 e = RD->field_end(); i != e; ++i) {
4891 FieldDecl *FD = *i;
4892 if (isTopLevelBlockPointerType(FD->getType()))
4893 RewriteBlockPointerDecl(FD);
4894 if (FD->getType()->isObjCQualifiedIdType() ||
4895 FD->getType()->isObjCQualifiedInterfaceType())
4896 RewriteObjCQualifiedInterfaceTypes(FD);
4897 }
4898}
4899
4900/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4901/// main file of the input.
4902void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
4903 switch (D->getKind()) {
4904 case Decl::Function: {
4905 FunctionDecl *FD = cast<FunctionDecl>(D);
4906 if (FD->isOverloadedOperator())
4907 return;
4908
4909 // Since function prototypes don't have ParmDecl's, we check the function
4910 // prototype. This enables us to rewrite function declarations and
4911 // definitions using the same code.
4912 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
4913
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00004914 if (!FD->isThisDeclarationADefinition())
4915 break;
4916
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004917 // FIXME: If this should support Obj-C++, support CXXTryStmt
4918 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4919 CurFunctionDef = FD;
4920 CurFunctionDeclToDeclareForBlock = FD;
4921 CurrentBody = Body;
4922 Body =
4923 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4924 FD->setBody(Body);
4925 CurrentBody = 0;
4926 if (PropParentMap) {
4927 delete PropParentMap;
4928 PropParentMap = 0;
4929 }
4930 // This synthesizes and inserts the block "impl" struct, invoke function,
4931 // and any copy/dispose helper functions.
4932 InsertBlockLiteralsWithinFunction(FD);
4933 CurFunctionDef = 0;
4934 CurFunctionDeclToDeclareForBlock = 0;
4935 }
4936 break;
4937 }
4938 case Decl::ObjCMethod: {
4939 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
4940 if (CompoundStmt *Body = MD->getCompoundBody()) {
4941 CurMethodDef = MD;
4942 CurrentBody = Body;
4943 Body =
4944 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4945 MD->setBody(Body);
4946 CurrentBody = 0;
4947 if (PropParentMap) {
4948 delete PropParentMap;
4949 PropParentMap = 0;
4950 }
4951 InsertBlockLiteralsWithinMethod(MD);
4952 CurMethodDef = 0;
4953 }
4954 break;
4955 }
4956 case Decl::ObjCImplementation: {
4957 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
4958 ClassImplementation.push_back(CI);
4959 break;
4960 }
4961 case Decl::ObjCCategoryImpl: {
4962 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
4963 CategoryImplementation.push_back(CI);
4964 break;
4965 }
4966 case Decl::Var: {
4967 VarDecl *VD = cast<VarDecl>(D);
4968 RewriteObjCQualifiedInterfaceTypes(VD);
4969 if (isTopLevelBlockPointerType(VD->getType()))
4970 RewriteBlockPointerDecl(VD);
4971 else if (VD->getType()->isFunctionPointerType()) {
4972 CheckFunctionPointerDecl(VD->getType(), VD);
4973 if (VD->getInit()) {
4974 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4975 RewriteCastExpr(CE);
4976 }
4977 }
4978 } else if (VD->getType()->isRecordType()) {
4979 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4980 if (RD->isCompleteDefinition())
4981 RewriteRecordBody(RD);
4982 }
4983 if (VD->getInit()) {
4984 GlobalVarDecl = VD;
4985 CurrentBody = VD->getInit();
4986 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
4987 CurrentBody = 0;
4988 if (PropParentMap) {
4989 delete PropParentMap;
4990 PropParentMap = 0;
4991 }
4992 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
4993 GlobalVarDecl = 0;
4994
4995 // This is needed for blocks.
4996 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4997 RewriteCastExpr(CE);
4998 }
4999 }
5000 break;
5001 }
5002 case Decl::TypeAlias:
5003 case Decl::Typedef: {
5004 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5005 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5006 RewriteBlockPointerDecl(TD);
5007 else if (TD->getUnderlyingType()->isFunctionPointerType())
5008 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5009 }
5010 break;
5011 }
5012 case Decl::CXXRecord:
5013 case Decl::Record: {
5014 RecordDecl *RD = cast<RecordDecl>(D);
5015 if (RD->isCompleteDefinition())
5016 RewriteRecordBody(RD);
5017 break;
5018 }
5019 default:
5020 break;
5021 }
5022 // Nothing yet.
5023}
5024
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005025/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5026/// protocol reference symbols in the for of:
5027/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5028static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5029 ObjCProtocolDecl *PDecl,
5030 std::string &Result) {
5031 // Also output .objc_protorefs$B section and its meta-data.
5032 if (Context->getLangOpts().MicrosoftExt)
5033 Result += "__declspec(allocate(\".objc_protorefs$B\")) ";
5034 Result += "struct _protocol_t *";
5035 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5036 Result += PDecl->getNameAsString();
5037 Result += " = &";
5038 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5039 Result += ";\n";
5040}
5041
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005042void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5043 if (Diags.hasErrorOccurred())
5044 return;
5045
5046 RewriteInclude();
5047
5048 // Here's a great place to add any extra declarations that may be needed.
5049 // Write out meta data for each @protocol(<expr>).
5050 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005051 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005052 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005053 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
5054 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005055
5056 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian57317782012-02-21 23:58:41 +00005057 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5058 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5059 // Write struct declaration for the class matching its ivar declarations.
5060 // Note that for modern abi, this is postponed until the end of TU
5061 // because class extensions and the implementation might declare their own
5062 // private ivars.
5063 RewriteInterfaceDecl(CDecl);
5064 }
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00005065
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005066 if (ClassImplementation.size() || CategoryImplementation.size())
5067 RewriteImplementations();
5068
5069 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5070 // we are done.
5071 if (const RewriteBuffer *RewriteBuf =
5072 Rewrite.getRewriteBufferFor(MainFileID)) {
5073 //printf("Changed:\n");
5074 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5075 } else {
5076 llvm::errs() << "No changes\n";
5077 }
5078
5079 if (ClassImplementation.size() || CategoryImplementation.size() ||
5080 ProtocolExprDecls.size()) {
5081 // Rewrite Objective-c meta data*
5082 std::string ResultStr;
5083 RewriteMetaDataIntoBuffer(ResultStr);
5084 // Emit metadata.
5085 *OutFile << ResultStr;
5086 }
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005087 // Emit ImageInfo;
5088 {
5089 std::string ResultStr;
5090 WriteImageInfo(ResultStr);
5091 *OutFile << ResultStr;
5092 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005093 OutFile->flush();
5094}
5095
5096void RewriteModernObjC::Initialize(ASTContext &context) {
5097 InitializeCommon(context);
5098
Fariborz Jahanian6991bc52012-03-10 17:45:38 +00005099 Preamble += "#ifndef __OBJC2__\n";
5100 Preamble += "#define __OBJC2__\n";
5101 Preamble += "#endif\n";
5102
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005103 // declaring objc_selector outside the parameter list removes a silly
5104 // scope related warning...
5105 if (IsHeader)
5106 Preamble = "#pragma once\n";
5107 Preamble += "struct objc_selector; struct objc_class;\n";
5108 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
5109 Preamble += "struct objc_object *superClass; ";
5110 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005111 // Define all sections using syntax that makes sense.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005112 // These are currently generated.
5113 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005114 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005115 Preamble += "#pragma section(\".objc_protolist$B\", long, read, write)\n";
5116 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005117 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5118 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005119 Preamble += "#pragma section(\".objc_protorefs$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005120 // These are generated but not necessary for functionality.
5121 Preamble += "#pragma section(\".datacoal_nt$B\", long, read, write)\n";
5122 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005123 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5124 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005125 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005126
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005127 // These need be generated for performance. Currently they are not,
5128 // using API calls instead.
5129 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5130 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5131 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5132
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005133 // Add a constructor for creating temporary objects.
5134 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
5135 ": ";
5136 Preamble += "object(o), superClass(s) {} ";
5137 }
5138 Preamble += "};\n";
5139 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5140 Preamble += "typedef struct objc_object Protocol;\n";
5141 Preamble += "#define _REWRITER_typedef_Protocol\n";
5142 Preamble += "#endif\n";
5143 if (LangOpts.MicrosoftExt) {
5144 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5145 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005146 }
5147 else
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005148 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005149
5150 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
5151 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
5152 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
5153 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
5154 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
5155
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005156 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5157 Preamble += "(const char *);\n";
5158 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5159 Preamble += "(struct objc_class *);\n";
5160 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5161 Preamble += "(const char *);\n";
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005162 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005163 // @synchronized hooks.
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005164 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter( struct objc_object *);\n";
5165 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005166 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5167 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5168 Preamble += "struct __objcFastEnumerationState {\n\t";
5169 Preamble += "unsigned long state;\n\t";
5170 Preamble += "void **itemsPtr;\n\t";
5171 Preamble += "unsigned long *mutationsPtr;\n\t";
5172 Preamble += "unsigned long extra[5];\n};\n";
5173 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5174 Preamble += "#define __FASTENUMERATIONSTATE\n";
5175 Preamble += "#endif\n";
5176 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5177 Preamble += "struct __NSConstantStringImpl {\n";
5178 Preamble += " int *isa;\n";
5179 Preamble += " int flags;\n";
5180 Preamble += " char *str;\n";
5181 Preamble += " long length;\n";
5182 Preamble += "};\n";
5183 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5184 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5185 Preamble += "#else\n";
5186 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5187 Preamble += "#endif\n";
5188 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5189 Preamble += "#endif\n";
5190 // Blocks preamble.
5191 Preamble += "#ifndef BLOCK_IMPL\n";
5192 Preamble += "#define BLOCK_IMPL\n";
5193 Preamble += "struct __block_impl {\n";
5194 Preamble += " void *isa;\n";
5195 Preamble += " int Flags;\n";
5196 Preamble += " int Reserved;\n";
5197 Preamble += " void *FuncPtr;\n";
5198 Preamble += "};\n";
5199 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5200 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5201 Preamble += "extern \"C\" __declspec(dllexport) "
5202 "void _Block_object_assign(void *, const void *, const int);\n";
5203 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5204 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5205 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5206 Preamble += "#else\n";
5207 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5208 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5209 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5210 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5211 Preamble += "#endif\n";
5212 Preamble += "#endif\n";
5213 if (LangOpts.MicrosoftExt) {
5214 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5215 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5216 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5217 Preamble += "#define __attribute__(X)\n";
5218 Preamble += "#endif\n";
5219 Preamble += "#define __weak\n";
5220 }
5221 else {
5222 Preamble += "#define __block\n";
5223 Preamble += "#define __weak\n";
5224 }
5225 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5226 // as this avoids warning in any 64bit/32bit compilation model.
5227 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5228}
5229
5230/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5231/// ivar offset.
5232void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5233 std::string &Result) {
5234 if (ivar->isBitField()) {
5235 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5236 // place all bitfields at offset 0.
5237 Result += "0";
5238 } else {
5239 Result += "__OFFSETOFIVAR__(struct ";
5240 Result += ivar->getContainingInterface()->getNameAsString();
5241 if (LangOpts.MicrosoftExt)
5242 Result += "_IMPL";
5243 Result += ", ";
5244 Result += ivar->getNameAsString();
5245 Result += ")";
5246 }
5247}
5248
5249/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
5250/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005251/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005252/// char *attributes;
5253/// }
5254
5255/// struct _prop_list_t {
5256/// uint32_t entsize; // sizeof(struct _prop_t)
5257/// uint32_t count_of_properties;
5258/// struct _prop_t prop_list[count_of_properties];
5259/// }
5260
5261/// struct _protocol_t;
5262
5263/// struct _protocol_list_t {
5264/// long protocol_count; // Note, this is 32/64 bit
5265/// struct _protocol_t * protocol_list[protocol_count];
5266/// }
5267
5268/// struct _objc_method {
5269/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005270/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005271/// char *_imp;
5272/// }
5273
5274/// struct _method_list_t {
5275/// uint32_t entsize; // sizeof(struct _objc_method)
5276/// uint32_t method_count;
5277/// struct _objc_method method_list[method_count];
5278/// }
5279
5280/// struct _protocol_t {
5281/// id isa; // NULL
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005282/// const char *protocol_name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005283/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005284/// const struct method_list_t *instance_methods;
5285/// const struct method_list_t *class_methods;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005286/// const struct method_list_t *optionalInstanceMethods;
5287/// const struct method_list_t *optionalClassMethods;
5288/// const struct _prop_list_t * properties;
5289/// const uint32_t size; // sizeof(struct _protocol_t)
5290/// const uint32_t flags; // = 0
5291/// const char ** extendedMethodTypes;
5292/// }
5293
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005294/// struct _ivar_t {
5295/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00005296/// const char *name;
5297/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005298/// uint32_t alignment;
5299/// uint32_t size;
5300/// }
5301
5302/// struct _ivar_list_t {
5303/// uint32 entsize; // sizeof(struct _ivar_t)
5304/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00005305/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005306/// }
5307
5308/// struct _class_ro_t {
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005309/// uint32_t flags;
5310/// uint32_t instanceStart;
5311/// uint32_t instanceSize;
5312/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005313/// const uint8_t *ivarLayout;
5314/// const char *name;
5315/// const struct _method_list_t *baseMethods;
5316/// const struct _protocol_list_t *baseProtocols;
5317/// const struct _ivar_list_t *ivars;
5318/// const uint8_t *weakIvarLayout;
5319/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005320/// }
5321
5322/// struct _class_t {
5323/// struct _class_t *isa;
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00005324/// struct _class_t *superclass;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005325/// void *cache;
5326/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005327/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005328/// }
5329
5330/// struct _category_t {
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005331/// const char *name;
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005332/// struct _class_t *cls;
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005333/// const struct _method_list_t *instance_methods;
5334/// const struct _method_list_t *class_methods;
5335/// const struct _protocol_list_t *protocols;
5336/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005337/// }
5338
5339/// MessageRefTy - LLVM for:
5340/// struct _message_ref_t {
5341/// IMP messenger;
5342/// SEL name;
5343/// };
5344
5345/// SuperMessageRefTy - LLVM for:
5346/// struct _super_message_ref_t {
5347/// SUPER_IMP messenger;
5348/// SEL name;
5349/// };
5350
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005351static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005352 static bool meta_data_declared = false;
5353 if (meta_data_declared)
5354 return;
5355
5356 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005357 Result += "\tconst char *name;\n";
5358 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005359 Result += "};\n";
5360
5361 Result += "\nstruct _protocol_t;\n";
5362
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005363 Result += "\nstruct _objc_method {\n";
5364 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005365 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005366 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005367 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005368
5369 Result += "\nstruct _protocol_t {\n";
5370 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005371 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005372 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005373 Result += "\tconst struct method_list_t *instance_methods;\n";
5374 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005375 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
5376 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
5377 Result += "\tconst struct _prop_list_t * properties;\n";
5378 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
5379 Result += "\tconst unsigned int flags; // = 0\n";
5380 Result += "\tconst char ** extendedMethodTypes;\n";
5381 Result += "};\n";
5382
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005383 Result += "\nstruct _ivar_t {\n";
5384 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005385 Result += "\tconst char *name;\n";
5386 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005387 Result += "\tunsigned int alignment;\n";
5388 Result += "\tunsigned int size;\n";
5389 Result += "};\n";
5390
5391 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005392 Result += "\tunsigned int flags;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005393 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005394 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005395 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
5396 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005397 Result += "\tunsigned int reserved;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005398 Result += "\tconst unsigned char *ivarLayout;\n";
5399 Result += "\tconst char *name;\n";
5400 Result += "\tconst struct _method_list_t *baseMethods;\n";
5401 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
5402 Result += "\tconst struct _ivar_list_t *ivars;\n";
5403 Result += "\tconst unsigned char *weakIvarLayout;\n";
5404 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005405 Result += "};\n";
5406
5407 Result += "\nstruct _class_t {\n";
5408 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00005409 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005410 Result += "\tvoid *cache;\n";
5411 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005412 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005413 Result += "};\n";
5414
5415 Result += "\nstruct _category_t {\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005416 Result += "\tconst char *name;\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005417 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005418 Result += "\tconst struct _method_list_t *instance_methods;\n";
5419 Result += "\tconst struct _method_list_t *class_methods;\n";
5420 Result += "\tconst struct _protocol_list_t *protocols;\n";
5421 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005422 Result += "};\n";
5423
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005424 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005425
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005426 meta_data_declared = true;
5427}
5428
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005429static void Write_protocol_list_t_TypeDecl(std::string &Result,
5430 long super_protocol_count) {
5431 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
5432 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
5433 Result += "\tstruct _protocol_t *super_protocols[";
5434 Result += utostr(super_protocol_count); Result += "];\n";
5435 Result += "}";
5436}
5437
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005438static void Write_method_list_t_TypeDecl(std::string &Result,
5439 unsigned int method_count) {
5440 Result += "struct /*_method_list_t*/"; Result += " {\n";
5441 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
5442 Result += "\tunsigned int method_count;\n";
5443 Result += "\tstruct _objc_method method_list[";
5444 Result += utostr(method_count); Result += "];\n";
5445 Result += "}";
5446}
5447
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005448static void Write__prop_list_t_TypeDecl(std::string &Result,
5449 unsigned int property_count) {
5450 Result += "struct /*_prop_list_t*/"; Result += " {\n";
5451 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5452 Result += "\tunsigned int count_of_properties;\n";
5453 Result += "\tstruct _prop_t prop_list[";
5454 Result += utostr(property_count); Result += "];\n";
5455 Result += "}";
5456}
5457
Fariborz Jahanianae932952012-02-10 20:47:10 +00005458static void Write__ivar_list_t_TypeDecl(std::string &Result,
5459 unsigned int ivar_count) {
5460 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
5461 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5462 Result += "\tunsigned int count;\n";
5463 Result += "\tstruct _ivar_t ivar_list[";
5464 Result += utostr(ivar_count); Result += "];\n";
5465 Result += "}";
5466}
5467
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005468static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
5469 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
5470 StringRef VarName,
5471 StringRef ProtocolName) {
5472 if (SuperProtocols.size() > 0) {
5473 Result += "\nstatic ";
5474 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
5475 Result += " "; Result += VarName;
5476 Result += ProtocolName;
5477 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5478 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
5479 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
5480 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
5481 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
5482 Result += SuperPD->getNameAsString();
5483 if (i == e-1)
5484 Result += "\n};\n";
5485 else
5486 Result += ",\n";
5487 }
5488 }
5489}
5490
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005491static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
5492 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005493 ArrayRef<ObjCMethodDecl *> Methods,
5494 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005495 StringRef TopLevelDeclName,
5496 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005497 if (Methods.size() > 0) {
5498 Result += "\nstatic ";
5499 Write_method_list_t_TypeDecl(Result, Methods.size());
5500 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005501 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005502 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5503 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
5504 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
5505 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
5506 ObjCMethodDecl *MD = Methods[i];
5507 if (i == 0)
5508 Result += "\t{{(struct objc_selector *)\"";
5509 else
5510 Result += "\t{(struct objc_selector *)\"";
5511 Result += (MD)->getSelector().getAsString(); Result += "\"";
5512 Result += ", ";
5513 std::string MethodTypeString;
5514 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
5515 Result += "\""; Result += MethodTypeString; Result += "\"";
5516 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005517 if (!MethodImpl)
5518 Result += "0";
5519 else {
5520 Result += "(void *)";
5521 Result += RewriteObj.MethodInternalNames[MD];
5522 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005523 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005524 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005525 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005526 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005527 }
5528 Result += "};\n";
5529 }
5530}
5531
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005532static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005533 ASTContext *Context, std::string &Result,
5534 ArrayRef<ObjCPropertyDecl *> Properties,
5535 const Decl *Container,
5536 StringRef VarName,
5537 StringRef ProtocolName) {
5538 if (Properties.size() > 0) {
5539 Result += "\nstatic ";
5540 Write__prop_list_t_TypeDecl(Result, Properties.size());
5541 Result += " "; Result += VarName;
5542 Result += ProtocolName;
5543 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5544 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
5545 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
5546 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
5547 ObjCPropertyDecl *PropDecl = Properties[i];
5548 if (i == 0)
5549 Result += "\t{{\"";
5550 else
5551 Result += "\t{\"";
5552 Result += PropDecl->getName(); Result += "\",";
5553 std::string PropertyTypeString, QuotePropertyTypeString;
5554 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
5555 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
5556 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
5557 if (i == e-1)
5558 Result += "}}\n";
5559 else
5560 Result += "},\n";
5561 }
5562 Result += "};\n";
5563 }
5564}
5565
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005566// Metadata flags
5567enum MetaDataDlags {
5568 CLS = 0x0,
5569 CLS_META = 0x1,
5570 CLS_ROOT = 0x2,
5571 OBJC2_CLS_HIDDEN = 0x10,
5572 CLS_EXCEPTION = 0x20,
5573
5574 /// (Obsolete) ARC-specific: this class has a .release_ivars method
5575 CLS_HAS_IVAR_RELEASER = 0x40,
5576 /// class was compiled with -fobjc-arr
5577 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
5578};
5579
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005580static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
5581 unsigned int flags,
5582 const std::string &InstanceStart,
5583 const std::string &InstanceSize,
5584 ArrayRef<ObjCMethodDecl *>baseMethods,
5585 ArrayRef<ObjCProtocolDecl *>baseProtocols,
5586 ArrayRef<ObjCIvarDecl *>ivars,
5587 ArrayRef<ObjCPropertyDecl *>Properties,
5588 StringRef VarName,
5589 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005590 Result += "\nstatic struct _class_ro_t ";
5591 Result += VarName; Result += ClassName;
5592 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5593 Result += "\t";
5594 Result += llvm::utostr(flags); Result += ", ";
5595 Result += InstanceStart; Result += ", ";
5596 Result += InstanceSize; Result += ", \n";
5597 Result += "\t";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005598 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
5599 if (Triple.getArch() == llvm::Triple::x86_64)
5600 // uint32_t const reserved; // only when building for 64bit targets
5601 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005602 // const uint8_t * const ivarLayout;
5603 Result += "0, \n\t";
5604 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005605 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005606 if (baseMethods.size() > 0) {
5607 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005608 if (metaclass)
5609 Result += "_OBJC_$_CLASS_METHODS_";
5610 else
5611 Result += "_OBJC_$_INSTANCE_METHODS_";
5612 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005613 Result += ",\n\t";
5614 }
5615 else
5616 Result += "0, \n\t";
5617
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005618 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005619 Result += "(const struct _objc_protocol_list *)&";
5620 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
5621 Result += ",\n\t";
5622 }
5623 else
5624 Result += "0, \n\t";
5625
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005626 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005627 Result += "(const struct _ivar_list_t *)&";
5628 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
5629 Result += ",\n\t";
5630 }
5631 else
5632 Result += "0, \n\t";
5633
5634 // weakIvarLayout
5635 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005636 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005637 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00005638 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005639 Result += ",\n";
5640 }
5641 else
5642 Result += "0, \n";
5643
5644 Result += "};\n";
5645}
5646
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005647static void Write_class_t(ASTContext *Context, std::string &Result,
5648 StringRef VarName,
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005649 const ObjCInterfaceDecl *CDecl, bool metaclass) {
5650 bool rootClass = (!CDecl->getSuperClass());
5651 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005652
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005653 if (!rootClass) {
5654 // Find the Root class
5655 RootClass = CDecl->getSuperClass();
5656 while (RootClass->getSuperClass()) {
5657 RootClass = RootClass->getSuperClass();
5658 }
5659 }
5660
5661 if (metaclass && rootClass) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005662 // Need to handle a case of use of forward declaration.
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005663 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005664 Result += "extern \"C\" ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005665 if (CDecl->getImplementation())
5666 Result += "__declspec(dllexport) ";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005667 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005668 Result += CDecl->getNameAsString();
5669 Result += ";\n";
5670 }
5671 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005672 if (!rootClass) {
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005673 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005674 Result += "extern \"C\" ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005675 if (CDecl->getSuperClass()->getImplementation())
5676 Result += "__declspec(dllexport) ";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005677 Result += "struct _class_t ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005678 Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005679 Result += CDecl->getSuperClass()->getNameAsString();
5680 Result += ";\n";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00005681
5682 if (metaclass) {
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005683 Result += "extern \"C\" ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00005684 if (RootClass->getImplementation())
5685 Result += "__declspec(dllexport) ";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005686 Result += "struct _class_t ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00005687 Result += VarName;
5688 Result += RootClass->getNameAsString();
5689 Result += ";\n";
5690 }
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005691 }
5692
Fariborz Jahaniane57303c2012-03-10 00:39:34 +00005693 Result += "\n__declspec(dllexport) struct _class_t "; Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005694 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
5695 Result += "\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005696 if (metaclass) {
5697 if (!rootClass) {
5698 Result += "0, // &"; Result += VarName;
5699 Result += RootClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005700 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005701 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005702 Result += CDecl->getSuperClass()->getNameAsString();
5703 Result += ",\n\t";
5704 }
5705 else {
Fariborz Jahanian452eac12012-03-20 21:09:58 +00005706 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005707 Result += CDecl->getNameAsString();
5708 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005709 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005710 Result += ",\n\t";
5711 }
5712 }
5713 else {
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005714 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005715 Result += CDecl->getNameAsString();
5716 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005717 if (!rootClass) {
5718 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005719 Result += CDecl->getSuperClass()->getNameAsString();
5720 Result += ",\n\t";
5721 }
5722 else
5723 Result += "0,\n\t";
5724 }
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005725 Result += "0, // (void *)&_objc_empty_cache,\n\t";
5726 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
5727 if (metaclass)
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005728 Result += "&_OBJC_METACLASS_RO_$_";
5729 else
5730 Result += "&_OBJC_CLASS_RO_$_";
5731 Result += CDecl->getNameAsString();
5732 Result += ",\n};\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005733
5734 // Add static function to initialize some of the meta-data fields.
5735 // avoid doing it twice.
5736 if (metaclass)
5737 return;
5738
5739 const ObjCInterfaceDecl *SuperClass =
5740 rootClass ? CDecl : CDecl->getSuperClass();
5741
5742 Result += "static void OBJC_CLASS_SETUP_$_";
5743 Result += CDecl->getNameAsString();
5744 Result += "(void ) {\n";
5745 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
5746 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00005747 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005748
5749 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian452eac12012-03-20 21:09:58 +00005750 Result += ".superclass = ";
5751 if (rootClass)
5752 Result += "&OBJC_CLASS_$_";
5753 else
5754 Result += "&OBJC_METACLASS_$_";
5755
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005756 Result += SuperClass->getNameAsString(); Result += ";\n";
5757
5758 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
5759 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
5760
5761 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
5762 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
5763 Result += CDecl->getNameAsString(); Result += ";\n";
5764
5765 if (!rootClass) {
5766 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
5767 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
5768 Result += SuperClass->getNameAsString(); Result += ";\n";
5769 }
5770
5771 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
5772 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
5773 Result += "}\n";
5774
Fariborz Jahanianfde05e12012-03-21 00:01:15 +00005775 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005776 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
5777 Result += "static void *OBJC_CLASS_SETUP2_$_";
5778 Result += CDecl->getNameAsString();
5779 Result += " = (void *)&OBJC_CLASS_SETUP_$_";
5780 Result += CDecl->getNameAsString();
5781 Result += ";\n\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005782}
5783
Fariborz Jahanian61186122012-02-17 18:40:41 +00005784static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
5785 std::string &Result,
5786 StringRef CatName,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005787 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00005788 ArrayRef<ObjCMethodDecl *> InstanceMethods,
5789 ArrayRef<ObjCMethodDecl *> ClassMethods,
5790 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
5791 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005792
NAKAMURA Takumi20f89392012-03-21 03:21:46 +00005793 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00005794 // must declare an extern class object in case this class is not implemented
5795 // in this TU.
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005796 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005797 Result += "extern \"C\" ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005798 if (ClassDecl->getImplementation())
5799 Result += "__declspec(dllexport) ";
5800
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005801 Result += "struct _class_t ";
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00005802 Result += "OBJC_CLASS_$_"; Result += ClassName;
5803 Result += ";\n";
5804
Fariborz Jahanian61186122012-02-17 18:40:41 +00005805 Result += "\nstatic struct _category_t ";
5806 Result += "_OBJC_$_CATEGORY_";
5807 Result += ClassName; Result += "_$_"; Result += CatName;
5808 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
5809 Result += "{\n";
5810 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005811 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanian61186122012-02-17 18:40:41 +00005812 Result += ",\n";
5813 if (InstanceMethods.size() > 0) {
5814 Result += "\t(const struct _method_list_t *)&";
5815 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
5816 Result += ClassName; Result += "_$_"; Result += CatName;
5817 Result += ",\n";
5818 }
5819 else
5820 Result += "\t0,\n";
5821
5822 if (ClassMethods.size() > 0) {
5823 Result += "\t(const struct _method_list_t *)&";
5824 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
5825 Result += ClassName; Result += "_$_"; Result += CatName;
5826 Result += ",\n";
5827 }
5828 else
5829 Result += "\t0,\n";
5830
5831 if (RefedProtocols.size() > 0) {
5832 Result += "\t(const struct _protocol_list_t *)&";
5833 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
5834 Result += ClassName; Result += "_$_"; Result += CatName;
5835 Result += ",\n";
5836 }
5837 else
5838 Result += "\t0,\n";
5839
5840 if (ClassProperties.size() > 0) {
5841 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
5842 Result += ClassName; Result += "_$_"; Result += CatName;
5843 Result += ",\n";
5844 }
5845 else
5846 Result += "\t0,\n";
5847
5848 Result += "};\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005849
5850 // Add static function to initialize the class pointer in the category structure.
5851 Result += "static void OBJC_CATEGORY_SETUP_$_";
5852 Result += ClassDecl->getNameAsString();
5853 Result += "_$_";
5854 Result += CatName;
5855 Result += "(void ) {\n";
5856 Result += "\t_OBJC_$_CATEGORY_";
5857 Result += ClassDecl->getNameAsString();
5858 Result += "_$_";
5859 Result += CatName;
5860 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
5861 Result += ";\n}\n";
5862
Fariborz Jahanianfde05e12012-03-21 00:01:15 +00005863 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005864 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
5865 Result += "static void *OBJC_CATEGORY_SETUP2_$_";
5866 Result += ClassDecl->getNameAsString();
5867 Result += "_$_";
5868 Result += CatName;
5869 Result += " = (void *)&OBJC_CATEGORY_SETUP_$_";
5870 Result += ClassDecl->getNameAsString();
5871 Result += "_$_";
5872 Result += CatName;
5873 Result += ";\n\n";
Fariborz Jahanian61186122012-02-17 18:40:41 +00005874}
5875
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00005876static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
5877 ASTContext *Context, std::string &Result,
5878 ArrayRef<ObjCMethodDecl *> Methods,
5879 StringRef VarName,
5880 StringRef ProtocolName) {
5881 if (Methods.size() == 0)
5882 return;
5883
5884 Result += "\nstatic const char *";
5885 Result += VarName; Result += ProtocolName;
5886 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
5887 Result += "{\n";
5888 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
5889 ObjCMethodDecl *MD = Methods[i];
5890 std::string MethodTypeString, QuoteMethodTypeString;
5891 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
5892 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
5893 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
5894 if (i == e-1)
5895 Result += "\n};\n";
5896 else {
5897 Result += ",\n";
5898 }
5899 }
5900}
5901
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005902static void Write_IvarOffsetVar(ASTContext *Context,
5903 std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005904 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00005905 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005906 // FIXME. visibilty of offset symbols may have to be set; for Darwin
5907 // this is what happens:
5908 /**
5909 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
5910 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
5911 Class->getVisibility() == HiddenVisibility)
5912 Visibility shoud be: HiddenVisibility;
5913 else
5914 Visibility shoud be: DefaultVisibility;
5915 */
5916
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005917 Result += "\n";
5918 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
5919 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005920 if (Context->getLangOpts().MicrosoftExt)
5921 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
5922
5923 if (!Context->getLangOpts().MicrosoftExt ||
5924 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanian117591f2012-03-10 01:34:42 +00005925 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahaniand1c84d32012-03-10 00:53:02 +00005926 Result += "unsigned long int ";
5927 else
5928 Result += "__declspec(dllexport) unsigned long int ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00005929 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005930 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
5931 Result += " = ";
5932 if (IvarDecl->isBitField()) {
5933 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5934 // place all bitfields at offset 0.
5935 Result += "0;\n";
5936 }
5937 else {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005938 Result += "__OFFSETOFIVAR__(struct ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00005939 Result += CDecl->getNameAsString();
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005940 Result += "_IMPL, ";
5941 Result += IvarDecl->getName(); Result += ");\n";
5942 }
5943 }
5944}
5945
Fariborz Jahanianae932952012-02-10 20:47:10 +00005946static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
5947 ASTContext *Context, std::string &Result,
5948 ArrayRef<ObjCIvarDecl *> Ivars,
5949 StringRef VarName,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00005950 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanianae932952012-02-10 20:47:10 +00005951 if (Ivars.size() > 0) {
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00005952 Write_IvarOffsetVar(Context, Result, Ivars, CDecl);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005953
Fariborz Jahanianae932952012-02-10 20:47:10 +00005954 Result += "\nstatic ";
5955 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
5956 Result += " "; Result += VarName;
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00005957 Result += CDecl->getNameAsString();
Fariborz Jahanianae932952012-02-10 20:47:10 +00005958 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5959 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
5960 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
5961 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
5962 ObjCIvarDecl *IvarDecl = Ivars[i];
5963 if (i == 0)
5964 Result += "\t{{";
5965 else
5966 Result += "\t {";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00005967 Result += "(unsigned long int *)&";
5968 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005969 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005970
5971 Result += "\""; Result += IvarDecl->getName(); Result += "\", ";
5972 std::string IvarTypeString, QuoteIvarTypeString;
5973 Context->getObjCEncodingForType(IvarDecl->getType(), IvarTypeString,
5974 IvarDecl);
5975 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
5976 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
5977
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00005978 // FIXME. this alignment represents the host alignment and need be changed to
5979 // represent the target alignment.
5980 unsigned Align = Context->getTypeAlign(IvarDecl->getType())/8;
5981 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00005982 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00005983 CharUnits Size = Context->getTypeSizeInChars(IvarDecl->getType());
5984 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00005985 if (i == e-1)
5986 Result += "}}\n";
5987 else
5988 Result += "},\n";
5989 }
5990 Result += "};\n";
5991 }
5992}
5993
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005994/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005995void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
5996 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005997
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005998 // Do not synthesize the protocol more than once.
5999 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6000 return;
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006001 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006002
6003 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6004 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006005 // Must write out all protocol definitions in current qualifier list,
6006 // and in their nested qualifiers before writing out current definition.
6007 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6008 E = PDecl->protocol_end(); I != E; ++I)
6009 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006010
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006011 // Construct method lists.
6012 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6013 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
6014 for (ObjCProtocolDecl::instmeth_iterator
6015 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
6016 I != E; ++I) {
6017 ObjCMethodDecl *MD = *I;
6018 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6019 OptInstanceMethods.push_back(MD);
6020 } else {
6021 InstanceMethods.push_back(MD);
6022 }
6023 }
6024
6025 for (ObjCProtocolDecl::classmeth_iterator
6026 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
6027 I != E; ++I) {
6028 ObjCMethodDecl *MD = *I;
6029 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6030 OptClassMethods.push_back(MD);
6031 } else {
6032 ClassMethods.push_back(MD);
6033 }
6034 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006035 std::vector<ObjCMethodDecl *> AllMethods;
6036 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6037 AllMethods.push_back(InstanceMethods[i]);
6038 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6039 AllMethods.push_back(ClassMethods[i]);
6040 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6041 AllMethods.push_back(OptInstanceMethods[i]);
6042 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6043 AllMethods.push_back(OptClassMethods[i]);
6044
6045 Write__extendedMethodTypes_initializer(*this, Context, Result,
6046 AllMethods,
6047 "_OBJC_PROTOCOL_METHOD_TYPES_",
6048 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006049 // Protocol's super protocol list
6050 std::vector<ObjCProtocolDecl *> SuperProtocols;
6051 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6052 E = PDecl->protocol_end(); I != E; ++I)
6053 SuperProtocols.push_back(*I);
6054
6055 Write_protocol_list_initializer(Context, Result, SuperProtocols,
6056 "_OBJC_PROTOCOL_REFS_",
6057 PDecl->getNameAsString());
6058
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006059 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006060 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006061 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006062
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006063 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006064 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006065 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006066
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006067 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006068 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006069 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006070
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006071 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006072 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006073 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006074
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006075 // Protocol's property metadata.
6076 std::vector<ObjCPropertyDecl *> ProtocolProperties;
6077 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
6078 E = PDecl->prop_end(); I != E; ++I)
6079 ProtocolProperties.push_back(*I);
6080
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006081 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006082 /* Container */0,
6083 "_OBJC_PROTOCOL_PROPERTIES_",
6084 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006085
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006086 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006087 Result += "\n";
6088 if (LangOpts.MicrosoftExt)
6089 Result += "__declspec(allocate(\".datacoal_nt$B\")) ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006090 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006091 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006092 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
6093 Result += "\t0,\n"; // id is; is null
6094 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006095 if (SuperProtocols.size() > 0) {
6096 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6097 Result += PDecl->getNameAsString(); Result += ",\n";
6098 }
6099 else
6100 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006101 if (InstanceMethods.size() > 0) {
6102 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
6103 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006104 }
6105 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006106 Result += "\t0,\n";
6107
6108 if (ClassMethods.size() > 0) {
6109 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
6110 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006111 }
6112 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006113 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006114
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006115 if (OptInstanceMethods.size() > 0) {
6116 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
6117 Result += PDecl->getNameAsString(); Result += ",\n";
6118 }
6119 else
6120 Result += "\t0,\n";
6121
6122 if (OptClassMethods.size() > 0) {
6123 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
6124 Result += PDecl->getNameAsString(); Result += ",\n";
6125 }
6126 else
6127 Result += "\t0,\n";
6128
6129 if (ProtocolProperties.size() > 0) {
6130 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
6131 Result += PDecl->getNameAsString(); Result += ",\n";
6132 }
6133 else
6134 Result += "\t0,\n";
6135
6136 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6137 Result += "\t0,\n";
6138
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006139 if (AllMethods.size() > 0) {
6140 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6141 Result += PDecl->getNameAsString();
6142 Result += "\n};\n";
6143 }
6144 else
6145 Result += "\t0\n};\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006146
6147 // Use this protocol meta-data to build protocol list table in section
6148 // .objc_protolist$B
6149 // Unspecified visibility means 'private extern'.
6150 if (LangOpts.MicrosoftExt)
6151 Result += "__declspec(allocate(\".objc_protolist$B\")) ";
6152 Result += "struct _protocol_t *";
6153 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6154 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6155 Result += ";\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006156
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006157 // Mark this protocol as having been generated.
6158 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
6159 llvm_unreachable("protocol already synthesized");
6160
6161}
6162
6163void RewriteModernObjC::RewriteObjCProtocolListMetaData(
6164 const ObjCList<ObjCProtocolDecl> &Protocols,
6165 StringRef prefix, StringRef ClassName,
6166 std::string &Result) {
6167 if (Protocols.empty()) return;
6168
6169 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006170 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006171
6172 // Output the top lovel protocol meta-data for the class.
6173 /* struct _objc_protocol_list {
6174 struct _objc_protocol_list *next;
6175 int protocol_count;
6176 struct _objc_protocol *class_protocols[];
6177 }
6178 */
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006179 Result += "\n";
6180 if (LangOpts.MicrosoftExt)
6181 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
6182 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006183 Result += "\tstruct _objc_protocol_list *next;\n";
6184 Result += "\tint protocol_count;\n";
6185 Result += "\tstruct _objc_protocol *class_protocols[";
6186 Result += utostr(Protocols.size());
6187 Result += "];\n} _OBJC_";
6188 Result += prefix;
6189 Result += "_PROTOCOLS_";
6190 Result += ClassName;
6191 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
6192 "{\n\t0, ";
6193 Result += utostr(Protocols.size());
6194 Result += "\n";
6195
6196 Result += "\t,{&_OBJC_PROTOCOL_";
6197 Result += Protocols[0]->getNameAsString();
6198 Result += " \n";
6199
6200 for (unsigned i = 1; i != Protocols.size(); i++) {
6201 Result += "\t ,&_OBJC_PROTOCOL_";
6202 Result += Protocols[i]->getNameAsString();
6203 Result += "\n";
6204 }
6205 Result += "\t }\n};\n";
6206}
6207
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006208/// hasObjCExceptionAttribute - Return true if this class or any super
6209/// class has the __objc_exception__ attribute.
6210/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
6211static bool hasObjCExceptionAttribute(ASTContext &Context,
6212 const ObjCInterfaceDecl *OID) {
6213 if (OID->hasAttr<ObjCExceptionAttr>())
6214 return true;
6215 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
6216 return hasObjCExceptionAttribute(Context, Super);
6217 return false;
6218}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006219
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006220void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
6221 std::string &Result) {
6222 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6223
6224 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00006225 if (CDecl->isImplicitInterfaceDecl())
6226 assert(false &&
6227 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006228
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006229 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006230 SmallVector<ObjCIvarDecl *, 8> IVars;
6231
6232 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6233 IVD; IVD = IVD->getNextIvar()) {
6234 // Ignore unnamed bit-fields.
6235 if (!IVD->getDeclName())
6236 continue;
6237 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006238 }
6239
Fariborz Jahanianae932952012-02-10 20:47:10 +00006240 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006241 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006242 CDecl);
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006243
6244 // Build _objc_method_list for class's instance methods if needed
6245 SmallVector<ObjCMethodDecl *, 32>
6246 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6247
6248 // If any of our property implementations have associated getters or
6249 // setters, produce metadata for them as well.
6250 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6251 PropEnd = IDecl->propimpl_end();
6252 Prop != PropEnd; ++Prop) {
6253 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6254 continue;
6255 if (!(*Prop)->getPropertyIvarDecl())
6256 continue;
6257 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
6258 if (!PD)
6259 continue;
6260 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
6261 if (!Getter->isDefined())
6262 InstanceMethods.push_back(Getter);
6263 if (PD->isReadOnly())
6264 continue;
6265 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
6266 if (!Setter->isDefined())
6267 InstanceMethods.push_back(Setter);
6268 }
6269
6270 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6271 "_OBJC_$_INSTANCE_METHODS_",
6272 IDecl->getNameAsString(), true);
6273
6274 SmallVector<ObjCMethodDecl *, 32>
6275 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6276
6277 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6278 "_OBJC_$_CLASS_METHODS_",
6279 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00006280
6281 // Protocols referenced in class declaration?
6282 // Protocol's super protocol list
6283 std::vector<ObjCProtocolDecl *> RefedProtocols;
6284 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
6285 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6286 E = Protocols.end();
6287 I != E; ++I) {
6288 RefedProtocols.push_back(*I);
6289 // Must write out all protocol definitions in current qualifier list,
6290 // and in their nested qualifiers before writing out current definition.
6291 RewriteObjCProtocolMetaData(*I, Result);
6292 }
6293
6294 Write_protocol_list_initializer(Context, Result,
6295 RefedProtocols,
6296 "_OBJC_CLASS_PROTOCOLS_$_",
6297 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006298
6299 // Protocol's property metadata.
6300 std::vector<ObjCPropertyDecl *> ClassProperties;
6301 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6302 E = CDecl->prop_end(); I != E; ++I)
6303 ClassProperties.push_back(*I);
6304
6305 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanian2df089d2012-03-22 17:39:35 +00006306 /* Container */IDecl,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006307 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006308 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006309
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006310
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006311 // Data for initializing _class_ro_t metaclass meta-data
6312 uint32_t flags = CLS_META;
6313 std::string InstanceSize;
6314 std::string InstanceStart;
6315
6316
6317 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
6318 if (classIsHidden)
6319 flags |= OBJC2_CLS_HIDDEN;
6320
6321 if (!CDecl->getSuperClass())
6322 // class is root
6323 flags |= CLS_ROOT;
6324 InstanceSize = "sizeof(struct _class_t)";
6325 InstanceStart = InstanceSize;
6326 Write__class_ro_t_initializer(Context, Result, flags,
6327 InstanceStart, InstanceSize,
6328 ClassMethods,
6329 0,
6330 0,
6331 0,
6332 "_OBJC_METACLASS_RO_$_",
6333 CDecl->getNameAsString());
6334
6335
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006336 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006337 flags = CLS;
6338 if (classIsHidden)
6339 flags |= OBJC2_CLS_HIDDEN;
6340
6341 if (hasObjCExceptionAttribute(*Context, CDecl))
6342 flags |= CLS_EXCEPTION;
6343
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006344 if (!CDecl->getSuperClass())
6345 // class is root
6346 flags |= CLS_ROOT;
6347
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006348 InstanceSize.clear();
6349 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006350 if (!ObjCSynthesizedStructs.count(CDecl)) {
6351 InstanceSize = "0";
6352 InstanceStart = "0";
6353 }
6354 else {
6355 InstanceSize = "sizeof(struct ";
6356 InstanceSize += CDecl->getNameAsString();
6357 InstanceSize += "_IMPL)";
6358
6359 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6360 if (IVD) {
6361 InstanceStart += "__OFFSETOFIVAR__(struct ";
6362 InstanceStart += CDecl->getNameAsString();
6363 InstanceStart += "_IMPL, ";
6364 InstanceStart += IVD->getNameAsString();
6365 InstanceStart += ")";
6366 }
6367 else
6368 InstanceStart = InstanceSize;
6369 }
6370 Write__class_ro_t_initializer(Context, Result, flags,
6371 InstanceStart, InstanceSize,
6372 InstanceMethods,
6373 RefedProtocols,
6374 IVars,
6375 ClassProperties,
6376 "_OBJC_CLASS_RO_$_",
6377 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006378
6379 Write_class_t(Context, Result,
6380 "OBJC_METACLASS_$_",
6381 CDecl, /*metaclass*/true);
6382
6383 Write_class_t(Context, Result,
6384 "OBJC_CLASS_$_",
6385 CDecl, /*metaclass*/false);
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006386
6387 if (ImplementationIsNonLazy(IDecl))
6388 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006389
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006390}
6391
6392void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
6393 int ClsDefCount = ClassImplementation.size();
6394 int CatDefCount = CategoryImplementation.size();
6395
6396 // For each implemented class, write out all its meta data.
6397 for (int i = 0; i < ClsDefCount; i++)
6398 RewriteObjCClassMetaData(ClassImplementation[i], Result);
6399
6400 // For each implemented category, write out all its meta data.
6401 for (int i = 0; i < CatDefCount; i++)
6402 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
6403
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006404 if (ClsDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006405 if (LangOpts.MicrosoftExt)
6406 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006407 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
6408 Result += llvm::utostr(ClsDefCount); Result += "]";
6409 Result +=
6410 " __attribute__((used, section (\"__DATA, __objc_classlist,"
6411 "regular,no_dead_strip\")))= {\n";
6412 for (int i = 0; i < ClsDefCount; i++) {
6413 Result += "\t&OBJC_CLASS_$_";
6414 Result += ClassImplementation[i]->getNameAsString();
6415 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006416 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006417 Result += "};\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006418
6419 if (!DefinedNonLazyClasses.empty()) {
6420 if (LangOpts.MicrosoftExt)
6421 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
6422 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
6423 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
6424 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
6425 Result += ",\n";
6426 }
6427 Result += "};\n";
6428 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006429 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00006430
6431 if (CatDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006432 if (LangOpts.MicrosoftExt)
6433 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006434 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
6435 Result += llvm::utostr(CatDefCount); Result += "]";
6436 Result +=
6437 " __attribute__((used, section (\"__DATA, __objc_catlist,"
6438 "regular,no_dead_strip\")))= {\n";
6439 for (int i = 0; i < CatDefCount; i++) {
6440 Result += "\t&_OBJC_$_CATEGORY_";
6441 Result +=
6442 CategoryImplementation[i]->getClassInterface()->getNameAsString();
6443 Result += "_$_";
6444 Result += CategoryImplementation[i]->getNameAsString();
6445 Result += ",\n";
6446 }
6447 Result += "};\n";
6448 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006449
6450 if (!DefinedNonLazyCategories.empty()) {
6451 if (LangOpts.MicrosoftExt)
6452 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
6453 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
6454 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
6455 Result += "\t&_OBJC_$_CATEGORY_";
6456 Result +=
6457 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
6458 Result += "_$_";
6459 Result += DefinedNonLazyCategories[i]->getNameAsString();
6460 Result += ",\n";
6461 }
6462 Result += "};\n";
6463 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006464}
6465
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006466void RewriteModernObjC::WriteImageInfo(std::string &Result) {
6467 if (LangOpts.MicrosoftExt)
6468 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
6469
6470 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
6471 // version 0, ObjCABI is 2
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006472 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006473}
6474
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006475/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
6476/// implementation.
6477void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
6478 std::string &Result) {
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006479 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006480 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
6481 // Find category declaration for this implementation.
Fariborz Jahanian61186122012-02-17 18:40:41 +00006482 ObjCCategoryDecl *CDecl=0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006483 for (CDecl = ClassDecl->getCategoryList(); CDecl;
6484 CDecl = CDecl->getNextClassCategory())
6485 if (CDecl->getIdentifier() == IDecl->getIdentifier())
6486 break;
6487
6488 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00006489 FullCategoryName += "_$_";
6490 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006491
6492 // Build _objc_method_list for class's instance methods if needed
6493 SmallVector<ObjCMethodDecl *, 32>
6494 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6495
6496 // If any of our property implementations have associated getters or
6497 // setters, produce metadata for them as well.
6498 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6499 PropEnd = IDecl->propimpl_end();
6500 Prop != PropEnd; ++Prop) {
6501 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6502 continue;
6503 if (!(*Prop)->getPropertyIvarDecl())
6504 continue;
6505 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
6506 if (!PD)
6507 continue;
6508 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
6509 InstanceMethods.push_back(Getter);
6510 if (PD->isReadOnly())
6511 continue;
6512 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
6513 InstanceMethods.push_back(Setter);
6514 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006515
Fariborz Jahanian61186122012-02-17 18:40:41 +00006516 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6517 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
6518 FullCategoryName, true);
6519
6520 SmallVector<ObjCMethodDecl *, 32>
6521 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6522
6523 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6524 "_OBJC_$_CATEGORY_CLASS_METHODS_",
6525 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006526
6527 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00006528 // Protocol's super protocol list
6529 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00006530 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
6531 E = CDecl->protocol_end();
6532
6533 I != E; ++I) {
Fariborz Jahanian61186122012-02-17 18:40:41 +00006534 RefedProtocols.push_back(*I);
6535 // Must write out all protocol definitions in current qualifier list,
6536 // and in their nested qualifiers before writing out current definition.
6537 RewriteObjCProtocolMetaData(*I, Result);
6538 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006539
Fariborz Jahanian61186122012-02-17 18:40:41 +00006540 Write_protocol_list_initializer(Context, Result,
6541 RefedProtocols,
6542 "_OBJC_CATEGORY_PROTOCOLS_$_",
6543 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006544
Fariborz Jahanian61186122012-02-17 18:40:41 +00006545 // Protocol's property metadata.
6546 std::vector<ObjCPropertyDecl *> ClassProperties;
6547 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6548 E = CDecl->prop_end(); I != E; ++I)
6549 ClassProperties.push_back(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006550
Fariborz Jahanian61186122012-02-17 18:40:41 +00006551 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
6552 /* Container */0,
6553 "_OBJC_$_PROP_LIST_",
6554 FullCategoryName);
6555
6556 Write_category_t(*this, Context, Result,
6557 CDecl->getNameAsString(),
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006558 ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006559 InstanceMethods,
6560 ClassMethods,
6561 RefedProtocols,
6562 ClassProperties);
6563
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006564 // Determine if this category is also "non-lazy".
6565 if (ImplementationIsNonLazy(IDecl))
6566 DefinedNonLazyCategories.push_back(CDecl);
6567
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006568}
6569
6570// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
6571/// class methods.
6572template<typename MethodIterator>
6573void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
6574 MethodIterator MethodEnd,
6575 bool IsInstanceMethod,
6576 StringRef prefix,
6577 StringRef ClassName,
6578 std::string &Result) {
6579 if (MethodBegin == MethodEnd) return;
6580
6581 if (!objc_impl_method) {
6582 /* struct _objc_method {
6583 SEL _cmd;
6584 char *method_types;
6585 void *_imp;
6586 }
6587 */
6588 Result += "\nstruct _objc_method {\n";
6589 Result += "\tSEL _cmd;\n";
6590 Result += "\tchar *method_types;\n";
6591 Result += "\tvoid *_imp;\n";
6592 Result += "};\n";
6593
6594 objc_impl_method = true;
6595 }
6596
6597 // Build _objc_method_list for class's methods if needed
6598
6599 /* struct {
6600 struct _objc_method_list *next_method;
6601 int method_count;
6602 struct _objc_method method_list[];
6603 }
6604 */
6605 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006606 Result += "\n";
6607 if (LangOpts.MicrosoftExt) {
6608 if (IsInstanceMethod)
6609 Result += "__declspec(allocate(\".inst_meth$B\")) ";
6610 else
6611 Result += "__declspec(allocate(\".cls_meth$B\")) ";
6612 }
6613 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006614 Result += "\tstruct _objc_method_list *next_method;\n";
6615 Result += "\tint method_count;\n";
6616 Result += "\tstruct _objc_method method_list[";
6617 Result += utostr(NumMethods);
6618 Result += "];\n} _OBJC_";
6619 Result += prefix;
6620 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
6621 Result += "_METHODS_";
6622 Result += ClassName;
6623 Result += " __attribute__ ((used, section (\"__OBJC, __";
6624 Result += IsInstanceMethod ? "inst" : "cls";
6625 Result += "_meth\")))= ";
6626 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
6627
6628 Result += "\t,{{(SEL)\"";
6629 Result += (*MethodBegin)->getSelector().getAsString().c_str();
6630 std::string MethodTypeString;
6631 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
6632 Result += "\", \"";
6633 Result += MethodTypeString;
6634 Result += "\", (void *)";
6635 Result += MethodInternalNames[*MethodBegin];
6636 Result += "}\n";
6637 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
6638 Result += "\t ,{(SEL)\"";
6639 Result += (*MethodBegin)->getSelector().getAsString().c_str();
6640 std::string MethodTypeString;
6641 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
6642 Result += "\", \"";
6643 Result += MethodTypeString;
6644 Result += "\", (void *)";
6645 Result += MethodInternalNames[*MethodBegin];
6646 Result += "}\n";
6647 }
6648 Result += "\t }\n};\n";
6649}
6650
6651Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
6652 SourceRange OldRange = IV->getSourceRange();
6653 Expr *BaseExpr = IV->getBase();
6654
6655 // Rewrite the base, but without actually doing replaces.
6656 {
6657 DisableReplaceStmtScope S(*this);
6658 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
6659 IV->setBase(BaseExpr);
6660 }
6661
6662 ObjCIvarDecl *D = IV->getDecl();
6663
6664 Expr *Replacement = IV;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006665
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006666 if (BaseExpr->getType()->isObjCObjectPointerType()) {
6667 const ObjCInterfaceType *iFaceDecl =
6668 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
6669 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
6670 // lookup which class implements the instance variable.
6671 ObjCInterfaceDecl *clsDeclared = 0;
6672 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
6673 clsDeclared);
6674 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
6675
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006676 // Build name of symbol holding ivar offset.
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006677 std::string IvarOffsetName;
6678 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
6679
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00006680 ReferencedIvars[clsDeclared].insert(D);
6681
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006682 // cast offset to "char *".
6683 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
6684 Context->getPointerType(Context->CharTy),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006685 CK_BitCast,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006686 BaseExpr);
6687 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
6688 SourceLocation(), &Context->Idents.get(IvarOffsetName),
6689 Context->UnsignedLongTy, 0, SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00006690 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
6691 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006692 SourceLocation());
6693 BinaryOperator *addExpr =
6694 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
6695 Context->getPointerType(Context->CharTy),
6696 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006697 // Don't forget the parens to enforce the proper binding.
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006698 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
6699 SourceLocation(),
6700 addExpr);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00006701 QualType IvarT = D->getType();
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00006702 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00006703 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006704
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006705 castExpr = NoTypeInfoCStyleCastExpr(Context,
6706 castT,
6707 CK_BitCast,
6708 PE);
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00006709 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006710 VK_LValue, OK_Ordinary,
6711 SourceLocation());
6712 PE = new (Context) ParenExpr(OldRange.getBegin(),
6713 OldRange.getEnd(),
6714 Exp);
6715
6716 Replacement = PE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006717 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006718
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006719 ReplaceStmtWithRange(IV, Replacement, OldRange);
6720 return Replacement;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006721}