blob: 40b806d69d52ca9e7e8dac659d0f982972334649 [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 (*)(...)".
Fariborz Jahanian2610f902012-03-27 16:42:20 +00001151 (void)convertBlockPointerToFunctionPointer(QT);
1152 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001153 ResultStr += Name;
1154 }
1155 }
1156 if (OMD->isVariadic())
1157 ResultStr += ", ...";
1158 ResultStr += ") ";
1159
1160 if (FPRetType) {
1161 ResultStr += ")"; // close the precedence "scope" for "*".
1162
1163 // Now, emit the argument types (if any).
1164 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1165 ResultStr += "(";
1166 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1167 if (i) ResultStr += ", ";
1168 std::string ParamStr = FT->getArgType(i).getAsString(
1169 Context->getPrintingPolicy());
1170 ResultStr += ParamStr;
1171 }
1172 if (FT->isVariadic()) {
1173 if (FT->getNumArgs()) ResultStr += ", ";
1174 ResultStr += "...";
1175 }
1176 ResultStr += ")";
1177 } else {
1178 ResultStr += "()";
1179 }
1180 }
1181}
1182void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1183 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1184 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1185
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001186 if (IMD) {
1187 InsertText(IMD->getLocStart(), "// ");
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001188 if (IMD->getIvarLBraceLoc().isValid())
1189 InsertText(IMD->getIvarLBraceLoc(), "// ");
1190 for (ObjCImplementationDecl::ivar_iterator
1191 I = IMD->ivar_begin(), E = IMD->ivar_end(); I != E; ++I) {
1192 ObjCIvarDecl *Ivar = (*I);
1193 SourceLocation LocStart = Ivar->getLocStart();
1194 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001195 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001196 if (IMD->getIvarRBraceLoc().isValid())
1197 InsertText(IMD->getIvarRBraceLoc(), "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001198 }
1199 else
1200 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001201
1202 for (ObjCCategoryImplDecl::instmeth_iterator
1203 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1204 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1205 I != E; ++I) {
1206 std::string ResultStr;
1207 ObjCMethodDecl *OMD = *I;
1208 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1209 SourceLocation LocStart = OMD->getLocStart();
1210 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1211
1212 const char *startBuf = SM->getCharacterData(LocStart);
1213 const char *endBuf = SM->getCharacterData(LocEnd);
1214 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1215 }
1216
1217 for (ObjCCategoryImplDecl::classmeth_iterator
1218 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1219 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1220 I != E; ++I) {
1221 std::string ResultStr;
1222 ObjCMethodDecl *OMD = *I;
1223 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1224 SourceLocation LocStart = OMD->getLocStart();
1225 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1226
1227 const char *startBuf = SM->getCharacterData(LocStart);
1228 const char *endBuf = SM->getCharacterData(LocEnd);
1229 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1230 }
1231 for (ObjCCategoryImplDecl::propimpl_iterator
1232 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1233 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1234 I != E; ++I) {
1235 RewritePropertyImplDecl(*I, IMD, CID);
1236 }
1237
1238 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1239}
1240
1241void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00001242 // Do not synthesize more than once.
1243 if (ObjCSynthesizedStructs.count(ClassDecl))
1244 return;
1245 // Make sure super class's are written before current class is written.
1246 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1247 while (SuperClass) {
1248 RewriteInterfaceDecl(SuperClass);
1249 SuperClass = SuperClass->getSuperClass();
1250 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001251 std::string ResultStr;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001252 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001253 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001254 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00001255 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1256
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001257 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001258 // Mark this typedef as having been written into its c++ equivalent.
1259 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001260
1261 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001262 E = ClassDecl->prop_end(); I != E; ++I)
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001263 RewriteProperty(*I);
1264 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001265 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001266 I != E; ++I)
1267 RewriteMethodDeclaration(*I);
1268 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001269 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001270 I != E; ++I)
1271 RewriteMethodDeclaration(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001272
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001273 // Lastly, comment out the @end.
1274 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1275 "/* @end */");
1276 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001277}
1278
1279Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1280 SourceRange OldRange = PseudoOp->getSourceRange();
1281
1282 // We just magically know some things about the structure of this
1283 // expression.
1284 ObjCMessageExpr *OldMsg =
1285 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1286 PseudoOp->getNumSemanticExprs() - 1));
1287
1288 // Because the rewriter doesn't allow us to rewrite rewritten code,
1289 // we need to suppress rewriting the sub-statements.
1290 Expr *Base, *RHS;
1291 {
1292 DisableReplaceStmtScope S(*this);
1293
1294 // Rebuild the base expression if we have one.
1295 Base = 0;
1296 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1297 Base = OldMsg->getInstanceReceiver();
1298 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1299 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1300 }
1301
1302 // Rebuild the RHS.
1303 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1304 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1305 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1306 }
1307
1308 // TODO: avoid this copy.
1309 SmallVector<SourceLocation, 1> SelLocs;
1310 OldMsg->getSelectorLocs(SelLocs);
1311
1312 ObjCMessageExpr *NewMsg = 0;
1313 switch (OldMsg->getReceiverKind()) {
1314 case ObjCMessageExpr::Class:
1315 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1316 OldMsg->getValueKind(),
1317 OldMsg->getLeftLoc(),
1318 OldMsg->getClassReceiverTypeInfo(),
1319 OldMsg->getSelector(),
1320 SelLocs,
1321 OldMsg->getMethodDecl(),
1322 RHS,
1323 OldMsg->getRightLoc(),
1324 OldMsg->isImplicit());
1325 break;
1326
1327 case ObjCMessageExpr::Instance:
1328 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1329 OldMsg->getValueKind(),
1330 OldMsg->getLeftLoc(),
1331 Base,
1332 OldMsg->getSelector(),
1333 SelLocs,
1334 OldMsg->getMethodDecl(),
1335 RHS,
1336 OldMsg->getRightLoc(),
1337 OldMsg->isImplicit());
1338 break;
1339
1340 case ObjCMessageExpr::SuperClass:
1341 case ObjCMessageExpr::SuperInstance:
1342 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1343 OldMsg->getValueKind(),
1344 OldMsg->getLeftLoc(),
1345 OldMsg->getSuperLoc(),
1346 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1347 OldMsg->getSuperType(),
1348 OldMsg->getSelector(),
1349 SelLocs,
1350 OldMsg->getMethodDecl(),
1351 RHS,
1352 OldMsg->getRightLoc(),
1353 OldMsg->isImplicit());
1354 break;
1355 }
1356
1357 Stmt *Replacement = SynthMessageExpr(NewMsg);
1358 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1359 return Replacement;
1360}
1361
1362Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1363 SourceRange OldRange = PseudoOp->getSourceRange();
1364
1365 // We just magically know some things about the structure of this
1366 // expression.
1367 ObjCMessageExpr *OldMsg =
1368 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1369
1370 // Because the rewriter doesn't allow us to rewrite rewritten code,
1371 // we need to suppress rewriting the sub-statements.
1372 Expr *Base = 0;
1373 {
1374 DisableReplaceStmtScope S(*this);
1375
1376 // Rebuild the base expression if we have one.
1377 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1378 Base = OldMsg->getInstanceReceiver();
1379 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1380 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1381 }
1382 }
1383
1384 // Intentionally empty.
1385 SmallVector<SourceLocation, 1> SelLocs;
1386 SmallVector<Expr*, 1> Args;
1387
1388 ObjCMessageExpr *NewMsg = 0;
1389 switch (OldMsg->getReceiverKind()) {
1390 case ObjCMessageExpr::Class:
1391 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1392 OldMsg->getValueKind(),
1393 OldMsg->getLeftLoc(),
1394 OldMsg->getClassReceiverTypeInfo(),
1395 OldMsg->getSelector(),
1396 SelLocs,
1397 OldMsg->getMethodDecl(),
1398 Args,
1399 OldMsg->getRightLoc(),
1400 OldMsg->isImplicit());
1401 break;
1402
1403 case ObjCMessageExpr::Instance:
1404 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1405 OldMsg->getValueKind(),
1406 OldMsg->getLeftLoc(),
1407 Base,
1408 OldMsg->getSelector(),
1409 SelLocs,
1410 OldMsg->getMethodDecl(),
1411 Args,
1412 OldMsg->getRightLoc(),
1413 OldMsg->isImplicit());
1414 break;
1415
1416 case ObjCMessageExpr::SuperClass:
1417 case ObjCMessageExpr::SuperInstance:
1418 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1419 OldMsg->getValueKind(),
1420 OldMsg->getLeftLoc(),
1421 OldMsg->getSuperLoc(),
1422 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1423 OldMsg->getSuperType(),
1424 OldMsg->getSelector(),
1425 SelLocs,
1426 OldMsg->getMethodDecl(),
1427 Args,
1428 OldMsg->getRightLoc(),
1429 OldMsg->isImplicit());
1430 break;
1431 }
1432
1433 Stmt *Replacement = SynthMessageExpr(NewMsg);
1434 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1435 return Replacement;
1436}
1437
1438/// SynthCountByEnumWithState - To print:
1439/// ((unsigned int (*)
1440/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1441/// (void *)objc_msgSend)((id)l_collection,
1442/// sel_registerName(
1443/// "countByEnumeratingWithState:objects:count:"),
1444/// &enumState,
1445/// (id *)__rw_items, (unsigned int)16)
1446///
1447void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1448 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1449 "id *, unsigned int))(void *)objc_msgSend)";
1450 buf += "\n\t\t";
1451 buf += "((id)l_collection,\n\t\t";
1452 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1453 buf += "\n\t\t";
1454 buf += "&enumState, "
1455 "(id *)__rw_items, (unsigned int)16)";
1456}
1457
1458/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1459/// statement to exit to its outer synthesized loop.
1460///
1461Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1462 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1463 return S;
1464 // replace break with goto __break_label
1465 std::string buf;
1466
1467 SourceLocation startLoc = S->getLocStart();
1468 buf = "goto __break_label_";
1469 buf += utostr(ObjCBcLabelNo.back());
1470 ReplaceText(startLoc, strlen("break"), buf);
1471
1472 return 0;
1473}
1474
1475/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1476/// statement to continue with its inner synthesized loop.
1477///
1478Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1479 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1480 return S;
1481 // replace continue with goto __continue_label
1482 std::string buf;
1483
1484 SourceLocation startLoc = S->getLocStart();
1485 buf = "goto __continue_label_";
1486 buf += utostr(ObjCBcLabelNo.back());
1487 ReplaceText(startLoc, strlen("continue"), buf);
1488
1489 return 0;
1490}
1491
1492/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1493/// It rewrites:
1494/// for ( type elem in collection) { stmts; }
1495
1496/// Into:
1497/// {
1498/// type elem;
1499/// struct __objcFastEnumerationState enumState = { 0 };
1500/// id __rw_items[16];
1501/// id l_collection = (id)collection;
1502/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1503/// objects:__rw_items count:16];
1504/// if (limit) {
1505/// unsigned long startMutations = *enumState.mutationsPtr;
1506/// do {
1507/// unsigned long counter = 0;
1508/// do {
1509/// if (startMutations != *enumState.mutationsPtr)
1510/// objc_enumerationMutation(l_collection);
1511/// elem = (type)enumState.itemsPtr[counter++];
1512/// stmts;
1513/// __continue_label: ;
1514/// } while (counter < limit);
1515/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1516/// objects:__rw_items count:16]);
1517/// elem = nil;
1518/// __break_label: ;
1519/// }
1520/// else
1521/// elem = nil;
1522/// }
1523///
1524Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1525 SourceLocation OrigEnd) {
1526 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1527 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1528 "ObjCForCollectionStmt Statement stack mismatch");
1529 assert(!ObjCBcLabelNo.empty() &&
1530 "ObjCForCollectionStmt - Label No stack empty");
1531
1532 SourceLocation startLoc = S->getLocStart();
1533 const char *startBuf = SM->getCharacterData(startLoc);
1534 StringRef elementName;
1535 std::string elementTypeAsString;
1536 std::string buf;
1537 buf = "\n{\n\t";
1538 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1539 // type elem;
1540 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1541 QualType ElementType = cast<ValueDecl>(D)->getType();
1542 if (ElementType->isObjCQualifiedIdType() ||
1543 ElementType->isObjCQualifiedInterfaceType())
1544 // Simply use 'id' for all qualified types.
1545 elementTypeAsString = "id";
1546 else
1547 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1548 buf += elementTypeAsString;
1549 buf += " ";
1550 elementName = D->getName();
1551 buf += elementName;
1552 buf += ";\n\t";
1553 }
1554 else {
1555 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1556 elementName = DR->getDecl()->getName();
1557 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1558 if (VD->getType()->isObjCQualifiedIdType() ||
1559 VD->getType()->isObjCQualifiedInterfaceType())
1560 // Simply use 'id' for all qualified types.
1561 elementTypeAsString = "id";
1562 else
1563 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1564 }
1565
1566 // struct __objcFastEnumerationState enumState = { 0 };
1567 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1568 // id __rw_items[16];
1569 buf += "id __rw_items[16];\n\t";
1570 // id l_collection = (id)
1571 buf += "id l_collection = (id)";
1572 // Find start location of 'collection' the hard way!
1573 const char *startCollectionBuf = startBuf;
1574 startCollectionBuf += 3; // skip 'for'
1575 startCollectionBuf = strchr(startCollectionBuf, '(');
1576 startCollectionBuf++; // skip '('
1577 // find 'in' and skip it.
1578 while (*startCollectionBuf != ' ' ||
1579 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1580 (*(startCollectionBuf+3) != ' ' &&
1581 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1582 startCollectionBuf++;
1583 startCollectionBuf += 3;
1584
1585 // Replace: "for (type element in" with string constructed thus far.
1586 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1587 // Replace ')' in for '(' type elem in collection ')' with ';'
1588 SourceLocation rightParenLoc = S->getRParenLoc();
1589 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1590 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1591 buf = ";\n\t";
1592
1593 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1594 // objects:__rw_items count:16];
1595 // which is synthesized into:
1596 // unsigned int limit =
1597 // ((unsigned int (*)
1598 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1599 // (void *)objc_msgSend)((id)l_collection,
1600 // sel_registerName(
1601 // "countByEnumeratingWithState:objects:count:"),
1602 // (struct __objcFastEnumerationState *)&state,
1603 // (id *)__rw_items, (unsigned int)16);
1604 buf += "unsigned long limit =\n\t\t";
1605 SynthCountByEnumWithState(buf);
1606 buf += ";\n\t";
1607 /// if (limit) {
1608 /// unsigned long startMutations = *enumState.mutationsPtr;
1609 /// do {
1610 /// unsigned long counter = 0;
1611 /// do {
1612 /// if (startMutations != *enumState.mutationsPtr)
1613 /// objc_enumerationMutation(l_collection);
1614 /// elem = (type)enumState.itemsPtr[counter++];
1615 buf += "if (limit) {\n\t";
1616 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1617 buf += "do {\n\t\t";
1618 buf += "unsigned long counter = 0;\n\t\t";
1619 buf += "do {\n\t\t\t";
1620 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1621 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1622 buf += elementName;
1623 buf += " = (";
1624 buf += elementTypeAsString;
1625 buf += ")enumState.itemsPtr[counter++];";
1626 // Replace ')' in for '(' type elem in collection ')' with all of these.
1627 ReplaceText(lparenLoc, 1, buf);
1628
1629 /// __continue_label: ;
1630 /// } while (counter < limit);
1631 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1632 /// objects:__rw_items count:16]);
1633 /// elem = nil;
1634 /// __break_label: ;
1635 /// }
1636 /// else
1637 /// elem = nil;
1638 /// }
1639 ///
1640 buf = ";\n\t";
1641 buf += "__continue_label_";
1642 buf += utostr(ObjCBcLabelNo.back());
1643 buf += ": ;";
1644 buf += "\n\t\t";
1645 buf += "} while (counter < limit);\n\t";
1646 buf += "} while (limit = ";
1647 SynthCountByEnumWithState(buf);
1648 buf += ");\n\t";
1649 buf += elementName;
1650 buf += " = ((";
1651 buf += elementTypeAsString;
1652 buf += ")0);\n\t";
1653 buf += "__break_label_";
1654 buf += utostr(ObjCBcLabelNo.back());
1655 buf += ": ;\n\t";
1656 buf += "}\n\t";
1657 buf += "else\n\t\t";
1658 buf += elementName;
1659 buf += " = ((";
1660 buf += elementTypeAsString;
1661 buf += ")0);\n\t";
1662 buf += "}\n";
1663
1664 // Insert all these *after* the statement body.
1665 // FIXME: If this should support Obj-C++, support CXXTryStmt
1666 if (isa<CompoundStmt>(S->getBody())) {
1667 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1668 InsertText(endBodyLoc, buf);
1669 } else {
1670 /* Need to treat single statements specially. For example:
1671 *
1672 * for (A *a in b) if (stuff()) break;
1673 * for (A *a in b) xxxyy;
1674 *
1675 * The following code simply scans ahead to the semi to find the actual end.
1676 */
1677 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1678 const char *semiBuf = strchr(stmtBuf, ';');
1679 assert(semiBuf && "Can't find ';'");
1680 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1681 InsertText(endBodyLoc, buf);
1682 }
1683 Stmts.pop_back();
1684 ObjCBcLabelNo.pop_back();
1685 return 0;
1686}
1687
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001688static void Write_RethrowObject(std::string &buf) {
1689 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1690 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1691 buf += "\tid rethrow;\n";
1692 buf += "\t} _fin_force_rethow(_rethrow);";
1693}
1694
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001695/// RewriteObjCSynchronizedStmt -
1696/// This routine rewrites @synchronized(expr) stmt;
1697/// into:
1698/// objc_sync_enter(expr);
1699/// @try stmt @finally { objc_sync_exit(expr); }
1700///
1701Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1702 // Get the start location and compute the semi location.
1703 SourceLocation startLoc = S->getLocStart();
1704 const char *startBuf = SM->getCharacterData(startLoc);
1705
1706 assert((*startBuf == '@') && "bogus @synchronized location");
1707
1708 std::string buf;
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001709 buf = "{ id _rethrow = 0; id _sync_obj = ";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001710
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001711 const char *lparenBuf = startBuf;
1712 while (*lparenBuf != '(') lparenBuf++;
1713 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001714
1715 buf = "; objc_sync_enter(_sync_obj);\n";
1716 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1717 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1718 buf += "\n\tid sync_exit;";
1719 buf += "\n\t} _sync_exit(_sync_obj);\n";
1720
1721 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1722 // the sync expression is typically a message expression that's already
1723 // been rewritten! (which implies the SourceLocation's are invalid).
1724 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1725 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1726 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1727 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1728
1729 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1730 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1731 assert (*LBraceLocBuf == '{');
1732 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001733
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001734 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay9ab511c2012-03-16 22:20:39 +00001735 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1736 "bogus @synchronized block");
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001737
1738 buf = "} catch (id e) {_rethrow = e;}\n";
1739 Write_RethrowObject(buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001740 buf += "}\n";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001741 buf += "}\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001742
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001743 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001744
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001745 return 0;
1746}
1747
1748void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1749{
1750 // Perform a bottom up traversal of all children.
1751 for (Stmt::child_range CI = S->children(); CI; ++CI)
1752 if (*CI)
1753 WarnAboutReturnGotoStmts(*CI);
1754
1755 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1756 Diags.Report(Context->getFullLoc(S->getLocStart()),
1757 TryFinallyContainsReturnDiag);
1758 }
1759 return;
1760}
1761
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001762Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001763 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001764 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001765 std::string buf;
1766
1767 if (finalStmt) {
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001768 if (noCatch)
1769 buf = "{ id volatile _rethrow = 0;\n";
1770 else {
1771 buf = "{ id volatile _rethrow = 0;\ntry {\n";
1772 }
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001773 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001774 // Get the start location and compute the semi location.
1775 SourceLocation startLoc = S->getLocStart();
1776 const char *startBuf = SM->getCharacterData(startLoc);
1777
1778 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001779 if (finalStmt)
1780 ReplaceText(startLoc, 1, buf);
1781 else
1782 // @try -> try
1783 ReplaceText(startLoc, 1, "");
1784
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001785 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1786 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001787 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001788
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001789 startLoc = Catch->getLocStart();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001790 bool AtRemoved = false;
1791 if (catchDecl) {
1792 QualType t = catchDecl->getType();
1793 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1794 // Should be a pointer to a class.
1795 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1796 if (IDecl) {
1797 std::string Result;
1798 startBuf = SM->getCharacterData(startLoc);
1799 assert((*startBuf == '@') && "bogus @catch location");
1800 SourceLocation rParenLoc = Catch->getRParenLoc();
1801 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1802
1803 // _objc_exc_Foo *_e as argument to catch.
1804 Result = "catch (_objc_exc_"; Result += IDecl->getNameAsString();
1805 Result += " *_"; Result += catchDecl->getNameAsString();
1806 Result += ")";
1807 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1808 // Foo *e = (Foo *)_e;
1809 Result.clear();
1810 Result = "{ ";
1811 Result += IDecl->getNameAsString();
1812 Result += " *"; Result += catchDecl->getNameAsString();
1813 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1814 Result += "_"; Result += catchDecl->getNameAsString();
1815
1816 Result += "; ";
1817 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
1818 ReplaceText(lBraceLoc, 1, Result);
1819 AtRemoved = true;
1820 }
1821 }
1822 }
1823 if (!AtRemoved)
1824 // @catch -> catch
1825 ReplaceText(startLoc, 1, "");
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001826
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001827 }
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001828 if (finalStmt) {
1829 buf.clear();
1830 if (noCatch)
1831 buf = "catch (id e) {_rethrow = e;}\n";
1832 else
1833 buf = "}\ncatch (id e) {_rethrow = e;}\n";
1834
1835 SourceLocation startFinalLoc = finalStmt->getLocStart();
1836 ReplaceText(startFinalLoc, 8, buf);
1837 Stmt *body = finalStmt->getFinallyBody();
1838 SourceLocation startFinalBodyLoc = body->getLocStart();
1839 buf.clear();
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001840 Write_RethrowObject(buf);
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001841 ReplaceText(startFinalBodyLoc, 1, buf);
1842
1843 SourceLocation endFinalBodyLoc = body->getLocEnd();
1844 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001845 // Now check for any return/continue/go statements within the @try.
1846 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001847 }
1848
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001849 return 0;
1850}
1851
1852// This can't be done with ReplaceStmt(S, ThrowExpr), since
1853// the throw expression is typically a message expression that's already
1854// been rewritten! (which implies the SourceLocation's are invalid).
1855Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
1856 // Get the start location and compute the semi location.
1857 SourceLocation startLoc = S->getLocStart();
1858 const char *startBuf = SM->getCharacterData(startLoc);
1859
1860 assert((*startBuf == '@') && "bogus @throw location");
1861
1862 std::string buf;
1863 /* void objc_exception_throw(id) __attribute__((noreturn)); */
1864 if (S->getThrowExpr())
1865 buf = "objc_exception_throw(";
Fariborz Jahanian40539462012-03-16 16:52:06 +00001866 else
1867 buf = "throw";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001868
1869 // handle "@ throw" correctly.
1870 const char *wBuf = strchr(startBuf, 'w');
1871 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1872 ReplaceText(startLoc, wBuf-startBuf+1, buf);
1873
1874 const char *semiBuf = strchr(startBuf, ';');
1875 assert((*semiBuf == ';') && "@throw: can't find ';'");
1876 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian40539462012-03-16 16:52:06 +00001877 if (S->getThrowExpr())
1878 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001879 return 0;
1880}
1881
1882Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
1883 // Create a new string expression.
1884 QualType StrType = Context->getPointerType(Context->CharTy);
1885 std::string StrEncoding;
1886 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
1887 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
1888 StringLiteral::Ascii, false,
1889 StrType, SourceLocation());
1890 ReplaceStmt(Exp, Replacement);
1891
1892 // Replace this subexpr in the parent.
1893 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1894 return Replacement;
1895}
1896
1897Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1898 if (!SelGetUidFunctionDecl)
1899 SynthSelGetUidFunctionDecl();
1900 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1901 // Create a call to sel_registerName("selName").
1902 SmallVector<Expr*, 8> SelExprs;
1903 QualType argType = Context->getPointerType(Context->CharTy);
1904 SelExprs.push_back(StringLiteral::Create(*Context,
1905 Exp->getSelector().getAsString(),
1906 StringLiteral::Ascii, false,
1907 argType, SourceLocation()));
1908 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1909 &SelExprs[0], SelExprs.size());
1910 ReplaceStmt(Exp, SelExp);
1911 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1912 return SelExp;
1913}
1914
1915CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
1916 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
1917 SourceLocation EndLoc) {
1918 // Get the type, we will need to reference it in a couple spots.
1919 QualType msgSendType = FD->getType();
1920
1921 // Create a reference to the objc_msgSend() declaration.
1922 DeclRefExpr *DRE =
John McCallf4b88a42012-03-10 09:33:50 +00001923 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001924
1925 // Now, we cast the reference to a pointer to the objc_msgSend type.
1926 QualType pToFunc = Context->getPointerType(msgSendType);
1927 ImplicitCastExpr *ICE =
1928 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
1929 DRE, 0, VK_RValue);
1930
1931 const FunctionType *FT = msgSendType->getAs<FunctionType>();
1932
1933 CallExpr *Exp =
1934 new (Context) CallExpr(*Context, ICE, args, nargs,
1935 FT->getCallResultType(*Context),
1936 VK_RValue, EndLoc);
1937 return Exp;
1938}
1939
1940static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1941 const char *&startRef, const char *&endRef) {
1942 while (startBuf < endBuf) {
1943 if (*startBuf == '<')
1944 startRef = startBuf; // mark the start.
1945 if (*startBuf == '>') {
1946 if (startRef && *startRef == '<') {
1947 endRef = startBuf; // mark the end.
1948 return true;
1949 }
1950 return false;
1951 }
1952 startBuf++;
1953 }
1954 return false;
1955}
1956
1957static void scanToNextArgument(const char *&argRef) {
1958 int angle = 0;
1959 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1960 if (*argRef == '<')
1961 angle++;
1962 else if (*argRef == '>')
1963 angle--;
1964 argRef++;
1965 }
1966 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1967}
1968
1969bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
1970 if (T->isObjCQualifiedIdType())
1971 return true;
1972 if (const PointerType *PT = T->getAs<PointerType>()) {
1973 if (PT->getPointeeType()->isObjCQualifiedIdType())
1974 return true;
1975 }
1976 if (T->isObjCObjectPointerType()) {
1977 T = T->getPointeeType();
1978 return T->isObjCQualifiedInterfaceType();
1979 }
1980 if (T->isArrayType()) {
1981 QualType ElemTy = Context->getBaseElementType(T);
1982 return needToScanForQualifiers(ElemTy);
1983 }
1984 return false;
1985}
1986
1987void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1988 QualType Type = E->getType();
1989 if (needToScanForQualifiers(Type)) {
1990 SourceLocation Loc, EndLoc;
1991
1992 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1993 Loc = ECE->getLParenLoc();
1994 EndLoc = ECE->getRParenLoc();
1995 } else {
1996 Loc = E->getLocStart();
1997 EndLoc = E->getLocEnd();
1998 }
1999 // This will defend against trying to rewrite synthesized expressions.
2000 if (Loc.isInvalid() || EndLoc.isInvalid())
2001 return;
2002
2003 const char *startBuf = SM->getCharacterData(Loc);
2004 const char *endBuf = SM->getCharacterData(EndLoc);
2005 const char *startRef = 0, *endRef = 0;
2006 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2007 // Get the locations of the startRef, endRef.
2008 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2009 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2010 // Comment out the protocol references.
2011 InsertText(LessLoc, "/*");
2012 InsertText(GreaterLoc, "*/");
2013 }
2014 }
2015}
2016
2017void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2018 SourceLocation Loc;
2019 QualType Type;
2020 const FunctionProtoType *proto = 0;
2021 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2022 Loc = VD->getLocation();
2023 Type = VD->getType();
2024 }
2025 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2026 Loc = FD->getLocation();
2027 // Check for ObjC 'id' and class types that have been adorned with protocol
2028 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2029 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2030 assert(funcType && "missing function type");
2031 proto = dyn_cast<FunctionProtoType>(funcType);
2032 if (!proto)
2033 return;
2034 Type = proto->getResultType();
2035 }
2036 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2037 Loc = FD->getLocation();
2038 Type = FD->getType();
2039 }
2040 else
2041 return;
2042
2043 if (needToScanForQualifiers(Type)) {
2044 // Since types are unique, we need to scan the buffer.
2045
2046 const char *endBuf = SM->getCharacterData(Loc);
2047 const char *startBuf = endBuf;
2048 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2049 startBuf--; // scan backward (from the decl location) for return type.
2050 const char *startRef = 0, *endRef = 0;
2051 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2052 // Get the locations of the startRef, endRef.
2053 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2054 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2055 // Comment out the protocol references.
2056 InsertText(LessLoc, "/*");
2057 InsertText(GreaterLoc, "*/");
2058 }
2059 }
2060 if (!proto)
2061 return; // most likely, was a variable
2062 // Now check arguments.
2063 const char *startBuf = SM->getCharacterData(Loc);
2064 const char *startFuncBuf = startBuf;
2065 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2066 if (needToScanForQualifiers(proto->getArgType(i))) {
2067 // Since types are unique, we need to scan the buffer.
2068
2069 const char *endBuf = startBuf;
2070 // scan forward (from the decl location) for argument types.
2071 scanToNextArgument(endBuf);
2072 const char *startRef = 0, *endRef = 0;
2073 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2074 // Get the locations of the startRef, endRef.
2075 SourceLocation LessLoc =
2076 Loc.getLocWithOffset(startRef-startFuncBuf);
2077 SourceLocation GreaterLoc =
2078 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2079 // Comment out the protocol references.
2080 InsertText(LessLoc, "/*");
2081 InsertText(GreaterLoc, "*/");
2082 }
2083 startBuf = ++endBuf;
2084 }
2085 else {
2086 // If the function name is derived from a macro expansion, then the
2087 // argument buffer will not follow the name. Need to speak with Chris.
2088 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2089 startBuf++; // scan forward (from the decl location) for argument types.
2090 startBuf++;
2091 }
2092 }
2093}
2094
2095void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2096 QualType QT = ND->getType();
2097 const Type* TypePtr = QT->getAs<Type>();
2098 if (!isa<TypeOfExprType>(TypePtr))
2099 return;
2100 while (isa<TypeOfExprType>(TypePtr)) {
2101 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2102 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2103 TypePtr = QT->getAs<Type>();
2104 }
2105 // FIXME. This will not work for multiple declarators; as in:
2106 // __typeof__(a) b,c,d;
2107 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2108 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2109 const char *startBuf = SM->getCharacterData(DeclLoc);
2110 if (ND->getInit()) {
2111 std::string Name(ND->getNameAsString());
2112 TypeAsString += " " + Name + " = ";
2113 Expr *E = ND->getInit();
2114 SourceLocation startLoc;
2115 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2116 startLoc = ECE->getLParenLoc();
2117 else
2118 startLoc = E->getLocStart();
2119 startLoc = SM->getExpansionLoc(startLoc);
2120 const char *endBuf = SM->getCharacterData(startLoc);
2121 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2122 }
2123 else {
2124 SourceLocation X = ND->getLocEnd();
2125 X = SM->getExpansionLoc(X);
2126 const char *endBuf = SM->getCharacterData(X);
2127 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2128 }
2129}
2130
2131// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2132void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2133 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2134 SmallVector<QualType, 16> ArgTys;
2135 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2136 QualType getFuncType =
2137 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
2138 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2139 SourceLocation(),
2140 SourceLocation(),
2141 SelGetUidIdent, getFuncType, 0,
2142 SC_Extern,
2143 SC_None, false);
2144}
2145
2146void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2147 // declared in <objc/objc.h>
2148 if (FD->getIdentifier() &&
2149 FD->getName() == "sel_registerName") {
2150 SelGetUidFunctionDecl = FD;
2151 return;
2152 }
2153 RewriteObjCQualifiedInterfaceTypes(FD);
2154}
2155
2156void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2157 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2158 const char *argPtr = TypeString.c_str();
2159 if (!strchr(argPtr, '^')) {
2160 Str += TypeString;
2161 return;
2162 }
2163 while (*argPtr) {
2164 Str += (*argPtr == '^' ? '*' : *argPtr);
2165 argPtr++;
2166 }
2167}
2168
2169// FIXME. Consolidate this routine with RewriteBlockPointerType.
2170void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2171 ValueDecl *VD) {
2172 QualType Type = VD->getType();
2173 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2174 const char *argPtr = TypeString.c_str();
2175 int paren = 0;
2176 while (*argPtr) {
2177 switch (*argPtr) {
2178 case '(':
2179 Str += *argPtr;
2180 paren++;
2181 break;
2182 case ')':
2183 Str += *argPtr;
2184 paren--;
2185 break;
2186 case '^':
2187 Str += '*';
2188 if (paren == 1)
2189 Str += VD->getNameAsString();
2190 break;
2191 default:
2192 Str += *argPtr;
2193 break;
2194 }
2195 argPtr++;
2196 }
2197}
2198
2199
2200void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2201 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2202 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2203 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2204 if (!proto)
2205 return;
2206 QualType Type = proto->getResultType();
2207 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2208 FdStr += " ";
2209 FdStr += FD->getName();
2210 FdStr += "(";
2211 unsigned numArgs = proto->getNumArgs();
2212 for (unsigned i = 0; i < numArgs; i++) {
2213 QualType ArgType = proto->getArgType(i);
2214 RewriteBlockPointerType(FdStr, ArgType);
2215 if (i+1 < numArgs)
2216 FdStr += ", ";
2217 }
2218 FdStr += ");\n";
2219 InsertText(FunLocStart, FdStr);
2220 CurFunctionDeclToDeclareForBlock = 0;
2221}
2222
2223// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
2224void RewriteModernObjC::SynthSuperContructorFunctionDecl() {
2225 if (SuperContructorFunctionDecl)
2226 return;
2227 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2228 SmallVector<QualType, 16> ArgTys;
2229 QualType argT = Context->getObjCIdType();
2230 assert(!argT.isNull() && "Can't find 'id' type");
2231 ArgTys.push_back(argT);
2232 ArgTys.push_back(argT);
2233 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2234 &ArgTys[0], ArgTys.size());
2235 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2236 SourceLocation(),
2237 SourceLocation(),
2238 msgSendIdent, msgSendType, 0,
2239 SC_Extern,
2240 SC_None, false);
2241}
2242
2243// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2244void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2245 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2246 SmallVector<QualType, 16> ArgTys;
2247 QualType argT = Context->getObjCIdType();
2248 assert(!argT.isNull() && "Can't find 'id' type");
2249 ArgTys.push_back(argT);
2250 argT = Context->getObjCSelType();
2251 assert(!argT.isNull() && "Can't find 'SEL' type");
2252 ArgTys.push_back(argT);
2253 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2254 &ArgTys[0], ArgTys.size(),
2255 true /*isVariadic*/);
2256 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2257 SourceLocation(),
2258 SourceLocation(),
2259 msgSendIdent, msgSendType, 0,
2260 SC_Extern,
2261 SC_None, false);
2262}
2263
2264// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
2265void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2266 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2267 SmallVector<QualType, 16> ArgTys;
2268 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2269 SourceLocation(), SourceLocation(),
2270 &Context->Idents.get("objc_super"));
2271 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2272 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2273 ArgTys.push_back(argT);
2274 argT = Context->getObjCSelType();
2275 assert(!argT.isNull() && "Can't find 'SEL' type");
2276 ArgTys.push_back(argT);
2277 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2278 &ArgTys[0], ArgTys.size(),
2279 true /*isVariadic*/);
2280 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2281 SourceLocation(),
2282 SourceLocation(),
2283 msgSendIdent, msgSendType, 0,
2284 SC_Extern,
2285 SC_None, false);
2286}
2287
2288// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2289void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2290 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2291 SmallVector<QualType, 16> ArgTys;
2292 QualType argT = Context->getObjCIdType();
2293 assert(!argT.isNull() && "Can't find 'id' type");
2294 ArgTys.push_back(argT);
2295 argT = Context->getObjCSelType();
2296 assert(!argT.isNull() && "Can't find 'SEL' type");
2297 ArgTys.push_back(argT);
2298 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2299 &ArgTys[0], ArgTys.size(),
2300 true /*isVariadic*/);
2301 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2302 SourceLocation(),
2303 SourceLocation(),
2304 msgSendIdent, msgSendType, 0,
2305 SC_Extern,
2306 SC_None, false);
2307}
2308
2309// SynthMsgSendSuperStretFunctionDecl -
2310// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
2311void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2312 IdentifierInfo *msgSendIdent =
2313 &Context->Idents.get("objc_msgSendSuper_stret");
2314 SmallVector<QualType, 16> ArgTys;
2315 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2316 SourceLocation(), SourceLocation(),
2317 &Context->Idents.get("objc_super"));
2318 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2319 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2320 ArgTys.push_back(argT);
2321 argT = Context->getObjCSelType();
2322 assert(!argT.isNull() && "Can't find 'SEL' type");
2323 ArgTys.push_back(argT);
2324 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2325 &ArgTys[0], ArgTys.size(),
2326 true /*isVariadic*/);
2327 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2328 SourceLocation(),
2329 SourceLocation(),
2330 msgSendIdent, msgSendType, 0,
2331 SC_Extern,
2332 SC_None, false);
2333}
2334
2335// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2336void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2337 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2338 SmallVector<QualType, 16> ArgTys;
2339 QualType argT = Context->getObjCIdType();
2340 assert(!argT.isNull() && "Can't find 'id' type");
2341 ArgTys.push_back(argT);
2342 argT = Context->getObjCSelType();
2343 assert(!argT.isNull() && "Can't find 'SEL' type");
2344 ArgTys.push_back(argT);
2345 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2346 &ArgTys[0], ArgTys.size(),
2347 true /*isVariadic*/);
2348 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2349 SourceLocation(),
2350 SourceLocation(),
2351 msgSendIdent, msgSendType, 0,
2352 SC_Extern,
2353 SC_None, false);
2354}
2355
2356// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
2357void RewriteModernObjC::SynthGetClassFunctionDecl() {
2358 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2359 SmallVector<QualType, 16> ArgTys;
2360 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2361 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2362 &ArgTys[0], ArgTys.size());
2363 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2364 SourceLocation(),
2365 SourceLocation(),
2366 getClassIdent, getClassType, 0,
2367 SC_Extern,
2368 SC_None, false);
2369}
2370
2371// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2372void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2373 IdentifierInfo *getSuperClassIdent =
2374 &Context->Idents.get("class_getSuperclass");
2375 SmallVector<QualType, 16> ArgTys;
2376 ArgTys.push_back(Context->getObjCClassType());
2377 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2378 &ArgTys[0], ArgTys.size());
2379 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2380 SourceLocation(),
2381 SourceLocation(),
2382 getSuperClassIdent,
2383 getClassType, 0,
2384 SC_Extern,
2385 SC_None,
2386 false);
2387}
2388
2389// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
2390void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2391 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2392 SmallVector<QualType, 16> ArgTys;
2393 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2394 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2395 &ArgTys[0], ArgTys.size());
2396 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2397 SourceLocation(),
2398 SourceLocation(),
2399 getClassIdent, getClassType, 0,
2400 SC_Extern,
2401 SC_None, false);
2402}
2403
2404Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2405 QualType strType = getConstantStringStructType();
2406
2407 std::string S = "__NSConstantStringImpl_";
2408
2409 std::string tmpName = InFileName;
2410 unsigned i;
2411 for (i=0; i < tmpName.length(); i++) {
2412 char c = tmpName.at(i);
2413 // replace any non alphanumeric characters with '_'.
2414 if (!isalpha(c) && (c < '0' || c > '9'))
2415 tmpName[i] = '_';
2416 }
2417 S += tmpName;
2418 S += "_";
2419 S += utostr(NumObjCStringLiterals++);
2420
2421 Preamble += "static __NSConstantStringImpl " + S;
2422 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2423 Preamble += "0x000007c8,"; // utf8_str
2424 // The pretty printer for StringLiteral handles escape characters properly.
2425 std::string prettyBufS;
2426 llvm::raw_string_ostream prettyBuf(prettyBufS);
2427 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2428 PrintingPolicy(LangOpts));
2429 Preamble += prettyBuf.str();
2430 Preamble += ",";
2431 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2432
2433 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2434 SourceLocation(), &Context->Idents.get(S),
2435 strType, 0, SC_Static, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002436 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002437 SourceLocation());
2438 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2439 Context->getPointerType(DRE->getType()),
2440 VK_RValue, OK_Ordinary,
2441 SourceLocation());
2442 // cast to NSConstantString *
2443 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2444 CK_CPointerToObjCPointerCast, Unop);
2445 ReplaceStmt(Exp, cast);
2446 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2447 return cast;
2448}
2449
2450// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
2451QualType RewriteModernObjC::getSuperStructType() {
2452 if (!SuperStructDecl) {
2453 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2454 SourceLocation(), SourceLocation(),
2455 &Context->Idents.get("objc_super"));
2456 QualType FieldTypes[2];
2457
2458 // struct objc_object *receiver;
2459 FieldTypes[0] = Context->getObjCIdType();
2460 // struct objc_class *super;
2461 FieldTypes[1] = Context->getObjCClassType();
2462
2463 // Create fields
2464 for (unsigned i = 0; i < 2; ++i) {
2465 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2466 SourceLocation(),
2467 SourceLocation(), 0,
2468 FieldTypes[i], 0,
2469 /*BitWidth=*/0,
2470 /*Mutable=*/false,
2471 /*HasInit=*/false));
2472 }
2473
2474 SuperStructDecl->completeDefinition();
2475 }
2476 return Context->getTagDeclType(SuperStructDecl);
2477}
2478
2479QualType RewriteModernObjC::getConstantStringStructType() {
2480 if (!ConstantStringDecl) {
2481 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2482 SourceLocation(), SourceLocation(),
2483 &Context->Idents.get("__NSConstantStringImpl"));
2484 QualType FieldTypes[4];
2485
2486 // struct objc_object *receiver;
2487 FieldTypes[0] = Context->getObjCIdType();
2488 // int flags;
2489 FieldTypes[1] = Context->IntTy;
2490 // char *str;
2491 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2492 // long length;
2493 FieldTypes[3] = Context->LongTy;
2494
2495 // Create fields
2496 for (unsigned i = 0; i < 4; ++i) {
2497 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2498 ConstantStringDecl,
2499 SourceLocation(),
2500 SourceLocation(), 0,
2501 FieldTypes[i], 0,
2502 /*BitWidth=*/0,
2503 /*Mutable=*/true,
2504 /*HasInit=*/false));
2505 }
2506
2507 ConstantStringDecl->completeDefinition();
2508 }
2509 return Context->getTagDeclType(ConstantStringDecl);
2510}
2511
2512Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2513 SourceLocation StartLoc,
2514 SourceLocation EndLoc) {
2515 if (!SelGetUidFunctionDecl)
2516 SynthSelGetUidFunctionDecl();
2517 if (!MsgSendFunctionDecl)
2518 SynthMsgSendFunctionDecl();
2519 if (!MsgSendSuperFunctionDecl)
2520 SynthMsgSendSuperFunctionDecl();
2521 if (!MsgSendStretFunctionDecl)
2522 SynthMsgSendStretFunctionDecl();
2523 if (!MsgSendSuperStretFunctionDecl)
2524 SynthMsgSendSuperStretFunctionDecl();
2525 if (!MsgSendFpretFunctionDecl)
2526 SynthMsgSendFpretFunctionDecl();
2527 if (!GetClassFunctionDecl)
2528 SynthGetClassFunctionDecl();
2529 if (!GetSuperClassFunctionDecl)
2530 SynthGetSuperClassFunctionDecl();
2531 if (!GetMetaClassFunctionDecl)
2532 SynthGetMetaClassFunctionDecl();
2533
2534 // default to objc_msgSend().
2535 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2536 // May need to use objc_msgSend_stret() as well.
2537 FunctionDecl *MsgSendStretFlavor = 0;
2538 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2539 QualType resultType = mDecl->getResultType();
2540 if (resultType->isRecordType())
2541 MsgSendStretFlavor = MsgSendStretFunctionDecl;
2542 else if (resultType->isRealFloatingType())
2543 MsgSendFlavor = MsgSendFpretFunctionDecl;
2544 }
2545
2546 // Synthesize a call to objc_msgSend().
2547 SmallVector<Expr*, 8> MsgExprs;
2548 switch (Exp->getReceiverKind()) {
2549 case ObjCMessageExpr::SuperClass: {
2550 MsgSendFlavor = MsgSendSuperFunctionDecl;
2551 if (MsgSendStretFlavor)
2552 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2553 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2554
2555 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2556
2557 SmallVector<Expr*, 4> InitExprs;
2558
2559 // set the receiver to self, the first argument to all methods.
2560 InitExprs.push_back(
2561 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2562 CK_BitCast,
2563 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00002564 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002565 Context->getObjCIdType(),
2566 VK_RValue,
2567 SourceLocation()))
2568 ); // set the 'receiver'.
2569
2570 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2571 SmallVector<Expr*, 8> ClsExprs;
2572 QualType argType = Context->getPointerType(Context->CharTy);
2573 ClsExprs.push_back(StringLiteral::Create(*Context,
2574 ClassDecl->getIdentifier()->getName(),
2575 StringLiteral::Ascii, false,
2576 argType, SourceLocation()));
2577 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2578 &ClsExprs[0],
2579 ClsExprs.size(),
2580 StartLoc,
2581 EndLoc);
2582 // (Class)objc_getClass("CurrentClass")
2583 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2584 Context->getObjCClassType(),
2585 CK_BitCast, Cls);
2586 ClsExprs.clear();
2587 ClsExprs.push_back(ArgExpr);
2588 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2589 &ClsExprs[0], ClsExprs.size(),
2590 StartLoc, EndLoc);
2591
2592 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2593 // To turn off a warning, type-cast to 'id'
2594 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2595 NoTypeInfoCStyleCastExpr(Context,
2596 Context->getObjCIdType(),
2597 CK_BitCast, Cls));
2598 // struct objc_super
2599 QualType superType = getSuperStructType();
2600 Expr *SuperRep;
2601
2602 if (LangOpts.MicrosoftExt) {
2603 SynthSuperContructorFunctionDecl();
2604 // Simulate a contructor call...
2605 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00002606 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002607 SourceLocation());
2608 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2609 InitExprs.size(),
2610 superType, VK_LValue,
2611 SourceLocation());
2612 // The code for super is a little tricky to prevent collision with
2613 // the structure definition in the header. The rewriter has it's own
2614 // internal definition (__rw_objc_super) that is uses. This is why
2615 // we need the cast below. For example:
2616 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2617 //
2618 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2619 Context->getPointerType(SuperRep->getType()),
2620 VK_RValue, OK_Ordinary,
2621 SourceLocation());
2622 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2623 Context->getPointerType(superType),
2624 CK_BitCast, SuperRep);
2625 } else {
2626 // (struct objc_super) { <exprs from above> }
2627 InitListExpr *ILE =
2628 new (Context) InitListExpr(*Context, SourceLocation(),
2629 &InitExprs[0], InitExprs.size(),
2630 SourceLocation());
2631 TypeSourceInfo *superTInfo
2632 = Context->getTrivialTypeSourceInfo(superType);
2633 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2634 superType, VK_LValue,
2635 ILE, false);
2636 // struct objc_super *
2637 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2638 Context->getPointerType(SuperRep->getType()),
2639 VK_RValue, OK_Ordinary,
2640 SourceLocation());
2641 }
2642 MsgExprs.push_back(SuperRep);
2643 break;
2644 }
2645
2646 case ObjCMessageExpr::Class: {
2647 SmallVector<Expr*, 8> ClsExprs;
2648 QualType argType = Context->getPointerType(Context->CharTy);
2649 ObjCInterfaceDecl *Class
2650 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
2651 IdentifierInfo *clsName = Class->getIdentifier();
2652 ClsExprs.push_back(StringLiteral::Create(*Context,
2653 clsName->getName(),
2654 StringLiteral::Ascii, false,
2655 argType, SourceLocation()));
2656 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2657 &ClsExprs[0],
2658 ClsExprs.size(),
2659 StartLoc, EndLoc);
2660 MsgExprs.push_back(Cls);
2661 break;
2662 }
2663
2664 case ObjCMessageExpr::SuperInstance:{
2665 MsgSendFlavor = MsgSendSuperFunctionDecl;
2666 if (MsgSendStretFlavor)
2667 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2668 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2669 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2670 SmallVector<Expr*, 4> InitExprs;
2671
2672 InitExprs.push_back(
2673 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2674 CK_BitCast,
2675 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00002676 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002677 Context->getObjCIdType(),
2678 VK_RValue, SourceLocation()))
2679 ); // set the 'receiver'.
2680
2681 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2682 SmallVector<Expr*, 8> ClsExprs;
2683 QualType argType = Context->getPointerType(Context->CharTy);
2684 ClsExprs.push_back(StringLiteral::Create(*Context,
2685 ClassDecl->getIdentifier()->getName(),
2686 StringLiteral::Ascii, false, argType,
2687 SourceLocation()));
2688 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2689 &ClsExprs[0],
2690 ClsExprs.size(),
2691 StartLoc, EndLoc);
2692 // (Class)objc_getClass("CurrentClass")
2693 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2694 Context->getObjCClassType(),
2695 CK_BitCast, Cls);
2696 ClsExprs.clear();
2697 ClsExprs.push_back(ArgExpr);
2698 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2699 &ClsExprs[0], ClsExprs.size(),
2700 StartLoc, EndLoc);
2701
2702 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2703 // To turn off a warning, type-cast to 'id'
2704 InitExprs.push_back(
2705 // set 'super class', using class_getSuperclass().
2706 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2707 CK_BitCast, Cls));
2708 // struct objc_super
2709 QualType superType = getSuperStructType();
2710 Expr *SuperRep;
2711
2712 if (LangOpts.MicrosoftExt) {
2713 SynthSuperContructorFunctionDecl();
2714 // Simulate a contructor call...
2715 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00002716 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002717 SourceLocation());
2718 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2719 InitExprs.size(),
2720 superType, VK_LValue, SourceLocation());
2721 // The code for super is a little tricky to prevent collision with
2722 // the structure definition in the header. The rewriter has it's own
2723 // internal definition (__rw_objc_super) that is uses. This is why
2724 // we need the cast below. For example:
2725 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2726 //
2727 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2728 Context->getPointerType(SuperRep->getType()),
2729 VK_RValue, OK_Ordinary,
2730 SourceLocation());
2731 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2732 Context->getPointerType(superType),
2733 CK_BitCast, SuperRep);
2734 } else {
2735 // (struct objc_super) { <exprs from above> }
2736 InitListExpr *ILE =
2737 new (Context) InitListExpr(*Context, SourceLocation(),
2738 &InitExprs[0], InitExprs.size(),
2739 SourceLocation());
2740 TypeSourceInfo *superTInfo
2741 = Context->getTrivialTypeSourceInfo(superType);
2742 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2743 superType, VK_RValue, ILE,
2744 false);
2745 }
2746 MsgExprs.push_back(SuperRep);
2747 break;
2748 }
2749
2750 case ObjCMessageExpr::Instance: {
2751 // Remove all type-casts because it may contain objc-style types; e.g.
2752 // Foo<Proto> *.
2753 Expr *recExpr = Exp->getInstanceReceiver();
2754 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2755 recExpr = CE->getSubExpr();
2756 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
2757 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
2758 ? CK_BlockPointerToObjCPointerCast
2759 : CK_CPointerToObjCPointerCast;
2760
2761 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2762 CK, recExpr);
2763 MsgExprs.push_back(recExpr);
2764 break;
2765 }
2766 }
2767
2768 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
2769 SmallVector<Expr*, 8> SelExprs;
2770 QualType argType = Context->getPointerType(Context->CharTy);
2771 SelExprs.push_back(StringLiteral::Create(*Context,
2772 Exp->getSelector().getAsString(),
2773 StringLiteral::Ascii, false,
2774 argType, SourceLocation()));
2775 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2776 &SelExprs[0], SelExprs.size(),
2777 StartLoc,
2778 EndLoc);
2779 MsgExprs.push_back(SelExp);
2780
2781 // Now push any user supplied arguments.
2782 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
2783 Expr *userExpr = Exp->getArg(i);
2784 // Make all implicit casts explicit...ICE comes in handy:-)
2785 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2786 // Reuse the ICE type, it is exactly what the doctor ordered.
2787 QualType type = ICE->getType();
2788 if (needToScanForQualifiers(type))
2789 type = Context->getObjCIdType();
2790 // Make sure we convert "type (^)(...)" to "type (*)(...)".
2791 (void)convertBlockPointerToFunctionPointer(type);
2792 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2793 CastKind CK;
2794 if (SubExpr->getType()->isIntegralType(*Context) &&
2795 type->isBooleanType()) {
2796 CK = CK_IntegralToBoolean;
2797 } else if (type->isObjCObjectPointerType()) {
2798 if (SubExpr->getType()->isBlockPointerType()) {
2799 CK = CK_BlockPointerToObjCPointerCast;
2800 } else if (SubExpr->getType()->isPointerType()) {
2801 CK = CK_CPointerToObjCPointerCast;
2802 } else {
2803 CK = CK_BitCast;
2804 }
2805 } else {
2806 CK = CK_BitCast;
2807 }
2808
2809 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
2810 }
2811 // Make id<P...> cast into an 'id' cast.
2812 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
2813 if (CE->getType()->isObjCQualifiedIdType()) {
2814 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
2815 userExpr = CE->getSubExpr();
2816 CastKind CK;
2817 if (userExpr->getType()->isIntegralType(*Context)) {
2818 CK = CK_IntegralToPointer;
2819 } else if (userExpr->getType()->isBlockPointerType()) {
2820 CK = CK_BlockPointerToObjCPointerCast;
2821 } else if (userExpr->getType()->isPointerType()) {
2822 CK = CK_CPointerToObjCPointerCast;
2823 } else {
2824 CK = CK_BitCast;
2825 }
2826 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2827 CK, userExpr);
2828 }
2829 }
2830 MsgExprs.push_back(userExpr);
2831 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2832 // out the argument in the original expression (since we aren't deleting
2833 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
2834 //Exp->setArg(i, 0);
2835 }
2836 // Generate the funky cast.
2837 CastExpr *cast;
2838 SmallVector<QualType, 8> ArgTypes;
2839 QualType returnType;
2840
2841 // Push 'id' and 'SEL', the 2 implicit arguments.
2842 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2843 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2844 else
2845 ArgTypes.push_back(Context->getObjCIdType());
2846 ArgTypes.push_back(Context->getObjCSelType());
2847 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
2848 // Push any user argument types.
2849 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2850 E = OMD->param_end(); PI != E; ++PI) {
2851 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
2852 ? Context->getObjCIdType()
2853 : (*PI)->getType();
2854 // Make sure we convert "t (^)(...)" to "t (*)(...)".
2855 (void)convertBlockPointerToFunctionPointer(t);
2856 ArgTypes.push_back(t);
2857 }
2858 returnType = Exp->getType();
2859 convertToUnqualifiedObjCType(returnType);
2860 (void)convertBlockPointerToFunctionPointer(returnType);
2861 } else {
2862 returnType = Context->getObjCIdType();
2863 }
2864 // Get the type, we will need to reference it in a couple spots.
2865 QualType msgSendType = MsgSendFlavor->getType();
2866
2867 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00002868 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002869 VK_LValue, SourceLocation());
2870
2871 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2872 // If we don't do this cast, we get the following bizarre warning/note:
2873 // xx.m:13: warning: function called through a non-compatible type
2874 // xx.m:13: note: if this code is reached, the program will abort
2875 cast = NoTypeInfoCStyleCastExpr(Context,
2876 Context->getPointerType(Context->VoidTy),
2877 CK_BitCast, DRE);
2878
2879 // Now do the "normal" pointer to function cast.
2880 QualType castType =
2881 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2882 // If we don't have a method decl, force a variadic cast.
2883 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
2884 castType = Context->getPointerType(castType);
2885 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2886 cast);
2887
2888 // Don't forget the parens to enforce the proper binding.
2889 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2890
2891 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2892 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2893 MsgExprs.size(),
2894 FT->getResultType(), VK_RValue,
2895 EndLoc);
2896 Stmt *ReplacingStmt = CE;
2897 if (MsgSendStretFlavor) {
2898 // We have the method which returns a struct/union. Must also generate
2899 // call to objc_msgSend_stret and hang both varieties on a conditional
2900 // expression which dictate which one to envoke depending on size of
2901 // method's return type.
2902
2903 // Create a reference to the objc_msgSend_stret() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00002904 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
2905 false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002906 VK_LValue, SourceLocation());
2907 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2908 cast = NoTypeInfoCStyleCastExpr(Context,
2909 Context->getPointerType(Context->VoidTy),
2910 CK_BitCast, STDRE);
2911 // Now do the "normal" pointer to function cast.
2912 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2913 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
2914 castType = Context->getPointerType(castType);
2915 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2916 cast);
2917
2918 // Don't forget the parens to enforce the proper binding.
2919 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
2920
2921 FT = msgSendType->getAs<FunctionType>();
2922 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2923 MsgExprs.size(),
2924 FT->getResultType(), VK_RValue,
2925 SourceLocation());
2926
2927 // Build sizeof(returnType)
2928 UnaryExprOrTypeTraitExpr *sizeofExpr =
2929 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
2930 Context->getTrivialTypeSourceInfo(returnType),
2931 Context->getSizeType(), SourceLocation(),
2932 SourceLocation());
2933 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2934 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2935 // For X86 it is more complicated and some kind of target specific routine
2936 // is needed to decide what to do.
2937 unsigned IntSize =
2938 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2939 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
2940 llvm::APInt(IntSize, 8),
2941 Context->IntTy,
2942 SourceLocation());
2943 BinaryOperator *lessThanExpr =
2944 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
2945 VK_RValue, OK_Ordinary, SourceLocation());
2946 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2947 ConditionalOperator *CondExpr =
2948 new (Context) ConditionalOperator(lessThanExpr,
2949 SourceLocation(), CE,
2950 SourceLocation(), STCE,
2951 returnType, VK_RValue, OK_Ordinary);
2952 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
2953 CondExpr);
2954 }
2955 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2956 return ReplacingStmt;
2957}
2958
2959Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
2960 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
2961 Exp->getLocEnd());
2962
2963 // Now do the actual rewrite.
2964 ReplaceStmt(Exp, ReplacingStmt);
2965
2966 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2967 return ReplacingStmt;
2968}
2969
2970// typedef struct objc_object Protocol;
2971QualType RewriteModernObjC::getProtocolType() {
2972 if (!ProtocolTypeDecl) {
2973 TypeSourceInfo *TInfo
2974 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
2975 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
2976 SourceLocation(), SourceLocation(),
2977 &Context->Idents.get("Protocol"),
2978 TInfo);
2979 }
2980 return Context->getTypeDeclType(ProtocolTypeDecl);
2981}
2982
2983/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2984/// a synthesized/forward data reference (to the protocol's metadata).
2985/// The forward references (and metadata) are generated in
2986/// RewriteModernObjC::HandleTranslationUnit().
2987Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00002988 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
2989 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002990 IdentifierInfo *ID = &Context->Idents.get(Name);
2991 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2992 SourceLocation(), ID, getProtocolType(), 0,
2993 SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002994 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
2995 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002996 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
2997 Context->getPointerType(DRE->getType()),
2998 VK_RValue, OK_Ordinary, SourceLocation());
2999 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3000 CK_BitCast,
3001 DerefExpr);
3002 ReplaceStmt(Exp, castExpr);
3003 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3004 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3005 return castExpr;
3006
3007}
3008
3009bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3010 const char *endBuf) {
3011 while (startBuf < endBuf) {
3012 if (*startBuf == '#') {
3013 // Skip whitespace.
3014 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3015 ;
3016 if (!strncmp(startBuf, "if", strlen("if")) ||
3017 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3018 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3019 !strncmp(startBuf, "define", strlen("define")) ||
3020 !strncmp(startBuf, "undef", strlen("undef")) ||
3021 !strncmp(startBuf, "else", strlen("else")) ||
3022 !strncmp(startBuf, "elif", strlen("elif")) ||
3023 !strncmp(startBuf, "endif", strlen("endif")) ||
3024 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3025 !strncmp(startBuf, "include", strlen("include")) ||
3026 !strncmp(startBuf, "import", strlen("import")) ||
3027 !strncmp(startBuf, "include_next", strlen("include_next")))
3028 return true;
3029 }
3030 startBuf++;
3031 }
3032 return false;
3033}
3034
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003035/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003036/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003037bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3038 std::string &Result) {
3039 if (Type->isArrayType()) {
3040 QualType ElemTy = Context->getBaseElementType(Type);
3041 return RewriteObjCFieldDeclType(ElemTy, Result);
3042 }
3043 else if (Type->isRecordType()) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003044 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3045 if (RD->isCompleteDefinition()) {
3046 if (RD->isStruct())
3047 Result += "\n\tstruct ";
3048 else if (RD->isUnion())
3049 Result += "\n\tunion ";
3050 else
3051 assert(false && "class not allowed as an ivar type");
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003052
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003053 Result += RD->getName();
3054 if (TagsDefinedInIvarDecls.count(RD)) {
3055 // This struct is already defined. Do not write its definition again.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003056 Result += " ";
3057 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003058 }
3059 TagsDefinedInIvarDecls.insert(RD);
3060 Result += " {\n";
3061 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003062 e = RD->field_end(); i != e; ++i) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003063 FieldDecl *FD = *i;
3064 RewriteObjCFieldDecl(FD, Result);
3065 }
3066 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003067 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003068 }
3069 }
3070 else if (Type->isEnumeralType()) {
3071 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3072 if (ED->isCompleteDefinition()) {
3073 Result += "\n\tenum ";
3074 Result += ED->getName();
3075 if (TagsDefinedInIvarDecls.count(ED)) {
3076 // This enum is already defined. Do not write its definition again.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003077 Result += " ";
3078 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003079 }
3080 TagsDefinedInIvarDecls.insert(ED);
3081
3082 Result += " {\n";
3083 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3084 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3085 Result += "\t"; Result += EC->getName(); Result += " = ";
3086 llvm::APSInt Val = EC->getInitVal();
3087 Result += Val.toString(10);
3088 Result += ",\n";
3089 }
3090 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003091 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003092 }
3093 }
3094
3095 Result += "\t";
3096 convertObjCTypeToCStyleType(Type);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003097 return false;
3098}
3099
3100
3101/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3102/// It handles elaborated types, as well as enum types in the process.
3103void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3104 std::string &Result) {
3105 QualType Type = fieldDecl->getType();
3106 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003107
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003108 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3109 if (!EleboratedType)
3110 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003111 Result += Name;
3112 if (fieldDecl->isBitField()) {
3113 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3114 }
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003115 else if (EleboratedType && Type->isArrayType()) {
3116 CanQualType CType = Context->getCanonicalType(Type);
3117 while (isa<ArrayType>(CType)) {
3118 if (const ConstantArrayType *CAT = Context->getAsConstantArrayType(CType)) {
3119 Result += "[";
3120 llvm::APInt Dim = CAT->getSize();
3121 Result += utostr(Dim.getZExtValue());
3122 Result += "]";
3123 }
3124 CType = CType->getAs<ArrayType>()->getElementType();
3125 }
3126 }
3127
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003128 Result += ";\n";
3129}
3130
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003131/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3132/// an objective-c class with ivars.
3133void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3134 std::string &Result) {
3135 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3136 assert(CDecl->getName() != "" &&
3137 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003138 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003139 SmallVector<ObjCIvarDecl *, 8> IVars;
3140 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003141 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003142 IVars.push_back(IVD);
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003143
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003144 SourceLocation LocStart = CDecl->getLocStart();
3145 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003146
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003147 const char *startBuf = SM->getCharacterData(LocStart);
3148 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003149
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003150 // If no ivars and no root or if its root, directly or indirectly,
3151 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003152 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003153 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3154 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3155 ReplaceText(LocStart, endBuf-startBuf, Result);
3156 return;
3157 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003158
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003159 Result += "\nstruct ";
3160 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003161 Result += "_IMPL {\n";
3162
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003163 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003164 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3165 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3166 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003167 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003168 TagsDefinedInIvarDecls.clear();
3169 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3170 RewriteObjCFieldDecl(IVars[i], Result);
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00003171
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003172 Result += "};\n";
3173 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3174 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003175 // Mark this struct as having been generated.
3176 if (!ObjCSynthesizedStructs.insert(CDecl))
3177 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003178}
3179
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003180static void WriteInternalIvarName(ObjCInterfaceDecl *IDecl,
3181 ObjCIvarDecl *IvarDecl, std::string &Result) {
3182 Result += "OBJC_IVAR_$_";
3183 Result += IDecl->getName();
3184 Result += "$";
3185 Result += IvarDecl->getName();
3186}
3187
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003188/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3189/// have been referenced in an ivar access expression.
3190void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3191 std::string &Result) {
3192 // write out ivar offset symbols which have been referenced in an ivar
3193 // access expression.
3194 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3195 if (Ivars.empty())
3196 return;
3197 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
3198 e = Ivars.end(); i != e; i++) {
3199 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003200 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00003201 Result += "extern \"C\" ";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003202 if (LangOpts.MicrosoftExt)
3203 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
3204 if (LangOpts.MicrosoftExt &&
3205 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
3206 IvarDecl->getAccessControl() != ObjCIvarDecl::Package) {
3207 const ObjCInterfaceDecl *CDecl = IvarDecl->getContainingInterface();
3208 if (CDecl->getImplementation())
3209 Result += "__declspec(dllexport) ";
3210 }
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00003211 Result += "unsigned long ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003212 WriteInternalIvarName(CDecl, IvarDecl, Result);
3213 Result += ";";
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003214 }
3215}
3216
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003217//===----------------------------------------------------------------------===//
3218// Meta Data Emission
3219//===----------------------------------------------------------------------===//
3220
3221
3222/// RewriteImplementations - This routine rewrites all method implementations
3223/// and emits meta-data.
3224
3225void RewriteModernObjC::RewriteImplementations() {
3226 int ClsDefCount = ClassImplementation.size();
3227 int CatDefCount = CategoryImplementation.size();
3228
3229 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003230 for (int i = 0; i < ClsDefCount; i++) {
3231 ObjCImplementationDecl *OIMP = ClassImplementation[i];
3232 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
3233 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00003234 assert(false &&
3235 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003236 RewriteImplementationDecl(OIMP);
3237 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003238
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003239 for (int i = 0; i < CatDefCount; i++) {
3240 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
3241 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
3242 if (CDecl->isImplicitInterfaceDecl())
3243 assert(false &&
3244 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003245 RewriteImplementationDecl(CIMP);
3246 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003247}
3248
3249void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
3250 const std::string &Name,
3251 ValueDecl *VD, bool def) {
3252 assert(BlockByRefDeclNo.count(VD) &&
3253 "RewriteByRefString: ByRef decl missing");
3254 if (def)
3255 ResultStr += "struct ";
3256 ResultStr += "__Block_byref_" + Name +
3257 "_" + utostr(BlockByRefDeclNo[VD]) ;
3258}
3259
3260static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3261 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3262 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3263 return false;
3264}
3265
3266std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3267 StringRef funcName,
3268 std::string Tag) {
3269 const FunctionType *AFT = CE->getFunctionType();
3270 QualType RT = AFT->getResultType();
3271 std::string StructRef = "struct " + Tag;
3272 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00003273 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003274
3275 BlockDecl *BD = CE->getBlockDecl();
3276
3277 if (isa<FunctionNoProtoType>(AFT)) {
3278 // No user-supplied arguments. Still need to pass in a pointer to the
3279 // block (to reference imported block decl refs).
3280 S += "(" + StructRef + " *__cself)";
3281 } else if (BD->param_empty()) {
3282 S += "(" + StructRef + " *__cself)";
3283 } else {
3284 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
3285 assert(FT && "SynthesizeBlockFunc: No function proto");
3286 S += '(';
3287 // first add the implicit argument.
3288 S += StructRef + " *__cself, ";
3289 std::string ParamStr;
3290 for (BlockDecl::param_iterator AI = BD->param_begin(),
3291 E = BD->param_end(); AI != E; ++AI) {
3292 if (AI != BD->param_begin()) S += ", ";
3293 ParamStr = (*AI)->getNameAsString();
3294 QualType QT = (*AI)->getType();
Fariborz Jahanian2610f902012-03-27 16:42:20 +00003295 (void)convertBlockPointerToFunctionPointer(QT);
3296 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003297 S += ParamStr;
3298 }
3299 if (FT->isVariadic()) {
3300 if (!BD->param_empty()) S += ", ";
3301 S += "...";
3302 }
3303 S += ')';
3304 }
3305 S += " {\n";
3306
3307 // Create local declarations to avoid rewriting all closure decl ref exprs.
3308 // First, emit a declaration for all "by ref" decls.
3309 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3310 E = BlockByRefDecls.end(); I != E; ++I) {
3311 S += " ";
3312 std::string Name = (*I)->getNameAsString();
3313 std::string TypeString;
3314 RewriteByRefString(TypeString, Name, (*I));
3315 TypeString += " *";
3316 Name = TypeString + Name;
3317 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
3318 }
3319 // Next, emit a declaration for all "by copy" declarations.
3320 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3321 E = BlockByCopyDecls.end(); I != E; ++I) {
3322 S += " ";
3323 // Handle nested closure invocation. For example:
3324 //
3325 // void (^myImportedClosure)(void);
3326 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3327 //
3328 // void (^anotherClosure)(void);
3329 // anotherClosure = ^(void) {
3330 // myImportedClosure(); // import and invoke the closure
3331 // };
3332 //
3333 if (isTopLevelBlockPointerType((*I)->getType())) {
3334 RewriteBlockPointerTypeVariable(S, (*I));
3335 S += " = (";
3336 RewriteBlockPointerType(S, (*I)->getType());
3337 S += ")";
3338 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3339 }
3340 else {
3341 std::string Name = (*I)->getNameAsString();
3342 QualType QT = (*I)->getType();
3343 if (HasLocalVariableExternalStorage(*I))
3344 QT = Context->getPointerType(QT);
3345 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
3346 S += Name + " = __cself->" +
3347 (*I)->getNameAsString() + "; // bound by copy\n";
3348 }
3349 }
3350 std::string RewrittenStr = RewrittenBlockExprs[CE];
3351 const char *cstr = RewrittenStr.c_str();
3352 while (*cstr++ != '{') ;
3353 S += cstr;
3354 S += "\n";
3355 return S;
3356}
3357
3358std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3359 StringRef funcName,
3360 std::string Tag) {
3361 std::string StructRef = "struct " + Tag;
3362 std::string S = "static void __";
3363
3364 S += funcName;
3365 S += "_block_copy_" + utostr(i);
3366 S += "(" + StructRef;
3367 S += "*dst, " + StructRef;
3368 S += "*src) {";
3369 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3370 E = ImportedBlockDecls.end(); I != E; ++I) {
3371 ValueDecl *VD = (*I);
3372 S += "_Block_object_assign((void*)&dst->";
3373 S += (*I)->getNameAsString();
3374 S += ", (void*)src->";
3375 S += (*I)->getNameAsString();
3376 if (BlockByRefDeclsPtrSet.count((*I)))
3377 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3378 else if (VD->getType()->isBlockPointerType())
3379 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3380 else
3381 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3382 }
3383 S += "}\n";
3384
3385 S += "\nstatic void __";
3386 S += funcName;
3387 S += "_block_dispose_" + utostr(i);
3388 S += "(" + StructRef;
3389 S += "*src) {";
3390 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3391 E = ImportedBlockDecls.end(); I != E; ++I) {
3392 ValueDecl *VD = (*I);
3393 S += "_Block_object_dispose((void*)src->";
3394 S += (*I)->getNameAsString();
3395 if (BlockByRefDeclsPtrSet.count((*I)))
3396 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3397 else if (VD->getType()->isBlockPointerType())
3398 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3399 else
3400 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3401 }
3402 S += "}\n";
3403 return S;
3404}
3405
3406std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3407 std::string Desc) {
3408 std::string S = "\nstruct " + Tag;
3409 std::string Constructor = " " + Tag;
3410
3411 S += " {\n struct __block_impl impl;\n";
3412 S += " struct " + Desc;
3413 S += "* Desc;\n";
3414
3415 Constructor += "(void *fp, "; // Invoke function pointer.
3416 Constructor += "struct " + Desc; // Descriptor pointer.
3417 Constructor += " *desc";
3418
3419 if (BlockDeclRefs.size()) {
3420 // Output all "by copy" declarations.
3421 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3422 E = BlockByCopyDecls.end(); I != E; ++I) {
3423 S += " ";
3424 std::string FieldName = (*I)->getNameAsString();
3425 std::string ArgName = "_" + FieldName;
3426 // Handle nested closure invocation. For example:
3427 //
3428 // void (^myImportedBlock)(void);
3429 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3430 //
3431 // void (^anotherBlock)(void);
3432 // anotherBlock = ^(void) {
3433 // myImportedBlock(); // import and invoke the closure
3434 // };
3435 //
3436 if (isTopLevelBlockPointerType((*I)->getType())) {
3437 S += "struct __block_impl *";
3438 Constructor += ", void *" + ArgName;
3439 } else {
3440 QualType QT = (*I)->getType();
3441 if (HasLocalVariableExternalStorage(*I))
3442 QT = Context->getPointerType(QT);
3443 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3444 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
3445 Constructor += ", " + ArgName;
3446 }
3447 S += FieldName + ";\n";
3448 }
3449 // Output all "by ref" declarations.
3450 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3451 E = BlockByRefDecls.end(); I != E; ++I) {
3452 S += " ";
3453 std::string FieldName = (*I)->getNameAsString();
3454 std::string ArgName = "_" + FieldName;
3455 {
3456 std::string TypeString;
3457 RewriteByRefString(TypeString, FieldName, (*I));
3458 TypeString += " *";
3459 FieldName = TypeString + FieldName;
3460 ArgName = TypeString + ArgName;
3461 Constructor += ", " + ArgName;
3462 }
3463 S += FieldName + "; // by ref\n";
3464 }
3465 // Finish writing the constructor.
3466 Constructor += ", int flags=0)";
3467 // Initialize all "by copy" arguments.
3468 bool firsTime = true;
3469 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3470 E = BlockByCopyDecls.end(); I != E; ++I) {
3471 std::string Name = (*I)->getNameAsString();
3472 if (firsTime) {
3473 Constructor += " : ";
3474 firsTime = false;
3475 }
3476 else
3477 Constructor += ", ";
3478 if (isTopLevelBlockPointerType((*I)->getType()))
3479 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3480 else
3481 Constructor += Name + "(_" + Name + ")";
3482 }
3483 // Initialize all "by ref" arguments.
3484 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3485 E = BlockByRefDecls.end(); I != E; ++I) {
3486 std::string Name = (*I)->getNameAsString();
3487 if (firsTime) {
3488 Constructor += " : ";
3489 firsTime = false;
3490 }
3491 else
3492 Constructor += ", ";
3493 Constructor += Name + "(_" + Name + "->__forwarding)";
3494 }
3495
3496 Constructor += " {\n";
3497 if (GlobalVarDecl)
3498 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3499 else
3500 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3501 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3502
3503 Constructor += " Desc = desc;\n";
3504 } else {
3505 // Finish writing the constructor.
3506 Constructor += ", int flags=0) {\n";
3507 if (GlobalVarDecl)
3508 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3509 else
3510 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3511 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3512 Constructor += " Desc = desc;\n";
3513 }
3514 Constructor += " ";
3515 Constructor += "}\n";
3516 S += Constructor;
3517 S += "};\n";
3518 return S;
3519}
3520
3521std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
3522 std::string ImplTag, int i,
3523 StringRef FunName,
3524 unsigned hasCopy) {
3525 std::string S = "\nstatic struct " + DescTag;
3526
3527 S += " {\n unsigned long reserved;\n";
3528 S += " unsigned long Block_size;\n";
3529 if (hasCopy) {
3530 S += " void (*copy)(struct ";
3531 S += ImplTag; S += "*, struct ";
3532 S += ImplTag; S += "*);\n";
3533
3534 S += " void (*dispose)(struct ";
3535 S += ImplTag; S += "*);\n";
3536 }
3537 S += "} ";
3538
3539 S += DescTag + "_DATA = { 0, sizeof(struct ";
3540 S += ImplTag + ")";
3541 if (hasCopy) {
3542 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3543 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
3544 }
3545 S += "};\n";
3546 return S;
3547}
3548
3549void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3550 StringRef FunName) {
3551 // Insert declaration for the function in which block literal is used.
3552 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
3553 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
3554 bool RewriteSC = (GlobalVarDecl &&
3555 !Blocks.empty() &&
3556 GlobalVarDecl->getStorageClass() == SC_Static &&
3557 GlobalVarDecl->getType().getCVRQualifiers());
3558 if (RewriteSC) {
3559 std::string SC(" void __");
3560 SC += GlobalVarDecl->getNameAsString();
3561 SC += "() {}";
3562 InsertText(FunLocStart, SC);
3563 }
3564
3565 // Insert closures that were part of the function.
3566 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3567 CollectBlockDeclRefInfo(Blocks[i]);
3568 // Need to copy-in the inner copied-in variables not actually used in this
3569 // block.
3570 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00003571 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003572 ValueDecl *VD = Exp->getDecl();
3573 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00003574 if (!VD->hasAttr<BlocksAttr>()) {
3575 if (!BlockByCopyDeclsPtrSet.count(VD)) {
3576 BlockByCopyDeclsPtrSet.insert(VD);
3577 BlockByCopyDecls.push_back(VD);
3578 }
3579 continue;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003580 }
John McCallf4b88a42012-03-10 09:33:50 +00003581
3582 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003583 BlockByRefDeclsPtrSet.insert(VD);
3584 BlockByRefDecls.push_back(VD);
3585 }
John McCallf4b88a42012-03-10 09:33:50 +00003586
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003587 // imported objects in the inner blocks not used in the outer
3588 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00003589 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003590 VD->getType()->isBlockPointerType())
3591 ImportedBlockDecls.insert(VD);
3592 }
3593
3594 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3595 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
3596
3597 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
3598
3599 InsertText(FunLocStart, CI);
3600
3601 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
3602
3603 InsertText(FunLocStart, CF);
3604
3605 if (ImportedBlockDecls.size()) {
3606 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
3607 InsertText(FunLocStart, HF);
3608 }
3609 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3610 ImportedBlockDecls.size() > 0);
3611 InsertText(FunLocStart, BD);
3612
3613 BlockDeclRefs.clear();
3614 BlockByRefDecls.clear();
3615 BlockByRefDeclsPtrSet.clear();
3616 BlockByCopyDecls.clear();
3617 BlockByCopyDeclsPtrSet.clear();
3618 ImportedBlockDecls.clear();
3619 }
3620 if (RewriteSC) {
3621 // Must insert any 'const/volatile/static here. Since it has been
3622 // removed as result of rewriting of block literals.
3623 std::string SC;
3624 if (GlobalVarDecl->getStorageClass() == SC_Static)
3625 SC = "static ";
3626 if (GlobalVarDecl->getType().isConstQualified())
3627 SC += "const ";
3628 if (GlobalVarDecl->getType().isVolatileQualified())
3629 SC += "volatile ";
3630 if (GlobalVarDecl->getType().isRestrictQualified())
3631 SC += "restrict ";
3632 InsertText(FunLocStart, SC);
3633 }
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00003634 if (GlobalConstructionExp) {
3635 // extra fancy dance for global literal expression.
3636
3637 // Always the latest block expression on the block stack.
3638 std::string Tag = "__";
3639 Tag += FunName;
3640 Tag += "_block_impl_";
3641 Tag += utostr(Blocks.size()-1);
3642 std::string globalBuf = "static ";
3643 globalBuf += Tag; globalBuf += " ";
3644 std::string SStr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003645
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00003646 llvm::raw_string_ostream constructorExprBuf(SStr);
3647 GlobalConstructionExp->printPretty(constructorExprBuf, *Context, 0,
3648 PrintingPolicy(LangOpts));
3649 globalBuf += constructorExprBuf.str();
3650 globalBuf += ";\n";
3651 InsertText(FunLocStart, globalBuf);
3652 GlobalConstructionExp = 0;
3653 }
3654
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003655 Blocks.clear();
3656 InnerDeclRefsCount.clear();
3657 InnerDeclRefs.clear();
3658 RewrittenBlockExprs.clear();
3659}
3660
3661void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3662 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
3663 StringRef FuncName = FD->getName();
3664
3665 SynthesizeBlockLiterals(FunLocStart, FuncName);
3666}
3667
3668static void BuildUniqueMethodName(std::string &Name,
3669 ObjCMethodDecl *MD) {
3670 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3671 Name = IFace->getName();
3672 Name += "__" + MD->getSelector().getAsString();
3673 // Convert colons to underscores.
3674 std::string::size_type loc = 0;
3675 while ((loc = Name.find(":", loc)) != std::string::npos)
3676 Name.replace(loc, 1, "_");
3677}
3678
3679void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
3680 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3681 //SourceLocation FunLocStart = MD->getLocStart();
3682 SourceLocation FunLocStart = MD->getLocStart();
3683 std::string FuncName;
3684 BuildUniqueMethodName(FuncName, MD);
3685 SynthesizeBlockLiterals(FunLocStart, FuncName);
3686}
3687
3688void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
3689 for (Stmt::child_range CI = S->children(); CI; ++CI)
3690 if (*CI) {
3691 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3692 GetBlockDeclRefExprs(CBE->getBody());
3693 else
3694 GetBlockDeclRefExprs(*CI);
3695 }
3696 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00003697 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
3698 if (DRE->refersToEnclosingLocal() &&
3699 HasLocalVariableExternalStorage(DRE->getDecl())) {
3700 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003701 }
3702
3703 return;
3704}
3705
3706void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +00003707 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003708 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
3709 for (Stmt::child_range CI = S->children(); CI; ++CI)
3710 if (*CI) {
3711 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
3712 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
3713 GetInnerBlockDeclRefExprs(CBE->getBody(),
3714 InnerBlockDeclRefs,
3715 InnerContexts);
3716 }
3717 else
3718 GetInnerBlockDeclRefExprs(*CI,
3719 InnerBlockDeclRefs,
3720 InnerContexts);
3721
3722 }
3723 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00003724 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3725 if (DRE->refersToEnclosingLocal()) {
3726 if (!isa<FunctionDecl>(DRE->getDecl()) &&
3727 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
3728 InnerBlockDeclRefs.push_back(DRE);
3729 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
3730 if (Var->isFunctionOrMethodVarDecl())
3731 ImportedLocalExternalDecls.insert(Var);
3732 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003733 }
3734
3735 return;
3736}
3737
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003738/// convertObjCTypeToCStyleType - This routine converts such objc types
3739/// as qualified objects, and blocks to their closest c/c++ types that
3740/// it can. It returns true if input type was modified.
3741bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
3742 QualType oldT = T;
3743 convertBlockPointerToFunctionPointer(T);
3744 if (T->isFunctionPointerType()) {
3745 QualType PointeeTy;
3746 if (const PointerType* PT = T->getAs<PointerType>()) {
3747 PointeeTy = PT->getPointeeType();
3748 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
3749 T = convertFunctionTypeOfBlocks(FT);
3750 T = Context->getPointerType(T);
3751 }
3752 }
3753 }
3754
3755 convertToUnqualifiedObjCType(T);
3756 return T != oldT;
3757}
3758
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003759/// convertFunctionTypeOfBlocks - This routine converts a function type
3760/// whose result type may be a block pointer or whose argument type(s)
3761/// might be block pointers to an equivalent function type replacing
3762/// all block pointers to function pointers.
3763QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3764 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3765 // FTP will be null for closures that don't take arguments.
3766 // Generate a funky cast.
3767 SmallVector<QualType, 8> ArgTypes;
3768 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003769 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003770
3771 if (FTP) {
3772 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3773 E = FTP->arg_type_end(); I && (I != E); ++I) {
3774 QualType t = *I;
3775 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003776 if (convertObjCTypeToCStyleType(t))
3777 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003778 ArgTypes.push_back(t);
3779 }
3780 }
3781 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003782 if (modified)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003783 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
3784 else FuncType = QualType(FT, 0);
3785 return FuncType;
3786}
3787
3788Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
3789 // Navigate to relevant type information.
3790 const BlockPointerType *CPT = 0;
3791
3792 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
3793 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003794 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
3795 CPT = MExpr->getType()->getAs<BlockPointerType>();
3796 }
3797 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3798 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3799 }
3800 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3801 CPT = IEXPR->getType()->getAs<BlockPointerType>();
3802 else if (const ConditionalOperator *CEXPR =
3803 dyn_cast<ConditionalOperator>(BlockExp)) {
3804 Expr *LHSExp = CEXPR->getLHS();
3805 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3806 Expr *RHSExp = CEXPR->getRHS();
3807 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3808 Expr *CONDExp = CEXPR->getCond();
3809 ConditionalOperator *CondExpr =
3810 new (Context) ConditionalOperator(CONDExp,
3811 SourceLocation(), cast<Expr>(LHSStmt),
3812 SourceLocation(), cast<Expr>(RHSStmt),
3813 Exp->getType(), VK_RValue, OK_Ordinary);
3814 return CondExpr;
3815 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3816 CPT = IRE->getType()->getAs<BlockPointerType>();
3817 } else if (const PseudoObjectExpr *POE
3818 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3819 CPT = POE->getType()->castAs<BlockPointerType>();
3820 } else {
3821 assert(1 && "RewriteBlockClass: Bad type");
3822 }
3823 assert(CPT && "RewriteBlockClass: Bad type");
3824 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
3825 assert(FT && "RewriteBlockClass: Bad type");
3826 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3827 // FTP will be null for closures that don't take arguments.
3828
3829 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3830 SourceLocation(), SourceLocation(),
3831 &Context->Idents.get("__block_impl"));
3832 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
3833
3834 // Generate a funky cast.
3835 SmallVector<QualType, 8> ArgTypes;
3836
3837 // Push the block argument type.
3838 ArgTypes.push_back(PtrBlock);
3839 if (FTP) {
3840 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3841 E = FTP->arg_type_end(); I && (I != E); ++I) {
3842 QualType t = *I;
3843 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3844 if (!convertBlockPointerToFunctionPointer(t))
3845 convertToUnqualifiedObjCType(t);
3846 ArgTypes.push_back(t);
3847 }
3848 }
3849 // Now do the pointer to function cast.
3850 QualType PtrToFuncCastType
3851 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
3852
3853 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
3854
3855 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
3856 CK_BitCast,
3857 const_cast<Expr*>(BlockExp));
3858 // Don't forget the parens to enforce the proper binding.
3859 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3860 BlkCast);
3861 //PE->dump();
3862
3863 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3864 SourceLocation(),
3865 &Context->Idents.get("FuncPtr"),
3866 Context->VoidPtrTy, 0,
3867 /*BitWidth=*/0, /*Mutable=*/true,
3868 /*HasInit=*/false);
3869 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
3870 FD->getType(), VK_LValue,
3871 OK_Ordinary);
3872
3873
3874 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
3875 CK_BitCast, ME);
3876 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3877
3878 SmallVector<Expr*, 8> BlkExprs;
3879 // Add the implicit argument.
3880 BlkExprs.push_back(BlkCast);
3881 // Add the user arguments.
3882 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3883 E = Exp->arg_end(); I != E; ++I) {
3884 BlkExprs.push_back(*I);
3885 }
3886 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
3887 BlkExprs.size(),
3888 Exp->getType(), VK_RValue,
3889 SourceLocation());
3890 return CE;
3891}
3892
3893// We need to return the rewritten expression to handle cases where the
John McCallf4b88a42012-03-10 09:33:50 +00003894// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003895// For example:
3896//
3897// int main() {
3898// __block Foo *f;
3899// __block int i;
3900//
3901// void (^myblock)() = ^() {
John McCallf4b88a42012-03-10 09:33:50 +00003902// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003903// i = 77;
3904// };
3905//}
John McCallf4b88a42012-03-10 09:33:50 +00003906Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003907 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
3908 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00003909 ValueDecl *VD = DeclRefExp->getDecl();
3910 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003911
3912 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3913 SourceLocation(),
3914 &Context->Idents.get("__forwarding"),
3915 Context->VoidPtrTy, 0,
3916 /*BitWidth=*/0, /*Mutable=*/true,
3917 /*HasInit=*/false);
3918 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
3919 FD, SourceLocation(),
3920 FD->getType(), VK_LValue,
3921 OK_Ordinary);
3922
3923 StringRef Name = VD->getName();
3924 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
3925 &Context->Idents.get(Name),
3926 Context->VoidPtrTy, 0,
3927 /*BitWidth=*/0, /*Mutable=*/true,
3928 /*HasInit=*/false);
3929 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
3930 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
3931
3932
3933
3934 // Need parens to enforce precedence.
3935 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
3936 DeclRefExp->getExprLoc(),
3937 ME);
3938 ReplaceStmt(DeclRefExp, PE);
3939 return PE;
3940}
3941
3942// Rewrites the imported local variable V with external storage
3943// (static, extern, etc.) as *V
3944//
3945Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
3946 ValueDecl *VD = DRE->getDecl();
3947 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3948 if (!ImportedLocalExternalDecls.count(Var))
3949 return DRE;
3950 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
3951 VK_LValue, OK_Ordinary,
3952 DRE->getLocation());
3953 // Need parens to enforce precedence.
3954 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3955 Exp);
3956 ReplaceStmt(DRE, PE);
3957 return PE;
3958}
3959
3960void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3961 SourceLocation LocStart = CE->getLParenLoc();
3962 SourceLocation LocEnd = CE->getRParenLoc();
3963
3964 // Need to avoid trying to rewrite synthesized casts.
3965 if (LocStart.isInvalid())
3966 return;
3967 // Need to avoid trying to rewrite casts contained in macros.
3968 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3969 return;
3970
3971 const char *startBuf = SM->getCharacterData(LocStart);
3972 const char *endBuf = SM->getCharacterData(LocEnd);
3973 QualType QT = CE->getType();
3974 const Type* TypePtr = QT->getAs<Type>();
3975 if (isa<TypeOfExprType>(TypePtr)) {
3976 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
3977 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
3978 std::string TypeAsString = "(";
3979 RewriteBlockPointerType(TypeAsString, QT);
3980 TypeAsString += ")";
3981 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
3982 return;
3983 }
3984 // advance the location to startArgList.
3985 const char *argPtr = startBuf;
3986
3987 while (*argPtr++ && (argPtr < endBuf)) {
3988 switch (*argPtr) {
3989 case '^':
3990 // Replace the '^' with '*'.
3991 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
3992 ReplaceText(LocStart, 1, "*");
3993 break;
3994 }
3995 }
3996 return;
3997}
3998
3999void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4000 SourceLocation DeclLoc = FD->getLocation();
4001 unsigned parenCount = 0;
4002
4003 // We have 1 or more arguments that have closure pointers.
4004 const char *startBuf = SM->getCharacterData(DeclLoc);
4005 const char *startArgList = strchr(startBuf, '(');
4006
4007 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4008
4009 parenCount++;
4010 // advance the location to startArgList.
4011 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4012 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4013
4014 const char *argPtr = startArgList;
4015
4016 while (*argPtr++ && parenCount) {
4017 switch (*argPtr) {
4018 case '^':
4019 // Replace the '^' with '*'.
4020 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4021 ReplaceText(DeclLoc, 1, "*");
4022 break;
4023 case '(':
4024 parenCount++;
4025 break;
4026 case ')':
4027 parenCount--;
4028 break;
4029 }
4030 }
4031 return;
4032}
4033
4034bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4035 const FunctionProtoType *FTP;
4036 const PointerType *PT = QT->getAs<PointerType>();
4037 if (PT) {
4038 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4039 } else {
4040 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4041 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4042 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4043 }
4044 if (FTP) {
4045 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4046 E = FTP->arg_type_end(); I != E; ++I)
4047 if (isTopLevelBlockPointerType(*I))
4048 return true;
4049 }
4050 return false;
4051}
4052
4053bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4054 const FunctionProtoType *FTP;
4055 const PointerType *PT = QT->getAs<PointerType>();
4056 if (PT) {
4057 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4058 } else {
4059 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4060 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4061 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4062 }
4063 if (FTP) {
4064 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4065 E = FTP->arg_type_end(); I != E; ++I) {
4066 if ((*I)->isObjCQualifiedIdType())
4067 return true;
4068 if ((*I)->isObjCObjectPointerType() &&
4069 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4070 return true;
4071 }
4072
4073 }
4074 return false;
4075}
4076
4077void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4078 const char *&RParen) {
4079 const char *argPtr = strchr(Name, '(');
4080 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4081
4082 LParen = argPtr; // output the start.
4083 argPtr++; // skip past the left paren.
4084 unsigned parenCount = 1;
4085
4086 while (*argPtr && parenCount) {
4087 switch (*argPtr) {
4088 case '(': parenCount++; break;
4089 case ')': parenCount--; break;
4090 default: break;
4091 }
4092 if (parenCount) argPtr++;
4093 }
4094 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4095 RParen = argPtr; // output the end
4096}
4097
4098void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4099 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4100 RewriteBlockPointerFunctionArgs(FD);
4101 return;
4102 }
4103 // Handle Variables and Typedefs.
4104 SourceLocation DeclLoc = ND->getLocation();
4105 QualType DeclT;
4106 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4107 DeclT = VD->getType();
4108 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4109 DeclT = TDD->getUnderlyingType();
4110 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4111 DeclT = FD->getType();
4112 else
4113 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4114
4115 const char *startBuf = SM->getCharacterData(DeclLoc);
4116 const char *endBuf = startBuf;
4117 // scan backward (from the decl location) for the end of the previous decl.
4118 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4119 startBuf--;
4120 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4121 std::string buf;
4122 unsigned OrigLength=0;
4123 // *startBuf != '^' if we are dealing with a pointer to function that
4124 // may take block argument types (which will be handled below).
4125 if (*startBuf == '^') {
4126 // Replace the '^' with '*', computing a negative offset.
4127 buf = '*';
4128 startBuf++;
4129 OrigLength++;
4130 }
4131 while (*startBuf != ')') {
4132 buf += *startBuf;
4133 startBuf++;
4134 OrigLength++;
4135 }
4136 buf += ')';
4137 OrigLength++;
4138
4139 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4140 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4141 // Replace the '^' with '*' for arguments.
4142 // Replace id<P> with id/*<>*/
4143 DeclLoc = ND->getLocation();
4144 startBuf = SM->getCharacterData(DeclLoc);
4145 const char *argListBegin, *argListEnd;
4146 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4147 while (argListBegin < argListEnd) {
4148 if (*argListBegin == '^')
4149 buf += '*';
4150 else if (*argListBegin == '<') {
4151 buf += "/*";
4152 buf += *argListBegin++;
4153 OrigLength++;;
4154 while (*argListBegin != '>') {
4155 buf += *argListBegin++;
4156 OrigLength++;
4157 }
4158 buf += *argListBegin;
4159 buf += "*/";
4160 }
4161 else
4162 buf += *argListBegin;
4163 argListBegin++;
4164 OrigLength++;
4165 }
4166 buf += ')';
4167 OrigLength++;
4168 }
4169 ReplaceText(Start, OrigLength, buf);
4170
4171 return;
4172}
4173
4174
4175/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4176/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4177/// struct Block_byref_id_object *src) {
4178/// _Block_object_assign (&_dest->object, _src->object,
4179/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4180/// [|BLOCK_FIELD_IS_WEAK]) // object
4181/// _Block_object_assign(&_dest->object, _src->object,
4182/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4183/// [|BLOCK_FIELD_IS_WEAK]) // block
4184/// }
4185/// And:
4186/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4187/// _Block_object_dispose(_src->object,
4188/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4189/// [|BLOCK_FIELD_IS_WEAK]) // object
4190/// _Block_object_dispose(_src->object,
4191/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4192/// [|BLOCK_FIELD_IS_WEAK]) // block
4193/// }
4194
4195std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4196 int flag) {
4197 std::string S;
4198 if (CopyDestroyCache.count(flag))
4199 return S;
4200 CopyDestroyCache.insert(flag);
4201 S = "static void __Block_byref_id_object_copy_";
4202 S += utostr(flag);
4203 S += "(void *dst, void *src) {\n";
4204
4205 // offset into the object pointer is computed as:
4206 // void * + void* + int + int + void* + void *
4207 unsigned IntSize =
4208 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4209 unsigned VoidPtrSize =
4210 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4211
4212 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4213 S += " _Block_object_assign((char*)dst + ";
4214 S += utostr(offset);
4215 S += ", *(void * *) ((char*)src + ";
4216 S += utostr(offset);
4217 S += "), ";
4218 S += utostr(flag);
4219 S += ");\n}\n";
4220
4221 S += "static void __Block_byref_id_object_dispose_";
4222 S += utostr(flag);
4223 S += "(void *src) {\n";
4224 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4225 S += utostr(offset);
4226 S += "), ";
4227 S += utostr(flag);
4228 S += ");\n}\n";
4229 return S;
4230}
4231
4232/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4233/// the declaration into:
4234/// struct __Block_byref_ND {
4235/// void *__isa; // NULL for everything except __weak pointers
4236/// struct __Block_byref_ND *__forwarding;
4237/// int32_t __flags;
4238/// int32_t __size;
4239/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4240/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4241/// typex ND;
4242/// };
4243///
4244/// It then replaces declaration of ND variable with:
4245/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4246/// __size=sizeof(struct __Block_byref_ND),
4247/// ND=initializer-if-any};
4248///
4249///
4250void RewriteModernObjC::RewriteByRefVar(VarDecl *ND) {
4251 // Insert declaration for the function in which block literal is
4252 // used.
4253 if (CurFunctionDeclToDeclareForBlock)
4254 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
4255 int flag = 0;
4256 int isa = 0;
4257 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4258 if (DeclLoc.isInvalid())
4259 // If type location is missing, it is because of missing type (a warning).
4260 // Use variable's location which is good for this case.
4261 DeclLoc = ND->getLocation();
4262 const char *startBuf = SM->getCharacterData(DeclLoc);
4263 SourceLocation X = ND->getLocEnd();
4264 X = SM->getExpansionLoc(X);
4265 const char *endBuf = SM->getCharacterData(X);
4266 std::string Name(ND->getNameAsString());
4267 std::string ByrefType;
4268 RewriteByRefString(ByrefType, Name, ND, true);
4269 ByrefType += " {\n";
4270 ByrefType += " void *__isa;\n";
4271 RewriteByRefString(ByrefType, Name, ND);
4272 ByrefType += " *__forwarding;\n";
4273 ByrefType += " int __flags;\n";
4274 ByrefType += " int __size;\n";
4275 // Add void *__Block_byref_id_object_copy;
4276 // void *__Block_byref_id_object_dispose; if needed.
4277 QualType Ty = ND->getType();
4278 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4279 if (HasCopyAndDispose) {
4280 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4281 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4282 }
4283
4284 QualType T = Ty;
4285 (void)convertBlockPointerToFunctionPointer(T);
4286 T.getAsStringInternal(Name, Context->getPrintingPolicy());
4287
4288 ByrefType += " " + Name + ";\n";
4289 ByrefType += "};\n";
4290 // Insert this type in global scope. It is needed by helper function.
4291 SourceLocation FunLocStart;
4292 if (CurFunctionDef)
4293 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4294 else {
4295 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4296 FunLocStart = CurMethodDef->getLocStart();
4297 }
4298 InsertText(FunLocStart, ByrefType);
4299 if (Ty.isObjCGCWeak()) {
4300 flag |= BLOCK_FIELD_IS_WEAK;
4301 isa = 1;
4302 }
4303
4304 if (HasCopyAndDispose) {
4305 flag = BLOCK_BYREF_CALLER;
4306 QualType Ty = ND->getType();
4307 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4308 if (Ty->isBlockPointerType())
4309 flag |= BLOCK_FIELD_IS_BLOCK;
4310 else
4311 flag |= BLOCK_FIELD_IS_OBJECT;
4312 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
4313 if (!HF.empty())
4314 InsertText(FunLocStart, HF);
4315 }
4316
4317 // struct __Block_byref_ND ND =
4318 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4319 // initializer-if-any};
4320 bool hasInit = (ND->getInit() != 0);
4321 unsigned flags = 0;
4322 if (HasCopyAndDispose)
4323 flags |= BLOCK_HAS_COPY_DISPOSE;
4324 Name = ND->getNameAsString();
4325 ByrefType.clear();
4326 RewriteByRefString(ByrefType, Name, ND);
4327 std::string ForwardingCastType("(");
4328 ForwardingCastType += ByrefType + " *)";
4329 if (!hasInit) {
4330 ByrefType += " " + Name + " = {(void*)";
4331 ByrefType += utostr(isa);
4332 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4333 ByrefType += utostr(flags);
4334 ByrefType += ", ";
4335 ByrefType += "sizeof(";
4336 RewriteByRefString(ByrefType, Name, ND);
4337 ByrefType += ")";
4338 if (HasCopyAndDispose) {
4339 ByrefType += ", __Block_byref_id_object_copy_";
4340 ByrefType += utostr(flag);
4341 ByrefType += ", __Block_byref_id_object_dispose_";
4342 ByrefType += utostr(flag);
4343 }
4344 ByrefType += "};\n";
4345 unsigned nameSize = Name.size();
4346 // for block or function pointer declaration. Name is aleady
4347 // part of the declaration.
4348 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4349 nameSize = 1;
4350 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
4351 }
4352 else {
4353 SourceLocation startLoc;
4354 Expr *E = ND->getInit();
4355 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4356 startLoc = ECE->getLParenLoc();
4357 else
4358 startLoc = E->getLocStart();
4359 startLoc = SM->getExpansionLoc(startLoc);
4360 endBuf = SM->getCharacterData(startLoc);
4361 ByrefType += " " + Name;
4362 ByrefType += " = {(void*)";
4363 ByrefType += utostr(isa);
4364 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4365 ByrefType += utostr(flags);
4366 ByrefType += ", ";
4367 ByrefType += "sizeof(";
4368 RewriteByRefString(ByrefType, Name, ND);
4369 ByrefType += "), ";
4370 if (HasCopyAndDispose) {
4371 ByrefType += "__Block_byref_id_object_copy_";
4372 ByrefType += utostr(flag);
4373 ByrefType += ", __Block_byref_id_object_dispose_";
4374 ByrefType += utostr(flag);
4375 ByrefType += ", ";
4376 }
4377 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
4378
4379 // Complete the newly synthesized compound expression by inserting a right
4380 // curly brace before the end of the declaration.
4381 // FIXME: This approach avoids rewriting the initializer expression. It
4382 // also assumes there is only one declarator. For example, the following
4383 // isn't currently supported by this routine (in general):
4384 //
4385 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4386 //
4387 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4388 const char *semiBuf = strchr(startInitializerBuf, ';');
4389 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4390 SourceLocation semiLoc =
4391 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
4392
4393 InsertText(semiLoc, "}");
4394 }
4395 return;
4396}
4397
4398void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4399 // Add initializers for any closure decl refs.
4400 GetBlockDeclRefExprs(Exp->getBody());
4401 if (BlockDeclRefs.size()) {
4402 // Unique all "by copy" declarations.
4403 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004404 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004405 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4406 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4407 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4408 }
4409 }
4410 // Unique all "by ref" declarations.
4411 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004412 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004413 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4414 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4415 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4416 }
4417 }
4418 // Find any imported blocks...they will need special attention.
4419 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004420 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004421 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4422 BlockDeclRefs[i]->getType()->isBlockPointerType())
4423 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4424 }
4425}
4426
4427FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
4428 IdentifierInfo *ID = &Context->Idents.get(name);
4429 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
4430 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4431 SourceLocation(), ID, FType, 0, SC_Extern,
4432 SC_None, false, false);
4433}
4434
4435Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +00004436 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00004437
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004438 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00004439
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004440 Blocks.push_back(Exp);
4441
4442 CollectBlockDeclRefInfo(Exp);
4443
4444 // Add inner imported variables now used in current block.
4445 int countOfInnerDecls = 0;
4446 if (!InnerBlockDeclRefs.empty()) {
4447 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00004448 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004449 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00004450 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004451 // We need to save the copied-in variables in nested
4452 // blocks because it is needed at the end for some of the API generations.
4453 // See SynthesizeBlockLiterals routine.
4454 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4455 BlockDeclRefs.push_back(Exp);
4456 BlockByCopyDeclsPtrSet.insert(VD);
4457 BlockByCopyDecls.push_back(VD);
4458 }
John McCallf4b88a42012-03-10 09:33:50 +00004459 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004460 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4461 BlockDeclRefs.push_back(Exp);
4462 BlockByRefDeclsPtrSet.insert(VD);
4463 BlockByRefDecls.push_back(VD);
4464 }
4465 }
4466 // Find any imported blocks...they will need special attention.
4467 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004468 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004469 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4470 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4471 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
4472 }
4473 InnerDeclRefsCount.push_back(countOfInnerDecls);
4474
4475 std::string FuncName;
4476
4477 if (CurFunctionDef)
4478 FuncName = CurFunctionDef->getNameAsString();
4479 else if (CurMethodDef)
4480 BuildUniqueMethodName(FuncName, CurMethodDef);
4481 else if (GlobalVarDecl)
4482 FuncName = std::string(GlobalVarDecl->getNameAsString());
4483
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004484 bool GlobalBlockExpr =
4485 block->getDeclContext()->getRedeclContext()->isFileContext();
4486
4487 if (GlobalBlockExpr && !GlobalVarDecl) {
4488 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
4489 GlobalBlockExpr = false;
4490 }
4491
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004492 std::string BlockNumber = utostr(Blocks.size()-1);
4493
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004494 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4495
4496 // Get a pointer to the function type so we can cast appropriately.
4497 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4498 QualType FType = Context->getPointerType(BFT);
4499
4500 FunctionDecl *FD;
4501 Expr *NewRep;
4502
4503 // Simulate a contructor call...
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004504 std::string Tag;
4505
4506 if (GlobalBlockExpr)
4507 Tag = "__global_";
4508 else
4509 Tag = "__";
4510 Tag += FuncName + "_block_impl_" + BlockNumber;
4511
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004512 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00004513 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004514 SourceLocation());
4515
4516 SmallVector<Expr*, 4> InitExprs;
4517
4518 // Initialize the block function.
4519 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00004520 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4521 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004522 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4523 CK_BitCast, Arg);
4524 InitExprs.push_back(castExpr);
4525
4526 // Initialize the block descriptor.
4527 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
4528
4529 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
4530 SourceLocation(), SourceLocation(),
4531 &Context->Idents.get(DescData.c_str()),
4532 Context->VoidPtrTy, 0,
4533 SC_Static, SC_None);
4534 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00004535 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004536 Context->VoidPtrTy,
4537 VK_LValue,
4538 SourceLocation()),
4539 UO_AddrOf,
4540 Context->getPointerType(Context->VoidPtrTy),
4541 VK_RValue, OK_Ordinary,
4542 SourceLocation());
4543 InitExprs.push_back(DescRefExpr);
4544
4545 // Add initializers for any closure decl refs.
4546 if (BlockDeclRefs.size()) {
4547 Expr *Exp;
4548 // Output all "by copy" declarations.
4549 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4550 E = BlockByCopyDecls.end(); I != E; ++I) {
4551 if (isObjCType((*I)->getType())) {
4552 // FIXME: Conform to ABI ([[obj retain] autorelease]).
4553 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004554 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
4555 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004556 if (HasLocalVariableExternalStorage(*I)) {
4557 QualType QT = (*I)->getType();
4558 QT = Context->getPointerType(QT);
4559 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4560 OK_Ordinary, SourceLocation());
4561 }
4562 } else if (isTopLevelBlockPointerType((*I)->getType())) {
4563 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004564 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4565 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004566 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4567 CK_BitCast, Arg);
4568 } else {
4569 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004570 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
4571 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004572 if (HasLocalVariableExternalStorage(*I)) {
4573 QualType QT = (*I)->getType();
4574 QT = Context->getPointerType(QT);
4575 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4576 OK_Ordinary, SourceLocation());
4577 }
4578
4579 }
4580 InitExprs.push_back(Exp);
4581 }
4582 // Output all "by ref" declarations.
4583 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4584 E = BlockByRefDecls.end(); I != E; ++I) {
4585 ValueDecl *ND = (*I);
4586 std::string Name(ND->getNameAsString());
4587 std::string RecName;
4588 RewriteByRefString(RecName, Name, ND, true);
4589 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4590 + sizeof("struct"));
4591 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4592 SourceLocation(), SourceLocation(),
4593 II);
4594 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4595 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4596
4597 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004598 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004599 SourceLocation());
4600 bool isNestedCapturedVar = false;
4601 if (block)
4602 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
4603 ce = block->capture_end(); ci != ce; ++ci) {
4604 const VarDecl *variable = ci->getVariable();
4605 if (variable == ND && ci->isNested()) {
4606 assert (ci->isByRef() &&
4607 "SynthBlockInitExpr - captured block variable is not byref");
4608 isNestedCapturedVar = true;
4609 break;
4610 }
4611 }
4612 // captured nested byref variable has its address passed. Do not take
4613 // its address again.
4614 if (!isNestedCapturedVar)
4615 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
4616 Context->getPointerType(Exp->getType()),
4617 VK_RValue, OK_Ordinary, SourceLocation());
4618 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
4619 InitExprs.push_back(Exp);
4620 }
4621 }
4622 if (ImportedBlockDecls.size()) {
4623 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4624 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
4625 unsigned IntSize =
4626 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4627 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4628 Context->IntTy, SourceLocation());
4629 InitExprs.push_back(FlagExp);
4630 }
4631 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4632 FType, VK_LValue, SourceLocation());
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004633
4634 if (GlobalBlockExpr) {
4635 assert (GlobalConstructionExp == 0 &&
4636 "SynthBlockInitExpr - GlobalConstructionExp must be null");
4637 GlobalConstructionExp = NewRep;
4638 NewRep = DRE;
4639 }
4640
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004641 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
4642 Context->getPointerType(NewRep->getType()),
4643 VK_RValue, OK_Ordinary, SourceLocation());
4644 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
4645 NewRep);
4646 BlockDeclRefs.clear();
4647 BlockByRefDecls.clear();
4648 BlockByRefDeclsPtrSet.clear();
4649 BlockByCopyDecls.clear();
4650 BlockByCopyDeclsPtrSet.clear();
4651 ImportedBlockDecls.clear();
4652 return NewRep;
4653}
4654
4655bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4656 if (const ObjCForCollectionStmt * CS =
4657 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4658 return CS->getElement() == DS;
4659 return false;
4660}
4661
4662//===----------------------------------------------------------------------===//
4663// Function Body / Expression rewriting
4664//===----------------------------------------------------------------------===//
4665
4666Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4667 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4668 isa<DoStmt>(S) || isa<ForStmt>(S))
4669 Stmts.push_back(S);
4670 else if (isa<ObjCForCollectionStmt>(S)) {
4671 Stmts.push_back(S);
4672 ObjCBcLabelNo.push_back(++BcLabelCount);
4673 }
4674
4675 // Pseudo-object operations and ivar references need special
4676 // treatment because we're going to recursively rewrite them.
4677 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4678 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4679 return RewritePropertyOrImplicitSetter(PseudoOp);
4680 } else {
4681 return RewritePropertyOrImplicitGetter(PseudoOp);
4682 }
4683 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4684 return RewriteObjCIvarRefExpr(IvarRefExpr);
4685 }
4686
4687 SourceRange OrigStmtRange = S->getSourceRange();
4688
4689 // Perform a bottom up rewrite of all children.
4690 for (Stmt::child_range CI = S->children(); CI; ++CI)
4691 if (*CI) {
4692 Stmt *childStmt = (*CI);
4693 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
4694 if (newStmt) {
4695 *CI = newStmt;
4696 }
4697 }
4698
4699 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00004700 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004701 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4702 InnerContexts.insert(BE->getBlockDecl());
4703 ImportedLocalExternalDecls.clear();
4704 GetInnerBlockDeclRefExprs(BE->getBody(),
4705 InnerBlockDeclRefs, InnerContexts);
4706 // Rewrite the block body in place.
4707 Stmt *SaveCurrentBody = CurrentBody;
4708 CurrentBody = BE->getBody();
4709 PropParentMap = 0;
4710 // block literal on rhs of a property-dot-sytax assignment
4711 // must be replaced by its synthesize ast so getRewrittenText
4712 // works as expected. In this case, what actually ends up on RHS
4713 // is the blockTranscribed which is the helper function for the
4714 // block literal; as in: self.c = ^() {[ace ARR];};
4715 bool saveDisableReplaceStmt = DisableReplaceStmt;
4716 DisableReplaceStmt = false;
4717 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4718 DisableReplaceStmt = saveDisableReplaceStmt;
4719 CurrentBody = SaveCurrentBody;
4720 PropParentMap = 0;
4721 ImportedLocalExternalDecls.clear();
4722 // Now we snarf the rewritten text and stash it away for later use.
4723 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
4724 RewrittenBlockExprs[BE] = Str;
4725
4726 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4727
4728 //blockTranscribed->dump();
4729 ReplaceStmt(S, blockTranscribed);
4730 return blockTranscribed;
4731 }
4732 // Handle specific things.
4733 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4734 return RewriteAtEncode(AtEncode);
4735
4736 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4737 return RewriteAtSelector(AtSelector);
4738
4739 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4740 return RewriteObjCStringLiteral(AtString);
4741
4742 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
4743#if 0
4744 // Before we rewrite it, put the original message expression in a comment.
4745 SourceLocation startLoc = MessExpr->getLocStart();
4746 SourceLocation endLoc = MessExpr->getLocEnd();
4747
4748 const char *startBuf = SM->getCharacterData(startLoc);
4749 const char *endBuf = SM->getCharacterData(endLoc);
4750
4751 std::string messString;
4752 messString += "// ";
4753 messString.append(startBuf, endBuf-startBuf+1);
4754 messString += "\n";
4755
4756 // FIXME: Missing definition of
4757 // InsertText(clang::SourceLocation, char const*, unsigned int).
4758 // InsertText(startLoc, messString.c_str(), messString.size());
4759 // Tried this, but it didn't work either...
4760 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
4761#endif
4762 return RewriteMessageExpr(MessExpr);
4763 }
4764
4765 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4766 return RewriteObjCTryStmt(StmtTry);
4767
4768 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4769 return RewriteObjCSynchronizedStmt(StmtTry);
4770
4771 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4772 return RewriteObjCThrowStmt(StmtThrow);
4773
4774 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4775 return RewriteObjCProtocolExpr(ProtocolExp);
4776
4777 if (ObjCForCollectionStmt *StmtForCollection =
4778 dyn_cast<ObjCForCollectionStmt>(S))
4779 return RewriteObjCForCollectionStmt(StmtForCollection,
4780 OrigStmtRange.getEnd());
4781 if (BreakStmt *StmtBreakStmt =
4782 dyn_cast<BreakStmt>(S))
4783 return RewriteBreakStmt(StmtBreakStmt);
4784 if (ContinueStmt *StmtContinueStmt =
4785 dyn_cast<ContinueStmt>(S))
4786 return RewriteContinueStmt(StmtContinueStmt);
4787
4788 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4789 // and cast exprs.
4790 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4791 // FIXME: What we're doing here is modifying the type-specifier that
4792 // precedes the first Decl. In the future the DeclGroup should have
4793 // a separate type-specifier that we can rewrite.
4794 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4795 // the context of an ObjCForCollectionStmt. For example:
4796 // NSArray *someArray;
4797 // for (id <FooProtocol> index in someArray) ;
4798 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4799 // and it depends on the original text locations/positions.
4800 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
4801 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4802
4803 // Blocks rewrite rules.
4804 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4805 DI != DE; ++DI) {
4806 Decl *SD = *DI;
4807 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
4808 if (isTopLevelBlockPointerType(ND->getType()))
4809 RewriteBlockPointerDecl(ND);
4810 else if (ND->getType()->isFunctionPointerType())
4811 CheckFunctionPointerDecl(ND->getType(), ND);
4812 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
4813 if (VD->hasAttr<BlocksAttr>()) {
4814 static unsigned uniqueByrefDeclCount = 0;
4815 assert(!BlockByRefDeclNo.count(ND) &&
4816 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4817 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
4818 RewriteByRefVar(VD);
4819 }
4820 else
4821 RewriteTypeOfDecl(VD);
4822 }
4823 }
4824 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
4825 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4826 RewriteBlockPointerDecl(TD);
4827 else if (TD->getUnderlyingType()->isFunctionPointerType())
4828 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4829 }
4830 }
4831 }
4832
4833 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4834 RewriteObjCQualifiedInterfaceTypes(CE);
4835
4836 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4837 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4838 assert(!Stmts.empty() && "Statement stack is empty");
4839 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4840 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4841 && "Statement stack mismatch");
4842 Stmts.pop_back();
4843 }
4844 // Handle blocks rewriting.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004845 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4846 ValueDecl *VD = DRE->getDecl();
4847 if (VD->hasAttr<BlocksAttr>())
4848 return RewriteBlockDeclRefExpr(DRE);
4849 if (HasLocalVariableExternalStorage(VD))
4850 return RewriteLocalVariableExternalStorage(DRE);
4851 }
4852
4853 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4854 if (CE->getCallee()->getType()->isBlockPointerType()) {
4855 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
4856 ReplaceStmt(S, BlockCall);
4857 return BlockCall;
4858 }
4859 }
4860 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
4861 RewriteCastExpr(CE);
4862 }
4863#if 0
4864 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4865 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4866 ICE->getSubExpr(),
4867 SourceLocation());
4868 // Get the new text.
4869 std::string SStr;
4870 llvm::raw_string_ostream Buf(SStr);
4871 Replacement->printPretty(Buf, *Context);
4872 const std::string &Str = Buf.str();
4873
4874 printf("CAST = %s\n", &Str[0]);
4875 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4876 delete S;
4877 return Replacement;
4878 }
4879#endif
4880 // Return this stmt unmodified.
4881 return S;
4882}
4883
4884void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
4885 for (RecordDecl::field_iterator i = RD->field_begin(),
4886 e = RD->field_end(); i != e; ++i) {
4887 FieldDecl *FD = *i;
4888 if (isTopLevelBlockPointerType(FD->getType()))
4889 RewriteBlockPointerDecl(FD);
4890 if (FD->getType()->isObjCQualifiedIdType() ||
4891 FD->getType()->isObjCQualifiedInterfaceType())
4892 RewriteObjCQualifiedInterfaceTypes(FD);
4893 }
4894}
4895
4896/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4897/// main file of the input.
4898void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
4899 switch (D->getKind()) {
4900 case Decl::Function: {
4901 FunctionDecl *FD = cast<FunctionDecl>(D);
4902 if (FD->isOverloadedOperator())
4903 return;
4904
4905 // Since function prototypes don't have ParmDecl's, we check the function
4906 // prototype. This enables us to rewrite function declarations and
4907 // definitions using the same code.
4908 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
4909
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00004910 if (!FD->isThisDeclarationADefinition())
4911 break;
4912
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004913 // FIXME: If this should support Obj-C++, support CXXTryStmt
4914 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4915 CurFunctionDef = FD;
4916 CurFunctionDeclToDeclareForBlock = FD;
4917 CurrentBody = Body;
4918 Body =
4919 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4920 FD->setBody(Body);
4921 CurrentBody = 0;
4922 if (PropParentMap) {
4923 delete PropParentMap;
4924 PropParentMap = 0;
4925 }
4926 // This synthesizes and inserts the block "impl" struct, invoke function,
4927 // and any copy/dispose helper functions.
4928 InsertBlockLiteralsWithinFunction(FD);
4929 CurFunctionDef = 0;
4930 CurFunctionDeclToDeclareForBlock = 0;
4931 }
4932 break;
4933 }
4934 case Decl::ObjCMethod: {
4935 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
4936 if (CompoundStmt *Body = MD->getCompoundBody()) {
4937 CurMethodDef = MD;
4938 CurrentBody = Body;
4939 Body =
4940 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4941 MD->setBody(Body);
4942 CurrentBody = 0;
4943 if (PropParentMap) {
4944 delete PropParentMap;
4945 PropParentMap = 0;
4946 }
4947 InsertBlockLiteralsWithinMethod(MD);
4948 CurMethodDef = 0;
4949 }
4950 break;
4951 }
4952 case Decl::ObjCImplementation: {
4953 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
4954 ClassImplementation.push_back(CI);
4955 break;
4956 }
4957 case Decl::ObjCCategoryImpl: {
4958 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
4959 CategoryImplementation.push_back(CI);
4960 break;
4961 }
4962 case Decl::Var: {
4963 VarDecl *VD = cast<VarDecl>(D);
4964 RewriteObjCQualifiedInterfaceTypes(VD);
4965 if (isTopLevelBlockPointerType(VD->getType()))
4966 RewriteBlockPointerDecl(VD);
4967 else if (VD->getType()->isFunctionPointerType()) {
4968 CheckFunctionPointerDecl(VD->getType(), VD);
4969 if (VD->getInit()) {
4970 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4971 RewriteCastExpr(CE);
4972 }
4973 }
4974 } else if (VD->getType()->isRecordType()) {
4975 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4976 if (RD->isCompleteDefinition())
4977 RewriteRecordBody(RD);
4978 }
4979 if (VD->getInit()) {
4980 GlobalVarDecl = VD;
4981 CurrentBody = VD->getInit();
4982 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
4983 CurrentBody = 0;
4984 if (PropParentMap) {
4985 delete PropParentMap;
4986 PropParentMap = 0;
4987 }
4988 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
4989 GlobalVarDecl = 0;
4990
4991 // This is needed for blocks.
4992 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4993 RewriteCastExpr(CE);
4994 }
4995 }
4996 break;
4997 }
4998 case Decl::TypeAlias:
4999 case Decl::Typedef: {
5000 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5001 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5002 RewriteBlockPointerDecl(TD);
5003 else if (TD->getUnderlyingType()->isFunctionPointerType())
5004 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5005 }
5006 break;
5007 }
5008 case Decl::CXXRecord:
5009 case Decl::Record: {
5010 RecordDecl *RD = cast<RecordDecl>(D);
5011 if (RD->isCompleteDefinition())
5012 RewriteRecordBody(RD);
5013 break;
5014 }
5015 default:
5016 break;
5017 }
5018 // Nothing yet.
5019}
5020
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005021/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5022/// protocol reference symbols in the for of:
5023/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5024static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5025 ObjCProtocolDecl *PDecl,
5026 std::string &Result) {
5027 // Also output .objc_protorefs$B section and its meta-data.
5028 if (Context->getLangOpts().MicrosoftExt)
5029 Result += "__declspec(allocate(\".objc_protorefs$B\")) ";
5030 Result += "struct _protocol_t *";
5031 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5032 Result += PDecl->getNameAsString();
5033 Result += " = &";
5034 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5035 Result += ";\n";
5036}
5037
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005038void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5039 if (Diags.hasErrorOccurred())
5040 return;
5041
5042 RewriteInclude();
5043
5044 // Here's a great place to add any extra declarations that may be needed.
5045 // Write out meta data for each @protocol(<expr>).
5046 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005047 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005048 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005049 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
5050 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005051
5052 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian57317782012-02-21 23:58:41 +00005053 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5054 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5055 // Write struct declaration for the class matching its ivar declarations.
5056 // Note that for modern abi, this is postponed until the end of TU
5057 // because class extensions and the implementation might declare their own
5058 // private ivars.
5059 RewriteInterfaceDecl(CDecl);
5060 }
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00005061
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005062 if (ClassImplementation.size() || CategoryImplementation.size())
5063 RewriteImplementations();
5064
5065 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5066 // we are done.
5067 if (const RewriteBuffer *RewriteBuf =
5068 Rewrite.getRewriteBufferFor(MainFileID)) {
5069 //printf("Changed:\n");
5070 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5071 } else {
5072 llvm::errs() << "No changes\n";
5073 }
5074
5075 if (ClassImplementation.size() || CategoryImplementation.size() ||
5076 ProtocolExprDecls.size()) {
5077 // Rewrite Objective-c meta data*
5078 std::string ResultStr;
5079 RewriteMetaDataIntoBuffer(ResultStr);
5080 // Emit metadata.
5081 *OutFile << ResultStr;
5082 }
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005083 // Emit ImageInfo;
5084 {
5085 std::string ResultStr;
5086 WriteImageInfo(ResultStr);
5087 *OutFile << ResultStr;
5088 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005089 OutFile->flush();
5090}
5091
5092void RewriteModernObjC::Initialize(ASTContext &context) {
5093 InitializeCommon(context);
5094
Fariborz Jahanian6991bc52012-03-10 17:45:38 +00005095 Preamble += "#ifndef __OBJC2__\n";
5096 Preamble += "#define __OBJC2__\n";
5097 Preamble += "#endif\n";
5098
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005099 // declaring objc_selector outside the parameter list removes a silly
5100 // scope related warning...
5101 if (IsHeader)
5102 Preamble = "#pragma once\n";
5103 Preamble += "struct objc_selector; struct objc_class;\n";
5104 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
5105 Preamble += "struct objc_object *superClass; ";
5106 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005107 // Define all sections using syntax that makes sense.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005108 // These are currently generated.
5109 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005110 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005111 Preamble += "#pragma section(\".objc_protolist$B\", long, read, write)\n";
5112 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005113 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5114 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005115 Preamble += "#pragma section(\".objc_protorefs$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005116 // These are generated but not necessary for functionality.
5117 Preamble += "#pragma section(\".datacoal_nt$B\", long, read, write)\n";
5118 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005119 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5120 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005121 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005122
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005123 // These need be generated for performance. Currently they are not,
5124 // using API calls instead.
5125 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5126 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5127 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5128
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005129 // Add a constructor for creating temporary objects.
5130 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
5131 ": ";
5132 Preamble += "object(o), superClass(s) {} ";
5133 }
5134 Preamble += "};\n";
5135 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5136 Preamble += "typedef struct objc_object Protocol;\n";
5137 Preamble += "#define _REWRITER_typedef_Protocol\n";
5138 Preamble += "#endif\n";
5139 if (LangOpts.MicrosoftExt) {
5140 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5141 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005142 }
5143 else
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005144 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005145
5146 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
5147 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
5148 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
5149 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
5150 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
5151
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005152 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5153 Preamble += "(const char *);\n";
5154 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5155 Preamble += "(struct objc_class *);\n";
5156 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5157 Preamble += "(const char *);\n";
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005158 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005159 // @synchronized hooks.
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005160 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter( struct objc_object *);\n";
5161 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005162 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5163 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5164 Preamble += "struct __objcFastEnumerationState {\n\t";
5165 Preamble += "unsigned long state;\n\t";
5166 Preamble += "void **itemsPtr;\n\t";
5167 Preamble += "unsigned long *mutationsPtr;\n\t";
5168 Preamble += "unsigned long extra[5];\n};\n";
5169 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5170 Preamble += "#define __FASTENUMERATIONSTATE\n";
5171 Preamble += "#endif\n";
5172 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5173 Preamble += "struct __NSConstantStringImpl {\n";
5174 Preamble += " int *isa;\n";
5175 Preamble += " int flags;\n";
5176 Preamble += " char *str;\n";
5177 Preamble += " long length;\n";
5178 Preamble += "};\n";
5179 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5180 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5181 Preamble += "#else\n";
5182 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5183 Preamble += "#endif\n";
5184 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5185 Preamble += "#endif\n";
5186 // Blocks preamble.
5187 Preamble += "#ifndef BLOCK_IMPL\n";
5188 Preamble += "#define BLOCK_IMPL\n";
5189 Preamble += "struct __block_impl {\n";
5190 Preamble += " void *isa;\n";
5191 Preamble += " int Flags;\n";
5192 Preamble += " int Reserved;\n";
5193 Preamble += " void *FuncPtr;\n";
5194 Preamble += "};\n";
5195 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5196 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5197 Preamble += "extern \"C\" __declspec(dllexport) "
5198 "void _Block_object_assign(void *, const void *, const int);\n";
5199 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5200 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5201 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5202 Preamble += "#else\n";
5203 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5204 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5205 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5206 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5207 Preamble += "#endif\n";
5208 Preamble += "#endif\n";
5209 if (LangOpts.MicrosoftExt) {
5210 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5211 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5212 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5213 Preamble += "#define __attribute__(X)\n";
5214 Preamble += "#endif\n";
5215 Preamble += "#define __weak\n";
5216 }
5217 else {
5218 Preamble += "#define __block\n";
5219 Preamble += "#define __weak\n";
5220 }
5221 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5222 // as this avoids warning in any 64bit/32bit compilation model.
5223 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5224}
5225
5226/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5227/// ivar offset.
5228void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5229 std::string &Result) {
5230 if (ivar->isBitField()) {
5231 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5232 // place all bitfields at offset 0.
5233 Result += "0";
5234 } else {
5235 Result += "__OFFSETOFIVAR__(struct ";
5236 Result += ivar->getContainingInterface()->getNameAsString();
5237 if (LangOpts.MicrosoftExt)
5238 Result += "_IMPL";
5239 Result += ", ";
5240 Result += ivar->getNameAsString();
5241 Result += ")";
5242 }
5243}
5244
5245/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
5246/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005247/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005248/// char *attributes;
5249/// }
5250
5251/// struct _prop_list_t {
5252/// uint32_t entsize; // sizeof(struct _prop_t)
5253/// uint32_t count_of_properties;
5254/// struct _prop_t prop_list[count_of_properties];
5255/// }
5256
5257/// struct _protocol_t;
5258
5259/// struct _protocol_list_t {
5260/// long protocol_count; // Note, this is 32/64 bit
5261/// struct _protocol_t * protocol_list[protocol_count];
5262/// }
5263
5264/// struct _objc_method {
5265/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005266/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005267/// char *_imp;
5268/// }
5269
5270/// struct _method_list_t {
5271/// uint32_t entsize; // sizeof(struct _objc_method)
5272/// uint32_t method_count;
5273/// struct _objc_method method_list[method_count];
5274/// }
5275
5276/// struct _protocol_t {
5277/// id isa; // NULL
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005278/// const char *protocol_name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005279/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005280/// const struct method_list_t *instance_methods;
5281/// const struct method_list_t *class_methods;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005282/// const struct method_list_t *optionalInstanceMethods;
5283/// const struct method_list_t *optionalClassMethods;
5284/// const struct _prop_list_t * properties;
5285/// const uint32_t size; // sizeof(struct _protocol_t)
5286/// const uint32_t flags; // = 0
5287/// const char ** extendedMethodTypes;
5288/// }
5289
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005290/// struct _ivar_t {
5291/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00005292/// const char *name;
5293/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005294/// uint32_t alignment;
5295/// uint32_t size;
5296/// }
5297
5298/// struct _ivar_list_t {
5299/// uint32 entsize; // sizeof(struct _ivar_t)
5300/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00005301/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005302/// }
5303
5304/// struct _class_ro_t {
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005305/// uint32_t flags;
5306/// uint32_t instanceStart;
5307/// uint32_t instanceSize;
5308/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005309/// const uint8_t *ivarLayout;
5310/// const char *name;
5311/// const struct _method_list_t *baseMethods;
5312/// const struct _protocol_list_t *baseProtocols;
5313/// const struct _ivar_list_t *ivars;
5314/// const uint8_t *weakIvarLayout;
5315/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005316/// }
5317
5318/// struct _class_t {
5319/// struct _class_t *isa;
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00005320/// struct _class_t *superclass;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005321/// void *cache;
5322/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005323/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005324/// }
5325
5326/// struct _category_t {
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005327/// const char *name;
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005328/// struct _class_t *cls;
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005329/// const struct _method_list_t *instance_methods;
5330/// const struct _method_list_t *class_methods;
5331/// const struct _protocol_list_t *protocols;
5332/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005333/// }
5334
5335/// MessageRefTy - LLVM for:
5336/// struct _message_ref_t {
5337/// IMP messenger;
5338/// SEL name;
5339/// };
5340
5341/// SuperMessageRefTy - LLVM for:
5342/// struct _super_message_ref_t {
5343/// SUPER_IMP messenger;
5344/// SEL name;
5345/// };
5346
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005347static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005348 static bool meta_data_declared = false;
5349 if (meta_data_declared)
5350 return;
5351
5352 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005353 Result += "\tconst char *name;\n";
5354 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005355 Result += "};\n";
5356
5357 Result += "\nstruct _protocol_t;\n";
5358
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005359 Result += "\nstruct _objc_method {\n";
5360 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005361 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005362 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005363 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005364
5365 Result += "\nstruct _protocol_t {\n";
5366 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005367 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005368 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005369 Result += "\tconst struct method_list_t *instance_methods;\n";
5370 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005371 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
5372 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
5373 Result += "\tconst struct _prop_list_t * properties;\n";
5374 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
5375 Result += "\tconst unsigned int flags; // = 0\n";
5376 Result += "\tconst char ** extendedMethodTypes;\n";
5377 Result += "};\n";
5378
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005379 Result += "\nstruct _ivar_t {\n";
5380 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005381 Result += "\tconst char *name;\n";
5382 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005383 Result += "\tunsigned int alignment;\n";
5384 Result += "\tunsigned int size;\n";
5385 Result += "};\n";
5386
5387 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005388 Result += "\tunsigned int flags;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005389 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005390 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005391 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
5392 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005393 Result += "\tunsigned int reserved;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005394 Result += "\tconst unsigned char *ivarLayout;\n";
5395 Result += "\tconst char *name;\n";
5396 Result += "\tconst struct _method_list_t *baseMethods;\n";
5397 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
5398 Result += "\tconst struct _ivar_list_t *ivars;\n";
5399 Result += "\tconst unsigned char *weakIvarLayout;\n";
5400 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005401 Result += "};\n";
5402
5403 Result += "\nstruct _class_t {\n";
5404 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00005405 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005406 Result += "\tvoid *cache;\n";
5407 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005408 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005409 Result += "};\n";
5410
5411 Result += "\nstruct _category_t {\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005412 Result += "\tconst char *name;\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005413 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005414 Result += "\tconst struct _method_list_t *instance_methods;\n";
5415 Result += "\tconst struct _method_list_t *class_methods;\n";
5416 Result += "\tconst struct _protocol_list_t *protocols;\n";
5417 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005418 Result += "};\n";
5419
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005420 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005421
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005422 meta_data_declared = true;
5423}
5424
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005425static void Write_protocol_list_t_TypeDecl(std::string &Result,
5426 long super_protocol_count) {
5427 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
5428 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
5429 Result += "\tstruct _protocol_t *super_protocols[";
5430 Result += utostr(super_protocol_count); Result += "];\n";
5431 Result += "}";
5432}
5433
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005434static void Write_method_list_t_TypeDecl(std::string &Result,
5435 unsigned int method_count) {
5436 Result += "struct /*_method_list_t*/"; Result += " {\n";
5437 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
5438 Result += "\tunsigned int method_count;\n";
5439 Result += "\tstruct _objc_method method_list[";
5440 Result += utostr(method_count); Result += "];\n";
5441 Result += "}";
5442}
5443
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005444static void Write__prop_list_t_TypeDecl(std::string &Result,
5445 unsigned int property_count) {
5446 Result += "struct /*_prop_list_t*/"; Result += " {\n";
5447 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5448 Result += "\tunsigned int count_of_properties;\n";
5449 Result += "\tstruct _prop_t prop_list[";
5450 Result += utostr(property_count); Result += "];\n";
5451 Result += "}";
5452}
5453
Fariborz Jahanianae932952012-02-10 20:47:10 +00005454static void Write__ivar_list_t_TypeDecl(std::string &Result,
5455 unsigned int ivar_count) {
5456 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
5457 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5458 Result += "\tunsigned int count;\n";
5459 Result += "\tstruct _ivar_t ivar_list[";
5460 Result += utostr(ivar_count); Result += "];\n";
5461 Result += "}";
5462}
5463
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005464static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
5465 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
5466 StringRef VarName,
5467 StringRef ProtocolName) {
5468 if (SuperProtocols.size() > 0) {
5469 Result += "\nstatic ";
5470 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
5471 Result += " "; Result += VarName;
5472 Result += ProtocolName;
5473 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5474 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
5475 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
5476 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
5477 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
5478 Result += SuperPD->getNameAsString();
5479 if (i == e-1)
5480 Result += "\n};\n";
5481 else
5482 Result += ",\n";
5483 }
5484 }
5485}
5486
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005487static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
5488 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005489 ArrayRef<ObjCMethodDecl *> Methods,
5490 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005491 StringRef TopLevelDeclName,
5492 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005493 if (Methods.size() > 0) {
5494 Result += "\nstatic ";
5495 Write_method_list_t_TypeDecl(Result, Methods.size());
5496 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005497 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005498 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5499 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
5500 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
5501 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
5502 ObjCMethodDecl *MD = Methods[i];
5503 if (i == 0)
5504 Result += "\t{{(struct objc_selector *)\"";
5505 else
5506 Result += "\t{(struct objc_selector *)\"";
5507 Result += (MD)->getSelector().getAsString(); Result += "\"";
5508 Result += ", ";
5509 std::string MethodTypeString;
5510 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
5511 Result += "\""; Result += MethodTypeString; Result += "\"";
5512 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005513 if (!MethodImpl)
5514 Result += "0";
5515 else {
5516 Result += "(void *)";
5517 Result += RewriteObj.MethodInternalNames[MD];
5518 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005519 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005520 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005521 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005522 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005523 }
5524 Result += "};\n";
5525 }
5526}
5527
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005528static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005529 ASTContext *Context, std::string &Result,
5530 ArrayRef<ObjCPropertyDecl *> Properties,
5531 const Decl *Container,
5532 StringRef VarName,
5533 StringRef ProtocolName) {
5534 if (Properties.size() > 0) {
5535 Result += "\nstatic ";
5536 Write__prop_list_t_TypeDecl(Result, Properties.size());
5537 Result += " "; Result += VarName;
5538 Result += ProtocolName;
5539 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5540 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
5541 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
5542 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
5543 ObjCPropertyDecl *PropDecl = Properties[i];
5544 if (i == 0)
5545 Result += "\t{{\"";
5546 else
5547 Result += "\t{\"";
5548 Result += PropDecl->getName(); Result += "\",";
5549 std::string PropertyTypeString, QuotePropertyTypeString;
5550 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
5551 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
5552 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
5553 if (i == e-1)
5554 Result += "}}\n";
5555 else
5556 Result += "},\n";
5557 }
5558 Result += "};\n";
5559 }
5560}
5561
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005562// Metadata flags
5563enum MetaDataDlags {
5564 CLS = 0x0,
5565 CLS_META = 0x1,
5566 CLS_ROOT = 0x2,
5567 OBJC2_CLS_HIDDEN = 0x10,
5568 CLS_EXCEPTION = 0x20,
5569
5570 /// (Obsolete) ARC-specific: this class has a .release_ivars method
5571 CLS_HAS_IVAR_RELEASER = 0x40,
5572 /// class was compiled with -fobjc-arr
5573 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
5574};
5575
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005576static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
5577 unsigned int flags,
5578 const std::string &InstanceStart,
5579 const std::string &InstanceSize,
5580 ArrayRef<ObjCMethodDecl *>baseMethods,
5581 ArrayRef<ObjCProtocolDecl *>baseProtocols,
5582 ArrayRef<ObjCIvarDecl *>ivars,
5583 ArrayRef<ObjCPropertyDecl *>Properties,
5584 StringRef VarName,
5585 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005586 Result += "\nstatic struct _class_ro_t ";
5587 Result += VarName; Result += ClassName;
5588 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5589 Result += "\t";
5590 Result += llvm::utostr(flags); Result += ", ";
5591 Result += InstanceStart; Result += ", ";
5592 Result += InstanceSize; Result += ", \n";
5593 Result += "\t";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005594 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
5595 if (Triple.getArch() == llvm::Triple::x86_64)
5596 // uint32_t const reserved; // only when building for 64bit targets
5597 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005598 // const uint8_t * const ivarLayout;
5599 Result += "0, \n\t";
5600 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005601 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005602 if (baseMethods.size() > 0) {
5603 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005604 if (metaclass)
5605 Result += "_OBJC_$_CLASS_METHODS_";
5606 else
5607 Result += "_OBJC_$_INSTANCE_METHODS_";
5608 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005609 Result += ",\n\t";
5610 }
5611 else
5612 Result += "0, \n\t";
5613
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005614 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005615 Result += "(const struct _objc_protocol_list *)&";
5616 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
5617 Result += ",\n\t";
5618 }
5619 else
5620 Result += "0, \n\t";
5621
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005622 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005623 Result += "(const struct _ivar_list_t *)&";
5624 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
5625 Result += ",\n\t";
5626 }
5627 else
5628 Result += "0, \n\t";
5629
5630 // weakIvarLayout
5631 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005632 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005633 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00005634 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005635 Result += ",\n";
5636 }
5637 else
5638 Result += "0, \n";
5639
5640 Result += "};\n";
5641}
5642
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005643static void Write_class_t(ASTContext *Context, std::string &Result,
5644 StringRef VarName,
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005645 const ObjCInterfaceDecl *CDecl, bool metaclass) {
5646 bool rootClass = (!CDecl->getSuperClass());
5647 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005648
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005649 if (!rootClass) {
5650 // Find the Root class
5651 RootClass = CDecl->getSuperClass();
5652 while (RootClass->getSuperClass()) {
5653 RootClass = RootClass->getSuperClass();
5654 }
5655 }
5656
5657 if (metaclass && rootClass) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005658 // Need to handle a case of use of forward declaration.
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005659 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005660 Result += "extern \"C\" ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005661 if (CDecl->getImplementation())
5662 Result += "__declspec(dllexport) ";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005663 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005664 Result += CDecl->getNameAsString();
5665 Result += ";\n";
5666 }
5667 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005668 if (!rootClass) {
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005669 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005670 Result += "extern \"C\" ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005671 if (CDecl->getSuperClass()->getImplementation())
5672 Result += "__declspec(dllexport) ";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005673 Result += "struct _class_t ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005674 Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005675 Result += CDecl->getSuperClass()->getNameAsString();
5676 Result += ";\n";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00005677
5678 if (metaclass) {
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005679 Result += "extern \"C\" ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00005680 if (RootClass->getImplementation())
5681 Result += "__declspec(dllexport) ";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005682 Result += "struct _class_t ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00005683 Result += VarName;
5684 Result += RootClass->getNameAsString();
5685 Result += ";\n";
5686 }
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005687 }
5688
Fariborz Jahaniane57303c2012-03-10 00:39:34 +00005689 Result += "\n__declspec(dllexport) struct _class_t "; Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005690 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
5691 Result += "\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005692 if (metaclass) {
5693 if (!rootClass) {
5694 Result += "0, // &"; Result += VarName;
5695 Result += RootClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005696 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005697 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005698 Result += CDecl->getSuperClass()->getNameAsString();
5699 Result += ",\n\t";
5700 }
5701 else {
Fariborz Jahanian452eac12012-03-20 21:09:58 +00005702 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005703 Result += CDecl->getNameAsString();
5704 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005705 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005706 Result += ",\n\t";
5707 }
5708 }
5709 else {
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005710 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005711 Result += CDecl->getNameAsString();
5712 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005713 if (!rootClass) {
5714 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005715 Result += CDecl->getSuperClass()->getNameAsString();
5716 Result += ",\n\t";
5717 }
5718 else
5719 Result += "0,\n\t";
5720 }
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005721 Result += "0, // (void *)&_objc_empty_cache,\n\t";
5722 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
5723 if (metaclass)
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005724 Result += "&_OBJC_METACLASS_RO_$_";
5725 else
5726 Result += "&_OBJC_CLASS_RO_$_";
5727 Result += CDecl->getNameAsString();
5728 Result += ",\n};\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005729
5730 // Add static function to initialize some of the meta-data fields.
5731 // avoid doing it twice.
5732 if (metaclass)
5733 return;
5734
5735 const ObjCInterfaceDecl *SuperClass =
5736 rootClass ? CDecl : CDecl->getSuperClass();
5737
5738 Result += "static void OBJC_CLASS_SETUP_$_";
5739 Result += CDecl->getNameAsString();
5740 Result += "(void ) {\n";
5741 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
5742 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00005743 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005744
5745 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian452eac12012-03-20 21:09:58 +00005746 Result += ".superclass = ";
5747 if (rootClass)
5748 Result += "&OBJC_CLASS_$_";
5749 else
5750 Result += "&OBJC_METACLASS_$_";
5751
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005752 Result += SuperClass->getNameAsString(); Result += ";\n";
5753
5754 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
5755 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
5756
5757 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
5758 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
5759 Result += CDecl->getNameAsString(); Result += ";\n";
5760
5761 if (!rootClass) {
5762 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
5763 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
5764 Result += SuperClass->getNameAsString(); Result += ";\n";
5765 }
5766
5767 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
5768 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
5769 Result += "}\n";
5770
Fariborz Jahanianfde05e12012-03-21 00:01:15 +00005771 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005772 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
5773 Result += "static void *OBJC_CLASS_SETUP2_$_";
5774 Result += CDecl->getNameAsString();
5775 Result += " = (void *)&OBJC_CLASS_SETUP_$_";
5776 Result += CDecl->getNameAsString();
5777 Result += ";\n\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005778}
5779
Fariborz Jahanian61186122012-02-17 18:40:41 +00005780static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
5781 std::string &Result,
5782 StringRef CatName,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005783 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00005784 ArrayRef<ObjCMethodDecl *> InstanceMethods,
5785 ArrayRef<ObjCMethodDecl *> ClassMethods,
5786 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
5787 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005788
NAKAMURA Takumi20f89392012-03-21 03:21:46 +00005789 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00005790 // must declare an extern class object in case this class is not implemented
5791 // in this TU.
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005792 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005793 Result += "extern \"C\" ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005794 if (ClassDecl->getImplementation())
5795 Result += "__declspec(dllexport) ";
5796
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005797 Result += "struct _class_t ";
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00005798 Result += "OBJC_CLASS_$_"; Result += ClassName;
5799 Result += ";\n";
5800
Fariborz Jahanian61186122012-02-17 18:40:41 +00005801 Result += "\nstatic struct _category_t ";
5802 Result += "_OBJC_$_CATEGORY_";
5803 Result += ClassName; Result += "_$_"; Result += CatName;
5804 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
5805 Result += "{\n";
5806 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005807 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanian61186122012-02-17 18:40:41 +00005808 Result += ",\n";
5809 if (InstanceMethods.size() > 0) {
5810 Result += "\t(const struct _method_list_t *)&";
5811 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
5812 Result += ClassName; Result += "_$_"; Result += CatName;
5813 Result += ",\n";
5814 }
5815 else
5816 Result += "\t0,\n";
5817
5818 if (ClassMethods.size() > 0) {
5819 Result += "\t(const struct _method_list_t *)&";
5820 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
5821 Result += ClassName; Result += "_$_"; Result += CatName;
5822 Result += ",\n";
5823 }
5824 else
5825 Result += "\t0,\n";
5826
5827 if (RefedProtocols.size() > 0) {
5828 Result += "\t(const struct _protocol_list_t *)&";
5829 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
5830 Result += ClassName; Result += "_$_"; Result += CatName;
5831 Result += ",\n";
5832 }
5833 else
5834 Result += "\t0,\n";
5835
5836 if (ClassProperties.size() > 0) {
5837 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
5838 Result += ClassName; Result += "_$_"; Result += CatName;
5839 Result += ",\n";
5840 }
5841 else
5842 Result += "\t0,\n";
5843
5844 Result += "};\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005845
5846 // Add static function to initialize the class pointer in the category structure.
5847 Result += "static void OBJC_CATEGORY_SETUP_$_";
5848 Result += ClassDecl->getNameAsString();
5849 Result += "_$_";
5850 Result += CatName;
5851 Result += "(void ) {\n";
5852 Result += "\t_OBJC_$_CATEGORY_";
5853 Result += ClassDecl->getNameAsString();
5854 Result += "_$_";
5855 Result += CatName;
5856 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
5857 Result += ";\n}\n";
5858
Fariborz Jahanianfde05e12012-03-21 00:01:15 +00005859 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005860 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
5861 Result += "static void *OBJC_CATEGORY_SETUP2_$_";
5862 Result += ClassDecl->getNameAsString();
5863 Result += "_$_";
5864 Result += CatName;
5865 Result += " = (void *)&OBJC_CATEGORY_SETUP_$_";
5866 Result += ClassDecl->getNameAsString();
5867 Result += "_$_";
5868 Result += CatName;
5869 Result += ";\n\n";
Fariborz Jahanian61186122012-02-17 18:40:41 +00005870}
5871
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00005872static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
5873 ASTContext *Context, std::string &Result,
5874 ArrayRef<ObjCMethodDecl *> Methods,
5875 StringRef VarName,
5876 StringRef ProtocolName) {
5877 if (Methods.size() == 0)
5878 return;
5879
5880 Result += "\nstatic const char *";
5881 Result += VarName; Result += ProtocolName;
5882 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
5883 Result += "{\n";
5884 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
5885 ObjCMethodDecl *MD = Methods[i];
5886 std::string MethodTypeString, QuoteMethodTypeString;
5887 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
5888 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
5889 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
5890 if (i == e-1)
5891 Result += "\n};\n";
5892 else {
5893 Result += ",\n";
5894 }
5895 }
5896}
5897
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005898static void Write_IvarOffsetVar(ASTContext *Context,
5899 std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005900 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00005901 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005902 // FIXME. visibilty of offset symbols may have to be set; for Darwin
5903 // this is what happens:
5904 /**
5905 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
5906 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
5907 Class->getVisibility() == HiddenVisibility)
5908 Visibility shoud be: HiddenVisibility;
5909 else
5910 Visibility shoud be: DefaultVisibility;
5911 */
5912
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005913 Result += "\n";
5914 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
5915 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005916 if (Context->getLangOpts().MicrosoftExt)
5917 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
5918
5919 if (!Context->getLangOpts().MicrosoftExt ||
5920 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanian117591f2012-03-10 01:34:42 +00005921 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahaniand1c84d32012-03-10 00:53:02 +00005922 Result += "unsigned long int ";
5923 else
5924 Result += "__declspec(dllexport) unsigned long int ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00005925 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005926 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
5927 Result += " = ";
5928 if (IvarDecl->isBitField()) {
5929 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5930 // place all bitfields at offset 0.
5931 Result += "0;\n";
5932 }
5933 else {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005934 Result += "__OFFSETOFIVAR__(struct ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00005935 Result += CDecl->getNameAsString();
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005936 Result += "_IMPL, ";
5937 Result += IvarDecl->getName(); Result += ");\n";
5938 }
5939 }
5940}
5941
Fariborz Jahanianae932952012-02-10 20:47:10 +00005942static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
5943 ASTContext *Context, std::string &Result,
5944 ArrayRef<ObjCIvarDecl *> Ivars,
5945 StringRef VarName,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00005946 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanianae932952012-02-10 20:47:10 +00005947 if (Ivars.size() > 0) {
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00005948 Write_IvarOffsetVar(Context, Result, Ivars, CDecl);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005949
Fariborz Jahanianae932952012-02-10 20:47:10 +00005950 Result += "\nstatic ";
5951 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
5952 Result += " "; Result += VarName;
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00005953 Result += CDecl->getNameAsString();
Fariborz Jahanianae932952012-02-10 20:47:10 +00005954 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5955 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
5956 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
5957 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
5958 ObjCIvarDecl *IvarDecl = Ivars[i];
5959 if (i == 0)
5960 Result += "\t{{";
5961 else
5962 Result += "\t {";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00005963 Result += "(unsigned long int *)&";
5964 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005965 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005966
5967 Result += "\""; Result += IvarDecl->getName(); Result += "\", ";
5968 std::string IvarTypeString, QuoteIvarTypeString;
5969 Context->getObjCEncodingForType(IvarDecl->getType(), IvarTypeString,
5970 IvarDecl);
5971 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
5972 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
5973
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00005974 // FIXME. this alignment represents the host alignment and need be changed to
5975 // represent the target alignment.
5976 unsigned Align = Context->getTypeAlign(IvarDecl->getType())/8;
5977 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00005978 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00005979 CharUnits Size = Context->getTypeSizeInChars(IvarDecl->getType());
5980 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00005981 if (i == e-1)
5982 Result += "}}\n";
5983 else
5984 Result += "},\n";
5985 }
5986 Result += "};\n";
5987 }
5988}
5989
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005990/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005991void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
5992 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005993
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005994 // Do not synthesize the protocol more than once.
5995 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
5996 return;
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005997 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005998
5999 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6000 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006001 // Must write out all protocol definitions in current qualifier list,
6002 // and in their nested qualifiers before writing out current definition.
6003 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6004 E = PDecl->protocol_end(); I != E; ++I)
6005 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006006
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006007 // Construct method lists.
6008 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6009 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
6010 for (ObjCProtocolDecl::instmeth_iterator
6011 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
6012 I != E; ++I) {
6013 ObjCMethodDecl *MD = *I;
6014 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6015 OptInstanceMethods.push_back(MD);
6016 } else {
6017 InstanceMethods.push_back(MD);
6018 }
6019 }
6020
6021 for (ObjCProtocolDecl::classmeth_iterator
6022 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
6023 I != E; ++I) {
6024 ObjCMethodDecl *MD = *I;
6025 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6026 OptClassMethods.push_back(MD);
6027 } else {
6028 ClassMethods.push_back(MD);
6029 }
6030 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006031 std::vector<ObjCMethodDecl *> AllMethods;
6032 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6033 AllMethods.push_back(InstanceMethods[i]);
6034 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6035 AllMethods.push_back(ClassMethods[i]);
6036 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6037 AllMethods.push_back(OptInstanceMethods[i]);
6038 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6039 AllMethods.push_back(OptClassMethods[i]);
6040
6041 Write__extendedMethodTypes_initializer(*this, Context, Result,
6042 AllMethods,
6043 "_OBJC_PROTOCOL_METHOD_TYPES_",
6044 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006045 // Protocol's super protocol list
6046 std::vector<ObjCProtocolDecl *> SuperProtocols;
6047 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6048 E = PDecl->protocol_end(); I != E; ++I)
6049 SuperProtocols.push_back(*I);
6050
6051 Write_protocol_list_initializer(Context, Result, SuperProtocols,
6052 "_OBJC_PROTOCOL_REFS_",
6053 PDecl->getNameAsString());
6054
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006055 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006056 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006057 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006058
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006059 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006060 "_OBJC_PROTOCOL_CLASS_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, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006064 "_OBJC_PROTOCOL_OPT_INSTANCE_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, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006068 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006069 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006070
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006071 // Protocol's property metadata.
6072 std::vector<ObjCPropertyDecl *> ProtocolProperties;
6073 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
6074 E = PDecl->prop_end(); I != E; ++I)
6075 ProtocolProperties.push_back(*I);
6076
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006077 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006078 /* Container */0,
6079 "_OBJC_PROTOCOL_PROPERTIES_",
6080 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006081
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006082 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006083 Result += "\n";
6084 if (LangOpts.MicrosoftExt)
6085 Result += "__declspec(allocate(\".datacoal_nt$B\")) ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006086 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006087 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006088 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
6089 Result += "\t0,\n"; // id is; is null
6090 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006091 if (SuperProtocols.size() > 0) {
6092 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6093 Result += PDecl->getNameAsString(); Result += ",\n";
6094 }
6095 else
6096 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006097 if (InstanceMethods.size() > 0) {
6098 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
6099 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006100 }
6101 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006102 Result += "\t0,\n";
6103
6104 if (ClassMethods.size() > 0) {
6105 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
6106 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006107 }
6108 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006109 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006110
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006111 if (OptInstanceMethods.size() > 0) {
6112 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
6113 Result += PDecl->getNameAsString(); Result += ",\n";
6114 }
6115 else
6116 Result += "\t0,\n";
6117
6118 if (OptClassMethods.size() > 0) {
6119 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
6120 Result += PDecl->getNameAsString(); Result += ",\n";
6121 }
6122 else
6123 Result += "\t0,\n";
6124
6125 if (ProtocolProperties.size() > 0) {
6126 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
6127 Result += PDecl->getNameAsString(); Result += ",\n";
6128 }
6129 else
6130 Result += "\t0,\n";
6131
6132 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6133 Result += "\t0,\n";
6134
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006135 if (AllMethods.size() > 0) {
6136 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6137 Result += PDecl->getNameAsString();
6138 Result += "\n};\n";
6139 }
6140 else
6141 Result += "\t0\n};\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006142
6143 // Use this protocol meta-data to build protocol list table in section
6144 // .objc_protolist$B
6145 // Unspecified visibility means 'private extern'.
6146 if (LangOpts.MicrosoftExt)
6147 Result += "__declspec(allocate(\".objc_protolist$B\")) ";
6148 Result += "struct _protocol_t *";
6149 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6150 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6151 Result += ";\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006152
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006153 // Mark this protocol as having been generated.
6154 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
6155 llvm_unreachable("protocol already synthesized");
6156
6157}
6158
6159void RewriteModernObjC::RewriteObjCProtocolListMetaData(
6160 const ObjCList<ObjCProtocolDecl> &Protocols,
6161 StringRef prefix, StringRef ClassName,
6162 std::string &Result) {
6163 if (Protocols.empty()) return;
6164
6165 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006166 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006167
6168 // Output the top lovel protocol meta-data for the class.
6169 /* struct _objc_protocol_list {
6170 struct _objc_protocol_list *next;
6171 int protocol_count;
6172 struct _objc_protocol *class_protocols[];
6173 }
6174 */
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006175 Result += "\n";
6176 if (LangOpts.MicrosoftExt)
6177 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
6178 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006179 Result += "\tstruct _objc_protocol_list *next;\n";
6180 Result += "\tint protocol_count;\n";
6181 Result += "\tstruct _objc_protocol *class_protocols[";
6182 Result += utostr(Protocols.size());
6183 Result += "];\n} _OBJC_";
6184 Result += prefix;
6185 Result += "_PROTOCOLS_";
6186 Result += ClassName;
6187 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
6188 "{\n\t0, ";
6189 Result += utostr(Protocols.size());
6190 Result += "\n";
6191
6192 Result += "\t,{&_OBJC_PROTOCOL_";
6193 Result += Protocols[0]->getNameAsString();
6194 Result += " \n";
6195
6196 for (unsigned i = 1; i != Protocols.size(); i++) {
6197 Result += "\t ,&_OBJC_PROTOCOL_";
6198 Result += Protocols[i]->getNameAsString();
6199 Result += "\n";
6200 }
6201 Result += "\t }\n};\n";
6202}
6203
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006204/// hasObjCExceptionAttribute - Return true if this class or any super
6205/// class has the __objc_exception__ attribute.
6206/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
6207static bool hasObjCExceptionAttribute(ASTContext &Context,
6208 const ObjCInterfaceDecl *OID) {
6209 if (OID->hasAttr<ObjCExceptionAttr>())
6210 return true;
6211 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
6212 return hasObjCExceptionAttribute(Context, Super);
6213 return false;
6214}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006215
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006216void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
6217 std::string &Result) {
6218 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6219
6220 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00006221 if (CDecl->isImplicitInterfaceDecl())
6222 assert(false &&
6223 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006224
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006225 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006226 SmallVector<ObjCIvarDecl *, 8> IVars;
6227
6228 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6229 IVD; IVD = IVD->getNextIvar()) {
6230 // Ignore unnamed bit-fields.
6231 if (!IVD->getDeclName())
6232 continue;
6233 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006234 }
6235
Fariborz Jahanianae932952012-02-10 20:47:10 +00006236 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006237 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006238 CDecl);
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006239
6240 // Build _objc_method_list for class's instance methods if needed
6241 SmallVector<ObjCMethodDecl *, 32>
6242 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6243
6244 // If any of our property implementations have associated getters or
6245 // setters, produce metadata for them as well.
6246 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6247 PropEnd = IDecl->propimpl_end();
6248 Prop != PropEnd; ++Prop) {
6249 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6250 continue;
6251 if (!(*Prop)->getPropertyIvarDecl())
6252 continue;
6253 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
6254 if (!PD)
6255 continue;
6256 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
6257 if (!Getter->isDefined())
6258 InstanceMethods.push_back(Getter);
6259 if (PD->isReadOnly())
6260 continue;
6261 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
6262 if (!Setter->isDefined())
6263 InstanceMethods.push_back(Setter);
6264 }
6265
6266 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6267 "_OBJC_$_INSTANCE_METHODS_",
6268 IDecl->getNameAsString(), true);
6269
6270 SmallVector<ObjCMethodDecl *, 32>
6271 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6272
6273 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6274 "_OBJC_$_CLASS_METHODS_",
6275 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00006276
6277 // Protocols referenced in class declaration?
6278 // Protocol's super protocol list
6279 std::vector<ObjCProtocolDecl *> RefedProtocols;
6280 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
6281 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6282 E = Protocols.end();
6283 I != E; ++I) {
6284 RefedProtocols.push_back(*I);
6285 // Must write out all protocol definitions in current qualifier list,
6286 // and in their nested qualifiers before writing out current definition.
6287 RewriteObjCProtocolMetaData(*I, Result);
6288 }
6289
6290 Write_protocol_list_initializer(Context, Result,
6291 RefedProtocols,
6292 "_OBJC_CLASS_PROTOCOLS_$_",
6293 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006294
6295 // Protocol's property metadata.
6296 std::vector<ObjCPropertyDecl *> ClassProperties;
6297 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6298 E = CDecl->prop_end(); I != E; ++I)
6299 ClassProperties.push_back(*I);
6300
6301 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanian2df089d2012-03-22 17:39:35 +00006302 /* Container */IDecl,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006303 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006304 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006305
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006306
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006307 // Data for initializing _class_ro_t metaclass meta-data
6308 uint32_t flags = CLS_META;
6309 std::string InstanceSize;
6310 std::string InstanceStart;
6311
6312
6313 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
6314 if (classIsHidden)
6315 flags |= OBJC2_CLS_HIDDEN;
6316
6317 if (!CDecl->getSuperClass())
6318 // class is root
6319 flags |= CLS_ROOT;
6320 InstanceSize = "sizeof(struct _class_t)";
6321 InstanceStart = InstanceSize;
6322 Write__class_ro_t_initializer(Context, Result, flags,
6323 InstanceStart, InstanceSize,
6324 ClassMethods,
6325 0,
6326 0,
6327 0,
6328 "_OBJC_METACLASS_RO_$_",
6329 CDecl->getNameAsString());
6330
6331
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006332 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006333 flags = CLS;
6334 if (classIsHidden)
6335 flags |= OBJC2_CLS_HIDDEN;
6336
6337 if (hasObjCExceptionAttribute(*Context, CDecl))
6338 flags |= CLS_EXCEPTION;
6339
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006340 if (!CDecl->getSuperClass())
6341 // class is root
6342 flags |= CLS_ROOT;
6343
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006344 InstanceSize.clear();
6345 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006346 if (!ObjCSynthesizedStructs.count(CDecl)) {
6347 InstanceSize = "0";
6348 InstanceStart = "0";
6349 }
6350 else {
6351 InstanceSize = "sizeof(struct ";
6352 InstanceSize += CDecl->getNameAsString();
6353 InstanceSize += "_IMPL)";
6354
6355 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6356 if (IVD) {
6357 InstanceStart += "__OFFSETOFIVAR__(struct ";
6358 InstanceStart += CDecl->getNameAsString();
6359 InstanceStart += "_IMPL, ";
6360 InstanceStart += IVD->getNameAsString();
6361 InstanceStart += ")";
6362 }
6363 else
6364 InstanceStart = InstanceSize;
6365 }
6366 Write__class_ro_t_initializer(Context, Result, flags,
6367 InstanceStart, InstanceSize,
6368 InstanceMethods,
6369 RefedProtocols,
6370 IVars,
6371 ClassProperties,
6372 "_OBJC_CLASS_RO_$_",
6373 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006374
6375 Write_class_t(Context, Result,
6376 "OBJC_METACLASS_$_",
6377 CDecl, /*metaclass*/true);
6378
6379 Write_class_t(Context, Result,
6380 "OBJC_CLASS_$_",
6381 CDecl, /*metaclass*/false);
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006382
6383 if (ImplementationIsNonLazy(IDecl))
6384 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006385
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006386}
6387
6388void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
6389 int ClsDefCount = ClassImplementation.size();
6390 int CatDefCount = CategoryImplementation.size();
6391
6392 // For each implemented class, write out all its meta data.
6393 for (int i = 0; i < ClsDefCount; i++)
6394 RewriteObjCClassMetaData(ClassImplementation[i], Result);
6395
6396 // For each implemented category, write out all its meta data.
6397 for (int i = 0; i < CatDefCount; i++)
6398 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
6399
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006400 if (ClsDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006401 if (LangOpts.MicrosoftExt)
6402 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006403 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
6404 Result += llvm::utostr(ClsDefCount); Result += "]";
6405 Result +=
6406 " __attribute__((used, section (\"__DATA, __objc_classlist,"
6407 "regular,no_dead_strip\")))= {\n";
6408 for (int i = 0; i < ClsDefCount; i++) {
6409 Result += "\t&OBJC_CLASS_$_";
6410 Result += ClassImplementation[i]->getNameAsString();
6411 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006412 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006413 Result += "};\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006414
6415 if (!DefinedNonLazyClasses.empty()) {
6416 if (LangOpts.MicrosoftExt)
6417 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
6418 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
6419 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
6420 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
6421 Result += ",\n";
6422 }
6423 Result += "};\n";
6424 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006425 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00006426
6427 if (CatDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006428 if (LangOpts.MicrosoftExt)
6429 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006430 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
6431 Result += llvm::utostr(CatDefCount); Result += "]";
6432 Result +=
6433 " __attribute__((used, section (\"__DATA, __objc_catlist,"
6434 "regular,no_dead_strip\")))= {\n";
6435 for (int i = 0; i < CatDefCount; i++) {
6436 Result += "\t&_OBJC_$_CATEGORY_";
6437 Result +=
6438 CategoryImplementation[i]->getClassInterface()->getNameAsString();
6439 Result += "_$_";
6440 Result += CategoryImplementation[i]->getNameAsString();
6441 Result += ",\n";
6442 }
6443 Result += "};\n";
6444 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006445
6446 if (!DefinedNonLazyCategories.empty()) {
6447 if (LangOpts.MicrosoftExt)
6448 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
6449 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
6450 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
6451 Result += "\t&_OBJC_$_CATEGORY_";
6452 Result +=
6453 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
6454 Result += "_$_";
6455 Result += DefinedNonLazyCategories[i]->getNameAsString();
6456 Result += ",\n";
6457 }
6458 Result += "};\n";
6459 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006460}
6461
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006462void RewriteModernObjC::WriteImageInfo(std::string &Result) {
6463 if (LangOpts.MicrosoftExt)
6464 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
6465
6466 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
6467 // version 0, ObjCABI is 2
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006468 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006469}
6470
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006471/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
6472/// implementation.
6473void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
6474 std::string &Result) {
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006475 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006476 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
6477 // Find category declaration for this implementation.
Fariborz Jahanian61186122012-02-17 18:40:41 +00006478 ObjCCategoryDecl *CDecl=0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006479 for (CDecl = ClassDecl->getCategoryList(); CDecl;
6480 CDecl = CDecl->getNextClassCategory())
6481 if (CDecl->getIdentifier() == IDecl->getIdentifier())
6482 break;
6483
6484 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00006485 FullCategoryName += "_$_";
6486 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006487
6488 // Build _objc_method_list for class's instance methods if needed
6489 SmallVector<ObjCMethodDecl *, 32>
6490 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6491
6492 // If any of our property implementations have associated getters or
6493 // setters, produce metadata for them as well.
6494 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6495 PropEnd = IDecl->propimpl_end();
6496 Prop != PropEnd; ++Prop) {
6497 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6498 continue;
6499 if (!(*Prop)->getPropertyIvarDecl())
6500 continue;
6501 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
6502 if (!PD)
6503 continue;
6504 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
6505 InstanceMethods.push_back(Getter);
6506 if (PD->isReadOnly())
6507 continue;
6508 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
6509 InstanceMethods.push_back(Setter);
6510 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006511
Fariborz Jahanian61186122012-02-17 18:40:41 +00006512 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6513 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
6514 FullCategoryName, true);
6515
6516 SmallVector<ObjCMethodDecl *, 32>
6517 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6518
6519 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6520 "_OBJC_$_CATEGORY_CLASS_METHODS_",
6521 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006522
6523 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00006524 // Protocol's super protocol list
6525 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00006526 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
6527 E = CDecl->protocol_end();
6528
6529 I != E; ++I) {
Fariborz Jahanian61186122012-02-17 18:40:41 +00006530 RefedProtocols.push_back(*I);
6531 // Must write out all protocol definitions in current qualifier list,
6532 // and in their nested qualifiers before writing out current definition.
6533 RewriteObjCProtocolMetaData(*I, Result);
6534 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006535
Fariborz Jahanian61186122012-02-17 18:40:41 +00006536 Write_protocol_list_initializer(Context, Result,
6537 RefedProtocols,
6538 "_OBJC_CATEGORY_PROTOCOLS_$_",
6539 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006540
Fariborz Jahanian61186122012-02-17 18:40:41 +00006541 // Protocol's property metadata.
6542 std::vector<ObjCPropertyDecl *> ClassProperties;
6543 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6544 E = CDecl->prop_end(); I != E; ++I)
6545 ClassProperties.push_back(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006546
Fariborz Jahanian61186122012-02-17 18:40:41 +00006547 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
6548 /* Container */0,
6549 "_OBJC_$_PROP_LIST_",
6550 FullCategoryName);
6551
6552 Write_category_t(*this, Context, Result,
6553 CDecl->getNameAsString(),
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006554 ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006555 InstanceMethods,
6556 ClassMethods,
6557 RefedProtocols,
6558 ClassProperties);
6559
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006560 // Determine if this category is also "non-lazy".
6561 if (ImplementationIsNonLazy(IDecl))
6562 DefinedNonLazyCategories.push_back(CDecl);
6563
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006564}
6565
6566// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
6567/// class methods.
6568template<typename MethodIterator>
6569void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
6570 MethodIterator MethodEnd,
6571 bool IsInstanceMethod,
6572 StringRef prefix,
6573 StringRef ClassName,
6574 std::string &Result) {
6575 if (MethodBegin == MethodEnd) return;
6576
6577 if (!objc_impl_method) {
6578 /* struct _objc_method {
6579 SEL _cmd;
6580 char *method_types;
6581 void *_imp;
6582 }
6583 */
6584 Result += "\nstruct _objc_method {\n";
6585 Result += "\tSEL _cmd;\n";
6586 Result += "\tchar *method_types;\n";
6587 Result += "\tvoid *_imp;\n";
6588 Result += "};\n";
6589
6590 objc_impl_method = true;
6591 }
6592
6593 // Build _objc_method_list for class's methods if needed
6594
6595 /* struct {
6596 struct _objc_method_list *next_method;
6597 int method_count;
6598 struct _objc_method method_list[];
6599 }
6600 */
6601 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006602 Result += "\n";
6603 if (LangOpts.MicrosoftExt) {
6604 if (IsInstanceMethod)
6605 Result += "__declspec(allocate(\".inst_meth$B\")) ";
6606 else
6607 Result += "__declspec(allocate(\".cls_meth$B\")) ";
6608 }
6609 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006610 Result += "\tstruct _objc_method_list *next_method;\n";
6611 Result += "\tint method_count;\n";
6612 Result += "\tstruct _objc_method method_list[";
6613 Result += utostr(NumMethods);
6614 Result += "];\n} _OBJC_";
6615 Result += prefix;
6616 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
6617 Result += "_METHODS_";
6618 Result += ClassName;
6619 Result += " __attribute__ ((used, section (\"__OBJC, __";
6620 Result += IsInstanceMethod ? "inst" : "cls";
6621 Result += "_meth\")))= ";
6622 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
6623
6624 Result += "\t,{{(SEL)\"";
6625 Result += (*MethodBegin)->getSelector().getAsString().c_str();
6626 std::string MethodTypeString;
6627 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
6628 Result += "\", \"";
6629 Result += MethodTypeString;
6630 Result += "\", (void *)";
6631 Result += MethodInternalNames[*MethodBegin];
6632 Result += "}\n";
6633 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
6634 Result += "\t ,{(SEL)\"";
6635 Result += (*MethodBegin)->getSelector().getAsString().c_str();
6636 std::string MethodTypeString;
6637 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
6638 Result += "\", \"";
6639 Result += MethodTypeString;
6640 Result += "\", (void *)";
6641 Result += MethodInternalNames[*MethodBegin];
6642 Result += "}\n";
6643 }
6644 Result += "\t }\n};\n";
6645}
6646
6647Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
6648 SourceRange OldRange = IV->getSourceRange();
6649 Expr *BaseExpr = IV->getBase();
6650
6651 // Rewrite the base, but without actually doing replaces.
6652 {
6653 DisableReplaceStmtScope S(*this);
6654 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
6655 IV->setBase(BaseExpr);
6656 }
6657
6658 ObjCIvarDecl *D = IV->getDecl();
6659
6660 Expr *Replacement = IV;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006661
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006662 if (BaseExpr->getType()->isObjCObjectPointerType()) {
6663 const ObjCInterfaceType *iFaceDecl =
6664 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
6665 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
6666 // lookup which class implements the instance variable.
6667 ObjCInterfaceDecl *clsDeclared = 0;
6668 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
6669 clsDeclared);
6670 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
6671
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006672 // Build name of symbol holding ivar offset.
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006673 std::string IvarOffsetName;
6674 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
6675
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00006676 ReferencedIvars[clsDeclared].insert(D);
6677
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006678 // cast offset to "char *".
6679 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
6680 Context->getPointerType(Context->CharTy),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006681 CK_BitCast,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006682 BaseExpr);
6683 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
6684 SourceLocation(), &Context->Idents.get(IvarOffsetName),
6685 Context->UnsignedLongTy, 0, SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00006686 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
6687 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006688 SourceLocation());
6689 BinaryOperator *addExpr =
6690 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
6691 Context->getPointerType(Context->CharTy),
6692 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006693 // Don't forget the parens to enforce the proper binding.
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006694 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
6695 SourceLocation(),
6696 addExpr);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00006697 QualType IvarT = D->getType();
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00006698 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00006699 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006700
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006701 castExpr = NoTypeInfoCStyleCastExpr(Context,
6702 castT,
6703 CK_BitCast,
6704 PE);
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00006705 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006706 VK_LValue, OK_Ordinary,
6707 SourceLocation());
6708 PE = new (Context) ParenExpr(OldRange.getBegin(),
6709 OldRange.getEnd(),
6710 Exp);
6711
6712 Replacement = PE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006713 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006714
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006715 ReplaceStmtWithRange(IV, Replacement, OldRange);
6716 return Replacement;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006717}