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