blob: fdaf44dd3300a2eeb43c5db9ad990fb06f7c18f0 [file] [log] [blame]
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Rewrite/ASTConsumers.h"
15#include "clang/Rewrite/Rewriter.h"
16#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ParentMap.h"
19#include "clang/Basic/SourceManager.h"
20#include "clang/Basic/IdentifierTable.h"
21#include "clang/Basic/Diagnostic.h"
22#include "clang/Lex/Lexer.h"
23#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
25#include "llvm/ADT/StringExtras.h"
26#include "llvm/ADT/SmallPtrSet.h"
27#include "llvm/ADT/OwningPtr.h"
28#include "llvm/ADT/DenseSet.h"
29
30using namespace clang;
31using llvm::utostr;
32
33namespace {
34 class RewriteModernObjC : public ASTConsumer {
35 protected:
36
37 enum {
38 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
39 block, ... */
40 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
41 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
42 __block variable */
43 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
44 helpers */
45 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
46 support routines */
47 BLOCK_BYREF_CURRENT_MAX = 256
48 };
49
50 enum {
51 BLOCK_NEEDS_FREE = (1 << 24),
52 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
53 BLOCK_HAS_CXX_OBJ = (1 << 26),
54 BLOCK_IS_GC = (1 << 27),
55 BLOCK_IS_GLOBAL = (1 << 28),
56 BLOCK_HAS_DESCRIPTOR = (1 << 29)
57 };
58 static const int OBJC_ABI_VERSION = 7;
59
60 Rewriter Rewrite;
61 DiagnosticsEngine &Diags;
62 const LangOptions &LangOpts;
63 ASTContext *Context;
64 SourceManager *SM;
65 TranslationUnitDecl *TUDecl;
66 FileID MainFileID;
67 const char *MainFileStart, *MainFileEnd;
68 Stmt *CurrentBody;
69 ParentMap *PropParentMap; // created lazily.
70 std::string InFileName;
71 raw_ostream* OutFile;
72 std::string Preamble;
73
74 TypeDecl *ProtocolTypeDecl;
75 VarDecl *GlobalVarDecl;
76 unsigned RewriteFailedDiag;
77 // ObjC string constant support.
78 unsigned NumObjCStringLiterals;
79 VarDecl *ConstantStringClassReference;
80 RecordDecl *NSStringRecord;
81
82 // ObjC foreach break/continue generation support.
83 int BcLabelCount;
84
85 unsigned TryFinallyContainsReturnDiag;
86 // Needed for super.
87 ObjCMethodDecl *CurMethodDef;
88 RecordDecl *SuperStructDecl;
89 RecordDecl *ConstantStringDecl;
90
91 FunctionDecl *MsgSendFunctionDecl;
92 FunctionDecl *MsgSendSuperFunctionDecl;
93 FunctionDecl *MsgSendStretFunctionDecl;
94 FunctionDecl *MsgSendSuperStretFunctionDecl;
95 FunctionDecl *MsgSendFpretFunctionDecl;
96 FunctionDecl *GetClassFunctionDecl;
97 FunctionDecl *GetMetaClassFunctionDecl;
98 FunctionDecl *GetSuperClassFunctionDecl;
99 FunctionDecl *SelGetUidFunctionDecl;
100 FunctionDecl *CFStringFunctionDecl;
101 FunctionDecl *SuperContructorFunctionDecl;
102 FunctionDecl *CurFunctionDef;
103 FunctionDecl *CurFunctionDeclToDeclareForBlock;
104
105 /* Misc. containers needed for meta-data rewrite. */
106 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
107 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
108 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
109 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000110 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000111 llvm::SmallPtrSet<TagDecl*, 8> TagsDefinedInIvarDecls;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000112 SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000113 SmallVector<Stmt *, 32> Stmts;
114 SmallVector<int, 8> ObjCBcLabelNo;
115 // Remember all the @protocol(<expr>) expressions.
116 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
117
118 llvm::DenseSet<uint64_t> CopyDestroyCache;
119
120 // Block expressions.
121 SmallVector<BlockExpr *, 32> Blocks;
122 SmallVector<int, 32> InnerDeclRefsCount;
123 SmallVector<BlockDeclRefExpr *, 32> InnerDeclRefs;
124
125 SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
126
127 // Block related declarations.
128 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
129 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
130 SmallVector<ValueDecl *, 8> BlockByRefDecls;
131 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
132 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
133 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
134 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
135
136 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000137 llvm::DenseMap<ObjCInterfaceDecl *,
138 llvm::SmallPtrSet<ObjCIvarDecl *, 8> > ReferencedIvars;
139
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000140 // This maps an original source AST to it's rewritten form. This allows
141 // us to avoid rewriting the same node twice (which is very uncommon).
142 // This is needed to support some of the exotic property rewriting.
143 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
144
145 // Needed for header files being rewritten
146 bool IsHeader;
147 bool SilenceRewriteMacroWarning;
148 bool objc_impl_method;
149
150 bool DisableReplaceStmt;
151 class DisableReplaceStmtScope {
152 RewriteModernObjC &R;
153 bool SavedValue;
154
155 public:
156 DisableReplaceStmtScope(RewriteModernObjC &R)
157 : R(R), SavedValue(R.DisableReplaceStmt) {
158 R.DisableReplaceStmt = true;
159 }
160 ~DisableReplaceStmtScope() {
161 R.DisableReplaceStmt = SavedValue;
162 }
163 };
164 void InitializeCommon(ASTContext &context);
165
166 public:
Fariborz Jahanian90af4e22012-02-14 17:19:02 +0000167 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000168 // Top Level Driver code.
169 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
170 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
171 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
172 if (!Class->isThisDeclarationADefinition()) {
173 RewriteForwardClassDecl(D);
174 break;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000175 } else {
176 // Keep track of all interface declarations seen.
Fariborz Jahanianf3295272012-02-24 21:42:38 +0000177 ObjCInterfacesSeen.push_back(Class);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000178 break;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000179 }
180 }
181
182 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
183 if (!Proto->isThisDeclarationADefinition()) {
184 RewriteForwardProtocolDecl(D);
185 break;
186 }
187 }
188
189 HandleTopLevelSingleDecl(*I);
190 }
191 return true;
192 }
193 void HandleTopLevelSingleDecl(Decl *D);
194 void HandleDeclInMainFile(Decl *D);
195 RewriteModernObjC(std::string inFile, raw_ostream *OS,
196 DiagnosticsEngine &D, const LangOptions &LOpts,
197 bool silenceMacroWarn);
198
199 ~RewriteModernObjC() {}
200
201 virtual void HandleTranslationUnit(ASTContext &C);
202
203 void ReplaceStmt(Stmt *Old, Stmt *New) {
204 Stmt *ReplacingStmt = ReplacedNodes[Old];
205
206 if (ReplacingStmt)
207 return; // We can't rewrite the same node twice.
208
209 if (DisableReplaceStmt)
210 return;
211
212 // If replacement succeeded or warning disabled return with no warning.
213 if (!Rewrite.ReplaceStmt(Old, New)) {
214 ReplacedNodes[Old] = New;
215 return;
216 }
217 if (SilenceRewriteMacroWarning)
218 return;
219 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
220 << Old->getSourceRange();
221 }
222
223 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
224 if (DisableReplaceStmt)
225 return;
226
227 // Measure the old text.
228 int Size = Rewrite.getRangeSize(SrcRange);
229 if (Size == -1) {
230 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
231 << Old->getSourceRange();
232 return;
233 }
234 // Get the new text.
235 std::string SStr;
236 llvm::raw_string_ostream S(SStr);
237 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
238 const std::string &Str = S.str();
239
240 // If replacement succeeded or warning disabled return with no warning.
241 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
242 ReplacedNodes[Old] = New;
243 return;
244 }
245 if (SilenceRewriteMacroWarning)
246 return;
247 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
248 << Old->getSourceRange();
249 }
250
251 void InsertText(SourceLocation Loc, StringRef Str,
252 bool InsertAfter = true) {
253 // If insertion succeeded or warning disabled return with no warning.
254 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
255 SilenceRewriteMacroWarning)
256 return;
257
258 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
259 }
260
261 void ReplaceText(SourceLocation Start, unsigned OrigLength,
262 StringRef Str) {
263 // If removal succeeded or warning disabled return with no warning.
264 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
265 SilenceRewriteMacroWarning)
266 return;
267
268 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
269 }
270
271 // Syntactic Rewriting.
272 void RewriteRecordBody(RecordDecl *RD);
273 void RewriteInclude();
274 void RewriteForwardClassDecl(DeclGroupRef D);
275 void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG);
276 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
277 const std::string &typedefString);
278 void RewriteImplementations();
279 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
280 ObjCImplementationDecl *IMD,
281 ObjCCategoryImplDecl *CID);
282 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
283 void RewriteImplementationDecl(Decl *Dcl);
284 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
285 ObjCMethodDecl *MDecl, std::string &ResultStr);
286 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
287 const FunctionType *&FPRetType);
288 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
289 ValueDecl *VD, bool def=false);
290 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
291 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
292 void RewriteForwardProtocolDecl(DeclGroupRef D);
293 void RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG);
294 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
295 void RewriteProperty(ObjCPropertyDecl *prop);
296 void RewriteFunctionDecl(FunctionDecl *FD);
297 void RewriteBlockPointerType(std::string& Str, QualType Type);
298 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
299 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
300 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
301 void RewriteTypeOfDecl(VarDecl *VD);
302 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
303
304 // Expression Rewriting.
305 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
306 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
307 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
308 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
309 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
310 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
311 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
312 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
313 void RewriteTryReturnStmts(Stmt *S);
314 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
315 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
316 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
317 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
318 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
319 SourceLocation OrigEnd);
320 Stmt *RewriteBreakStmt(BreakStmt *S);
321 Stmt *RewriteContinueStmt(ContinueStmt *S);
322 void RewriteCastExpr(CStyleCastExpr *CE);
323
324 // Block rewriting.
325 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
326
327 // Block specific rewrite rules.
328 void RewriteBlockPointerDecl(NamedDecl *VD);
329 void RewriteByRefVar(VarDecl *VD);
330 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
331 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
332 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
333
334 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
335 std::string &Result);
336
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000337 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
338
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000339 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
340 std::string &Result);
341
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000342 virtual void Initialize(ASTContext &context);
343
344 // Misc. AST transformation routines. Somtimes they end up calling
345 // rewriting routines on the new ASTs.
346 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
347 Expr **args, unsigned nargs,
348 SourceLocation StartLoc=SourceLocation(),
349 SourceLocation EndLoc=SourceLocation());
350
351 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
352 SourceLocation StartLoc=SourceLocation(),
353 SourceLocation EndLoc=SourceLocation());
354
355 void SynthCountByEnumWithState(std::string &buf);
356 void SynthMsgSendFunctionDecl();
357 void SynthMsgSendSuperFunctionDecl();
358 void SynthMsgSendStretFunctionDecl();
359 void SynthMsgSendFpretFunctionDecl();
360 void SynthMsgSendSuperStretFunctionDecl();
361 void SynthGetClassFunctionDecl();
362 void SynthGetMetaClassFunctionDecl();
363 void SynthGetSuperClassFunctionDecl();
364 void SynthSelGetUidFunctionDecl();
365 void SynthSuperContructorFunctionDecl();
366
367 // Rewriting metadata
368 template<typename MethodIterator>
369 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
370 MethodIterator MethodEnd,
371 bool IsInstanceMethod,
372 StringRef prefix,
373 StringRef ClassName,
374 std::string &Result);
Fariborz Jahanianda9624a2012-02-08 19:53:58 +0000375 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
376 std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000377 virtual void RewriteObjCProtocolListMetaData(
378 const ObjCList<ObjCProtocolDecl> &Prots,
379 StringRef prefix, StringRef ClassName, std::string &Result);
380 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
381 std::string &Result);
382 virtual void RewriteMetaDataIntoBuffer(std::string &Result);
383 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
384 std::string &Result);
385
386 // Rewriting ivar
387 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
388 std::string &Result);
389 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
390
391
392 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
393 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
394 StringRef funcName, std::string Tag);
395 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
396 StringRef funcName, std::string Tag);
397 std::string SynthesizeBlockImpl(BlockExpr *CE,
398 std::string Tag, std::string Desc);
399 std::string SynthesizeBlockDescriptor(std::string DescTag,
400 std::string ImplTag,
401 int i, StringRef funcName,
402 unsigned hasCopy);
403 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
404 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
405 StringRef FunName);
406 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
407 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
408 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs);
409
410 // Misc. helper routines.
411 QualType getProtocolType();
412 void WarnAboutReturnGotoStmts(Stmt *S);
413 void HasReturnStmts(Stmt *S, bool &hasReturns);
414 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
415 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
416 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
417
418 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
419 void CollectBlockDeclRefInfo(BlockExpr *Exp);
420 void GetBlockDeclRefExprs(Stmt *S);
421 void GetInnerBlockDeclRefExprs(Stmt *S,
422 SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
423 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
424
425 // We avoid calling Type::isBlockPointerType(), since it operates on the
426 // canonical type. We only care if the top-level type is a closure pointer.
427 bool isTopLevelBlockPointerType(QualType T) {
428 return isa<BlockPointerType>(T);
429 }
430
431 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
432 /// to a function pointer type and upon success, returns true; false
433 /// otherwise.
434 bool convertBlockPointerToFunctionPointer(QualType &T) {
435 if (isTopLevelBlockPointerType(T)) {
436 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
437 T = Context->getPointerType(BPT->getPointeeType());
438 return true;
439 }
440 return false;
441 }
442
Fariborz Jahanian164d6f82012-02-13 18:57:49 +0000443 bool convertObjCTypeToCStyleType(QualType &T);
444
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000445 bool needToScanForQualifiers(QualType T);
446 QualType getSuperStructType();
447 QualType getConstantStringStructType();
448 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
449 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
450
451 void convertToUnqualifiedObjCType(QualType &T) {
452 if (T->isObjCQualifiedIdType())
453 T = Context->getObjCIdType();
454 else if (T->isObjCQualifiedClassType())
455 T = Context->getObjCClassType();
456 else if (T->isObjCObjectPointerType() &&
457 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
458 if (const ObjCObjectPointerType * OBJPT =
459 T->getAsObjCInterfacePointerType()) {
460 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
461 T = QualType(IFaceT, 0);
462 T = Context->getPointerType(T);
463 }
464 }
465 }
466
467 // FIXME: This predicate seems like it would be useful to add to ASTContext.
468 bool isObjCType(QualType T) {
469 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
470 return false;
471
472 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
473
474 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
475 OCT == Context->getCanonicalType(Context->getObjCClassType()))
476 return true;
477
478 if (const PointerType *PT = OCT->getAs<PointerType>()) {
479 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
480 PT->getPointeeType()->isObjCQualifiedIdType())
481 return true;
482 }
483 return false;
484 }
485 bool PointerTypeTakesAnyBlockArguments(QualType QT);
486 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
487 void GetExtentOfArgList(const char *Name, const char *&LParen,
488 const char *&RParen);
489
490 void QuoteDoublequotes(std::string &From, std::string &To) {
491 for (unsigned i = 0; i < From.length(); i++) {
492 if (From[i] == '"')
493 To += "\\\"";
494 else
495 To += From[i];
496 }
497 }
498
499 QualType getSimpleFunctionType(QualType result,
500 const QualType *args,
501 unsigned numArgs,
502 bool variadic = false) {
503 if (result == Context->getObjCInstanceType())
504 result = Context->getObjCIdType();
505 FunctionProtoType::ExtProtoInfo fpi;
506 fpi.Variadic = variadic;
507 return Context->getFunctionType(result, args, numArgs, fpi);
508 }
509
510 // Helper function: create a CStyleCastExpr with trivial type source info.
511 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
512 CastKind Kind, Expr *E) {
513 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
514 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
515 SourceLocation(), SourceLocation());
516 }
517 };
518
519}
520
521void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
522 NamedDecl *D) {
523 if (const FunctionProtoType *fproto
524 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
525 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
526 E = fproto->arg_type_end(); I && (I != E); ++I)
527 if (isTopLevelBlockPointerType(*I)) {
528 // All the args are checked/rewritten. Don't call twice!
529 RewriteBlockPointerDecl(D);
530 break;
531 }
532 }
533}
534
535void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
536 const PointerType *PT = funcType->getAs<PointerType>();
537 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
538 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
539}
540
541static bool IsHeaderFile(const std::string &Filename) {
542 std::string::size_type DotPos = Filename.rfind('.');
543
544 if (DotPos == std::string::npos) {
545 // no file extension
546 return false;
547 }
548
549 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
550 // C header: .h
551 // C++ header: .hh or .H;
552 return Ext == "h" || Ext == "hh" || Ext == "H";
553}
554
555RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
556 DiagnosticsEngine &D, const LangOptions &LOpts,
557 bool silenceMacroWarn)
558 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
559 SilenceRewriteMacroWarning(silenceMacroWarn) {
560 IsHeader = IsHeaderFile(inFile);
561 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
562 "rewriting sub-expression within a macro (may not be correct)");
563 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
564 DiagnosticsEngine::Warning,
565 "rewriter doesn't support user-specified control flow semantics "
566 "for @try/@finally (code may not execute properly)");
567}
568
569ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
570 raw_ostream* OS,
571 DiagnosticsEngine &Diags,
572 const LangOptions &LOpts,
573 bool SilenceRewriteMacroWarning) {
574 return new RewriteModernObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
575}
576
577void RewriteModernObjC::InitializeCommon(ASTContext &context) {
578 Context = &context;
579 SM = &Context->getSourceManager();
580 TUDecl = Context->getTranslationUnitDecl();
581 MsgSendFunctionDecl = 0;
582 MsgSendSuperFunctionDecl = 0;
583 MsgSendStretFunctionDecl = 0;
584 MsgSendSuperStretFunctionDecl = 0;
585 MsgSendFpretFunctionDecl = 0;
586 GetClassFunctionDecl = 0;
587 GetMetaClassFunctionDecl = 0;
588 GetSuperClassFunctionDecl = 0;
589 SelGetUidFunctionDecl = 0;
590 CFStringFunctionDecl = 0;
591 ConstantStringClassReference = 0;
592 NSStringRecord = 0;
593 CurMethodDef = 0;
594 CurFunctionDef = 0;
595 CurFunctionDeclToDeclareForBlock = 0;
596 GlobalVarDecl = 0;
597 SuperStructDecl = 0;
598 ProtocolTypeDecl = 0;
599 ConstantStringDecl = 0;
600 BcLabelCount = 0;
601 SuperContructorFunctionDecl = 0;
602 NumObjCStringLiterals = 0;
603 PropParentMap = 0;
604 CurrentBody = 0;
605 DisableReplaceStmt = false;
606 objc_impl_method = false;
607
608 // Get the ID and start/end of the main file.
609 MainFileID = SM->getMainFileID();
610 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
611 MainFileStart = MainBuf->getBufferStart();
612 MainFileEnd = MainBuf->getBufferEnd();
613
614 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
615}
616
617//===----------------------------------------------------------------------===//
618// Top Level Driver Code
619//===----------------------------------------------------------------------===//
620
621void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
622 if (Diags.hasErrorOccurred())
623 return;
624
625 // Two cases: either the decl could be in the main file, or it could be in a
626 // #included file. If the former, rewrite it now. If the later, check to see
627 // if we rewrote the #include/#import.
628 SourceLocation Loc = D->getLocation();
629 Loc = SM->getExpansionLoc(Loc);
630
631 // If this is for a builtin, ignore it.
632 if (Loc.isInvalid()) return;
633
634 // Look for built-in declarations that we need to refer during the rewrite.
635 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
636 RewriteFunctionDecl(FD);
637 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
638 // declared in <Foundation/NSString.h>
639 if (FVD->getName() == "_NSConstantStringClassReference") {
640 ConstantStringClassReference = FVD;
641 return;
642 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000643 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
644 RewriteCategoryDecl(CD);
645 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
646 if (PD->isThisDeclarationADefinition())
647 RewriteProtocolDecl(PD);
648 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
649 // Recurse into linkage specifications
650 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
651 DIEnd = LSD->decls_end();
652 DI != DIEnd; ) {
653 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
654 if (!IFace->isThisDeclarationADefinition()) {
655 SmallVector<Decl *, 8> DG;
656 SourceLocation StartLoc = IFace->getLocStart();
657 do {
658 if (isa<ObjCInterfaceDecl>(*DI) &&
659 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
660 StartLoc == (*DI)->getLocStart())
661 DG.push_back(*DI);
662 else
663 break;
664
665 ++DI;
666 } while (DI != DIEnd);
667 RewriteForwardClassDecl(DG);
668 continue;
669 }
670 }
671
672 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
673 if (!Proto->isThisDeclarationADefinition()) {
674 SmallVector<Decl *, 8> DG;
675 SourceLocation StartLoc = Proto->getLocStart();
676 do {
677 if (isa<ObjCProtocolDecl>(*DI) &&
678 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
679 StartLoc == (*DI)->getLocStart())
680 DG.push_back(*DI);
681 else
682 break;
683
684 ++DI;
685 } while (DI != DIEnd);
686 RewriteForwardProtocolDecl(DG);
687 continue;
688 }
689 }
690
691 HandleTopLevelSingleDecl(*DI);
692 ++DI;
693 }
694 }
695 // If we have a decl in the main file, see if we should rewrite it.
696 if (SM->isFromMainFile(Loc))
697 return HandleDeclInMainFile(D);
698}
699
700//===----------------------------------------------------------------------===//
701// Syntactic (non-AST) Rewriting Code
702//===----------------------------------------------------------------------===//
703
704void RewriteModernObjC::RewriteInclude() {
705 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
706 StringRef MainBuf = SM->getBufferData(MainFileID);
707 const char *MainBufStart = MainBuf.begin();
708 const char *MainBufEnd = MainBuf.end();
709 size_t ImportLen = strlen("import");
710
711 // Loop over the whole file, looking for includes.
712 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
713 if (*BufPtr == '#') {
714 if (++BufPtr == MainBufEnd)
715 return;
716 while (*BufPtr == ' ' || *BufPtr == '\t')
717 if (++BufPtr == MainBufEnd)
718 return;
719 if (!strncmp(BufPtr, "import", ImportLen)) {
720 // replace import with include
721 SourceLocation ImportLoc =
722 LocStart.getLocWithOffset(BufPtr-MainBufStart);
723 ReplaceText(ImportLoc, ImportLen, "include");
724 BufPtr += ImportLen;
725 }
726 }
727 }
728}
729
730static std::string getIvarAccessString(ObjCIvarDecl *OID) {
731 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
732 std::string S;
733 S = "((struct ";
734 S += ClassDecl->getIdentifier()->getName();
735 S += "_IMPL *)self)->";
736 S += OID->getName();
737 return S;
738}
739
740void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
741 ObjCImplementationDecl *IMD,
742 ObjCCategoryImplDecl *CID) {
743 static bool objcGetPropertyDefined = false;
744 static bool objcSetPropertyDefined = false;
745 SourceLocation startLoc = PID->getLocStart();
746 InsertText(startLoc, "// ");
747 const char *startBuf = SM->getCharacterData(startLoc);
748 assert((*startBuf == '@') && "bogus @synthesize location");
749 const char *semiBuf = strchr(startBuf, ';');
750 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
751 SourceLocation onePastSemiLoc =
752 startLoc.getLocWithOffset(semiBuf-startBuf+1);
753
754 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
755 return; // FIXME: is this correct?
756
757 // Generate the 'getter' function.
758 ObjCPropertyDecl *PD = PID->getPropertyDecl();
759 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
760
761 if (!OID)
762 return;
763 unsigned Attributes = PD->getPropertyAttributes();
764 if (!PD->getGetterMethodDecl()->isDefined()) {
765 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
766 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
767 ObjCPropertyDecl::OBJC_PR_copy));
768 std::string Getr;
769 if (GenGetProperty && !objcGetPropertyDefined) {
770 objcGetPropertyDefined = true;
771 // FIXME. Is this attribute correct in all cases?
772 Getr = "\nextern \"C\" __declspec(dllimport) "
773 "id objc_getProperty(id, SEL, long, bool);\n";
774 }
775 RewriteObjCMethodDecl(OID->getContainingInterface(),
776 PD->getGetterMethodDecl(), Getr);
777 Getr += "{ ";
778 // Synthesize an explicit cast to gain access to the ivar.
779 // See objc-act.c:objc_synthesize_new_getter() for details.
780 if (GenGetProperty) {
781 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
782 Getr += "typedef ";
783 const FunctionType *FPRetType = 0;
784 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
785 FPRetType);
786 Getr += " _TYPE";
787 if (FPRetType) {
788 Getr += ")"; // close the precedence "scope" for "*".
789
790 // Now, emit the argument types (if any).
791 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
792 Getr += "(";
793 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
794 if (i) Getr += ", ";
795 std::string ParamStr = FT->getArgType(i).getAsString(
796 Context->getPrintingPolicy());
797 Getr += ParamStr;
798 }
799 if (FT->isVariadic()) {
800 if (FT->getNumArgs()) Getr += ", ";
801 Getr += "...";
802 }
803 Getr += ")";
804 } else
805 Getr += "()";
806 }
807 Getr += ";\n";
808 Getr += "return (_TYPE)";
809 Getr += "objc_getProperty(self, _cmd, ";
810 RewriteIvarOffsetComputation(OID, Getr);
811 Getr += ", 1)";
812 }
813 else
814 Getr += "return " + getIvarAccessString(OID);
815 Getr += "; }";
816 InsertText(onePastSemiLoc, Getr);
817 }
818
819 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
820 return;
821
822 // Generate the 'setter' function.
823 std::string Setr;
824 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
825 ObjCPropertyDecl::OBJC_PR_copy);
826 if (GenSetProperty && !objcSetPropertyDefined) {
827 objcSetPropertyDefined = true;
828 // FIXME. Is this attribute correct in all cases?
829 Setr = "\nextern \"C\" __declspec(dllimport) "
830 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
831 }
832
833 RewriteObjCMethodDecl(OID->getContainingInterface(),
834 PD->getSetterMethodDecl(), Setr);
835 Setr += "{ ";
836 // Synthesize an explicit cast to initialize the ivar.
837 // See objc-act.c:objc_synthesize_new_setter() for details.
838 if (GenSetProperty) {
839 Setr += "objc_setProperty (self, _cmd, ";
840 RewriteIvarOffsetComputation(OID, Setr);
841 Setr += ", (id)";
842 Setr += PD->getName();
843 Setr += ", ";
844 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
845 Setr += "0, ";
846 else
847 Setr += "1, ";
848 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
849 Setr += "1)";
850 else
851 Setr += "0)";
852 }
853 else {
854 Setr += getIvarAccessString(OID) + " = ";
855 Setr += PD->getName();
856 }
857 Setr += "; }";
858 InsertText(onePastSemiLoc, Setr);
859}
860
861static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
862 std::string &typedefString) {
863 typedefString += "#ifndef _REWRITER_typedef_";
864 typedefString += ForwardDecl->getNameAsString();
865 typedefString += "\n";
866 typedefString += "#define _REWRITER_typedef_";
867 typedefString += ForwardDecl->getNameAsString();
868 typedefString += "\n";
869 typedefString += "typedef struct objc_object ";
870 typedefString += ForwardDecl->getNameAsString();
871 typedefString += ";\n#endif\n";
872}
873
874void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
875 const std::string &typedefString) {
876 SourceLocation startLoc = ClassDecl->getLocStart();
877 const char *startBuf = SM->getCharacterData(startLoc);
878 const char *semiPtr = strchr(startBuf, ';');
879 // Replace the @class with typedefs corresponding to the classes.
880 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
881}
882
883void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
884 std::string typedefString;
885 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
886 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
887 if (I == D.begin()) {
888 // Translate to typedef's that forward reference structs with the same name
889 // as the class. As a convenience, we include the original declaration
890 // as a comment.
891 typedefString += "// @class ";
892 typedefString += ForwardDecl->getNameAsString();
893 typedefString += ";\n";
894 }
895 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
896 }
897 DeclGroupRef::iterator I = D.begin();
898 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
899}
900
901void RewriteModernObjC::RewriteForwardClassDecl(
902 const llvm::SmallVector<Decl*, 8> &D) {
903 std::string typedefString;
904 for (unsigned i = 0; i < D.size(); i++) {
905 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
906 if (i == 0) {
907 typedefString += "// @class ";
908 typedefString += ForwardDecl->getNameAsString();
909 typedefString += ";\n";
910 }
911 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
912 }
913 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
914}
915
916void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
917 // When method is a synthesized one, such as a getter/setter there is
918 // nothing to rewrite.
919 if (Method->isImplicit())
920 return;
921 SourceLocation LocStart = Method->getLocStart();
922 SourceLocation LocEnd = Method->getLocEnd();
923
924 if (SM->getExpansionLineNumber(LocEnd) >
925 SM->getExpansionLineNumber(LocStart)) {
926 InsertText(LocStart, "#if 0\n");
927 ReplaceText(LocEnd, 1, ";\n#endif\n");
928 } else {
929 InsertText(LocStart, "// ");
930 }
931}
932
933void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
934 SourceLocation Loc = prop->getAtLoc();
935
936 ReplaceText(Loc, 0, "// ");
937 // FIXME: handle properties that are declared across multiple lines.
938}
939
940void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
941 SourceLocation LocStart = CatDecl->getLocStart();
942
943 // FIXME: handle category headers that are declared across multiple lines.
944 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianaf300292012-02-20 20:09:20 +0000945 if (CatDecl->getIvarLBraceLoc().isValid())
946 InsertText(CatDecl->getIvarLBraceLoc(), "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +0000947 for (ObjCCategoryDecl::ivar_iterator
948 I = CatDecl->ivar_begin(), E = CatDecl->ivar_end(); I != E; ++I) {
949 ObjCIvarDecl *Ivar = (*I);
950 SourceLocation LocStart = Ivar->getLocStart();
951 ReplaceText(LocStart, 0, "// ");
952 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +0000953 if (CatDecl->getIvarRBraceLoc().isValid())
954 InsertText(CatDecl->getIvarRBraceLoc(), "// ");
955
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000956 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
957 E = CatDecl->prop_end(); I != E; ++I)
958 RewriteProperty(*I);
959
960 for (ObjCCategoryDecl::instmeth_iterator
961 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
962 I != E; ++I)
963 RewriteMethodDeclaration(*I);
964 for (ObjCCategoryDecl::classmeth_iterator
965 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
966 I != E; ++I)
967 RewriteMethodDeclaration(*I);
968
969 // Lastly, comment out the @end.
970 ReplaceText(CatDecl->getAtEndRange().getBegin(),
971 strlen("@end"), "/* @end */");
972}
973
974void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
975 SourceLocation LocStart = PDecl->getLocStart();
976 assert(PDecl->isThisDeclarationADefinition());
977
978 // FIXME: handle protocol headers that are declared across multiple lines.
979 ReplaceText(LocStart, 0, "// ");
980
981 for (ObjCProtocolDecl::instmeth_iterator
982 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
983 I != E; ++I)
984 RewriteMethodDeclaration(*I);
985 for (ObjCProtocolDecl::classmeth_iterator
986 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
987 I != E; ++I)
988 RewriteMethodDeclaration(*I);
989
990 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
991 E = PDecl->prop_end(); I != E; ++I)
992 RewriteProperty(*I);
993
994 // Lastly, comment out the @end.
995 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
996 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
997
998 // Must comment out @optional/@required
999 const char *startBuf = SM->getCharacterData(LocStart);
1000 const char *endBuf = SM->getCharacterData(LocEnd);
1001 for (const char *p = startBuf; p < endBuf; p++) {
1002 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1003 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1004 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1005
1006 }
1007 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1008 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1009 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1010
1011 }
1012 }
1013}
1014
1015void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1016 SourceLocation LocStart = (*D.begin())->getLocStart();
1017 if (LocStart.isInvalid())
1018 llvm_unreachable("Invalid SourceLocation");
1019 // FIXME: handle forward protocol that are declared across multiple lines.
1020 ReplaceText(LocStart, 0, "// ");
1021}
1022
1023void
1024RewriteModernObjC::RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG) {
1025 SourceLocation LocStart = DG[0]->getLocStart();
1026 if (LocStart.isInvalid())
1027 llvm_unreachable("Invalid SourceLocation");
1028 // FIXME: handle forward protocol that are declared across multiple lines.
1029 ReplaceText(LocStart, 0, "// ");
1030}
1031
1032void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1033 const FunctionType *&FPRetType) {
1034 if (T->isObjCQualifiedIdType())
1035 ResultStr += "id";
1036 else if (T->isFunctionPointerType() ||
1037 T->isBlockPointerType()) {
1038 // needs special handling, since pointer-to-functions have special
1039 // syntax (where a decaration models use).
1040 QualType retType = T;
1041 QualType PointeeTy;
1042 if (const PointerType* PT = retType->getAs<PointerType>())
1043 PointeeTy = PT->getPointeeType();
1044 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1045 PointeeTy = BPT->getPointeeType();
1046 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1047 ResultStr += FPRetType->getResultType().getAsString(
1048 Context->getPrintingPolicy());
1049 ResultStr += "(*";
1050 }
1051 } else
1052 ResultStr += T.getAsString(Context->getPrintingPolicy());
1053}
1054
1055void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1056 ObjCMethodDecl *OMD,
1057 std::string &ResultStr) {
1058 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1059 const FunctionType *FPRetType = 0;
1060 ResultStr += "\nstatic ";
1061 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1062 ResultStr += " ";
1063
1064 // Unique method name
1065 std::string NameStr;
1066
1067 if (OMD->isInstanceMethod())
1068 NameStr += "_I_";
1069 else
1070 NameStr += "_C_";
1071
1072 NameStr += IDecl->getNameAsString();
1073 NameStr += "_";
1074
1075 if (ObjCCategoryImplDecl *CID =
1076 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1077 NameStr += CID->getNameAsString();
1078 NameStr += "_";
1079 }
1080 // Append selector names, replacing ':' with '_'
1081 {
1082 std::string selString = OMD->getSelector().getAsString();
1083 int len = selString.size();
1084 for (int i = 0; i < len; i++)
1085 if (selString[i] == ':')
1086 selString[i] = '_';
1087 NameStr += selString;
1088 }
1089 // Remember this name for metadata emission
1090 MethodInternalNames[OMD] = NameStr;
1091 ResultStr += NameStr;
1092
1093 // Rewrite arguments
1094 ResultStr += "(";
1095
1096 // invisible arguments
1097 if (OMD->isInstanceMethod()) {
1098 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1099 selfTy = Context->getPointerType(selfTy);
1100 if (!LangOpts.MicrosoftExt) {
1101 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1102 ResultStr += "struct ";
1103 }
1104 // When rewriting for Microsoft, explicitly omit the structure name.
1105 ResultStr += IDecl->getNameAsString();
1106 ResultStr += " *";
1107 }
1108 else
1109 ResultStr += Context->getObjCClassType().getAsString(
1110 Context->getPrintingPolicy());
1111
1112 ResultStr += " self, ";
1113 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1114 ResultStr += " _cmd";
1115
1116 // Method arguments.
1117 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1118 E = OMD->param_end(); PI != E; ++PI) {
1119 ParmVarDecl *PDecl = *PI;
1120 ResultStr += ", ";
1121 if (PDecl->getType()->isObjCQualifiedIdType()) {
1122 ResultStr += "id ";
1123 ResultStr += PDecl->getNameAsString();
1124 } else {
1125 std::string Name = PDecl->getNameAsString();
1126 QualType QT = PDecl->getType();
1127 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1128 if (convertBlockPointerToFunctionPointer(QT))
1129 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
1130 else
1131 PDecl->getType().getAsStringInternal(Name, Context->getPrintingPolicy());
1132 ResultStr += Name;
1133 }
1134 }
1135 if (OMD->isVariadic())
1136 ResultStr += ", ...";
1137 ResultStr += ") ";
1138
1139 if (FPRetType) {
1140 ResultStr += ")"; // close the precedence "scope" for "*".
1141
1142 // Now, emit the argument types (if any).
1143 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1144 ResultStr += "(";
1145 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1146 if (i) ResultStr += ", ";
1147 std::string ParamStr = FT->getArgType(i).getAsString(
1148 Context->getPrintingPolicy());
1149 ResultStr += ParamStr;
1150 }
1151 if (FT->isVariadic()) {
1152 if (FT->getNumArgs()) ResultStr += ", ";
1153 ResultStr += "...";
1154 }
1155 ResultStr += ")";
1156 } else {
1157 ResultStr += "()";
1158 }
1159 }
1160}
1161void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1162 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1163 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1164
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001165 if (IMD) {
1166 InsertText(IMD->getLocStart(), "// ");
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001167 if (IMD->getIvarLBraceLoc().isValid())
1168 InsertText(IMD->getIvarLBraceLoc(), "// ");
1169 for (ObjCImplementationDecl::ivar_iterator
1170 I = IMD->ivar_begin(), E = IMD->ivar_end(); I != E; ++I) {
1171 ObjCIvarDecl *Ivar = (*I);
1172 SourceLocation LocStart = Ivar->getLocStart();
1173 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001174 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001175 if (IMD->getIvarRBraceLoc().isValid())
1176 InsertText(IMD->getIvarRBraceLoc(), "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001177 }
1178 else
1179 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001180
1181 for (ObjCCategoryImplDecl::instmeth_iterator
1182 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1183 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1184 I != E; ++I) {
1185 std::string ResultStr;
1186 ObjCMethodDecl *OMD = *I;
1187 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1188 SourceLocation LocStart = OMD->getLocStart();
1189 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1190
1191 const char *startBuf = SM->getCharacterData(LocStart);
1192 const char *endBuf = SM->getCharacterData(LocEnd);
1193 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1194 }
1195
1196 for (ObjCCategoryImplDecl::classmeth_iterator
1197 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1198 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1199 I != E; ++I) {
1200 std::string ResultStr;
1201 ObjCMethodDecl *OMD = *I;
1202 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1203 SourceLocation LocStart = OMD->getLocStart();
1204 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1205
1206 const char *startBuf = SM->getCharacterData(LocStart);
1207 const char *endBuf = SM->getCharacterData(LocEnd);
1208 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1209 }
1210 for (ObjCCategoryImplDecl::propimpl_iterator
1211 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1212 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1213 I != E; ++I) {
1214 RewritePropertyImplDecl(*I, IMD, CID);
1215 }
1216
1217 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1218}
1219
1220void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00001221 // Do not synthesize more than once.
1222 if (ObjCSynthesizedStructs.count(ClassDecl))
1223 return;
1224 // Make sure super class's are written before current class is written.
1225 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1226 while (SuperClass) {
1227 RewriteInterfaceDecl(SuperClass);
1228 SuperClass = SuperClass->getSuperClass();
1229 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001230 std::string ResultStr;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001231 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001232 // we haven't seen a forward decl - generate a typedef.
1233 ResultStr = "#ifndef _REWRITER_typedef_";
1234 ResultStr += ClassDecl->getNameAsString();
1235 ResultStr += "\n";
1236 ResultStr += "#define _REWRITER_typedef_";
1237 ResultStr += ClassDecl->getNameAsString();
1238 ResultStr += "\n";
1239 ResultStr += "typedef struct objc_object ";
1240 ResultStr += ClassDecl->getNameAsString();
1241 ResultStr += ";\n#endif\n";
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00001242
1243 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1244
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001245 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001246 // Mark this typedef as having been written into its c++ equivalent.
1247 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001248
1249 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001250 E = ClassDecl->prop_end(); I != E; ++I)
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001251 RewriteProperty(*I);
1252 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001253 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001254 I != E; ++I)
1255 RewriteMethodDeclaration(*I);
1256 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001257 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001258 I != E; ++I)
1259 RewriteMethodDeclaration(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001260
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001261 // Lastly, comment out the @end.
1262 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1263 "/* @end */");
1264 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001265}
1266
1267Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1268 SourceRange OldRange = PseudoOp->getSourceRange();
1269
1270 // We just magically know some things about the structure of this
1271 // expression.
1272 ObjCMessageExpr *OldMsg =
1273 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1274 PseudoOp->getNumSemanticExprs() - 1));
1275
1276 // Because the rewriter doesn't allow us to rewrite rewritten code,
1277 // we need to suppress rewriting the sub-statements.
1278 Expr *Base, *RHS;
1279 {
1280 DisableReplaceStmtScope S(*this);
1281
1282 // Rebuild the base expression if we have one.
1283 Base = 0;
1284 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1285 Base = OldMsg->getInstanceReceiver();
1286 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1287 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1288 }
1289
1290 // Rebuild the RHS.
1291 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1292 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1293 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1294 }
1295
1296 // TODO: avoid this copy.
1297 SmallVector<SourceLocation, 1> SelLocs;
1298 OldMsg->getSelectorLocs(SelLocs);
1299
1300 ObjCMessageExpr *NewMsg = 0;
1301 switch (OldMsg->getReceiverKind()) {
1302 case ObjCMessageExpr::Class:
1303 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1304 OldMsg->getValueKind(),
1305 OldMsg->getLeftLoc(),
1306 OldMsg->getClassReceiverTypeInfo(),
1307 OldMsg->getSelector(),
1308 SelLocs,
1309 OldMsg->getMethodDecl(),
1310 RHS,
1311 OldMsg->getRightLoc(),
1312 OldMsg->isImplicit());
1313 break;
1314
1315 case ObjCMessageExpr::Instance:
1316 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1317 OldMsg->getValueKind(),
1318 OldMsg->getLeftLoc(),
1319 Base,
1320 OldMsg->getSelector(),
1321 SelLocs,
1322 OldMsg->getMethodDecl(),
1323 RHS,
1324 OldMsg->getRightLoc(),
1325 OldMsg->isImplicit());
1326 break;
1327
1328 case ObjCMessageExpr::SuperClass:
1329 case ObjCMessageExpr::SuperInstance:
1330 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1331 OldMsg->getValueKind(),
1332 OldMsg->getLeftLoc(),
1333 OldMsg->getSuperLoc(),
1334 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1335 OldMsg->getSuperType(),
1336 OldMsg->getSelector(),
1337 SelLocs,
1338 OldMsg->getMethodDecl(),
1339 RHS,
1340 OldMsg->getRightLoc(),
1341 OldMsg->isImplicit());
1342 break;
1343 }
1344
1345 Stmt *Replacement = SynthMessageExpr(NewMsg);
1346 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1347 return Replacement;
1348}
1349
1350Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1351 SourceRange OldRange = PseudoOp->getSourceRange();
1352
1353 // We just magically know some things about the structure of this
1354 // expression.
1355 ObjCMessageExpr *OldMsg =
1356 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1357
1358 // Because the rewriter doesn't allow us to rewrite rewritten code,
1359 // we need to suppress rewriting the sub-statements.
1360 Expr *Base = 0;
1361 {
1362 DisableReplaceStmtScope S(*this);
1363
1364 // Rebuild the base expression if we have one.
1365 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1366 Base = OldMsg->getInstanceReceiver();
1367 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1368 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1369 }
1370 }
1371
1372 // Intentionally empty.
1373 SmallVector<SourceLocation, 1> SelLocs;
1374 SmallVector<Expr*, 1> Args;
1375
1376 ObjCMessageExpr *NewMsg = 0;
1377 switch (OldMsg->getReceiverKind()) {
1378 case ObjCMessageExpr::Class:
1379 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1380 OldMsg->getValueKind(),
1381 OldMsg->getLeftLoc(),
1382 OldMsg->getClassReceiverTypeInfo(),
1383 OldMsg->getSelector(),
1384 SelLocs,
1385 OldMsg->getMethodDecl(),
1386 Args,
1387 OldMsg->getRightLoc(),
1388 OldMsg->isImplicit());
1389 break;
1390
1391 case ObjCMessageExpr::Instance:
1392 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1393 OldMsg->getValueKind(),
1394 OldMsg->getLeftLoc(),
1395 Base,
1396 OldMsg->getSelector(),
1397 SelLocs,
1398 OldMsg->getMethodDecl(),
1399 Args,
1400 OldMsg->getRightLoc(),
1401 OldMsg->isImplicit());
1402 break;
1403
1404 case ObjCMessageExpr::SuperClass:
1405 case ObjCMessageExpr::SuperInstance:
1406 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1407 OldMsg->getValueKind(),
1408 OldMsg->getLeftLoc(),
1409 OldMsg->getSuperLoc(),
1410 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1411 OldMsg->getSuperType(),
1412 OldMsg->getSelector(),
1413 SelLocs,
1414 OldMsg->getMethodDecl(),
1415 Args,
1416 OldMsg->getRightLoc(),
1417 OldMsg->isImplicit());
1418 break;
1419 }
1420
1421 Stmt *Replacement = SynthMessageExpr(NewMsg);
1422 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1423 return Replacement;
1424}
1425
1426/// SynthCountByEnumWithState - To print:
1427/// ((unsigned int (*)
1428/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1429/// (void *)objc_msgSend)((id)l_collection,
1430/// sel_registerName(
1431/// "countByEnumeratingWithState:objects:count:"),
1432/// &enumState,
1433/// (id *)__rw_items, (unsigned int)16)
1434///
1435void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1436 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1437 "id *, unsigned int))(void *)objc_msgSend)";
1438 buf += "\n\t\t";
1439 buf += "((id)l_collection,\n\t\t";
1440 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1441 buf += "\n\t\t";
1442 buf += "&enumState, "
1443 "(id *)__rw_items, (unsigned int)16)";
1444}
1445
1446/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1447/// statement to exit to its outer synthesized loop.
1448///
1449Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1450 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1451 return S;
1452 // replace break with goto __break_label
1453 std::string buf;
1454
1455 SourceLocation startLoc = S->getLocStart();
1456 buf = "goto __break_label_";
1457 buf += utostr(ObjCBcLabelNo.back());
1458 ReplaceText(startLoc, strlen("break"), buf);
1459
1460 return 0;
1461}
1462
1463/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1464/// statement to continue with its inner synthesized loop.
1465///
1466Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1467 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1468 return S;
1469 // replace continue with goto __continue_label
1470 std::string buf;
1471
1472 SourceLocation startLoc = S->getLocStart();
1473 buf = "goto __continue_label_";
1474 buf += utostr(ObjCBcLabelNo.back());
1475 ReplaceText(startLoc, strlen("continue"), buf);
1476
1477 return 0;
1478}
1479
1480/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1481/// It rewrites:
1482/// for ( type elem in collection) { stmts; }
1483
1484/// Into:
1485/// {
1486/// type elem;
1487/// struct __objcFastEnumerationState enumState = { 0 };
1488/// id __rw_items[16];
1489/// id l_collection = (id)collection;
1490/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1491/// objects:__rw_items count:16];
1492/// if (limit) {
1493/// unsigned long startMutations = *enumState.mutationsPtr;
1494/// do {
1495/// unsigned long counter = 0;
1496/// do {
1497/// if (startMutations != *enumState.mutationsPtr)
1498/// objc_enumerationMutation(l_collection);
1499/// elem = (type)enumState.itemsPtr[counter++];
1500/// stmts;
1501/// __continue_label: ;
1502/// } while (counter < limit);
1503/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1504/// objects:__rw_items count:16]);
1505/// elem = nil;
1506/// __break_label: ;
1507/// }
1508/// else
1509/// elem = nil;
1510/// }
1511///
1512Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1513 SourceLocation OrigEnd) {
1514 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1515 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1516 "ObjCForCollectionStmt Statement stack mismatch");
1517 assert(!ObjCBcLabelNo.empty() &&
1518 "ObjCForCollectionStmt - Label No stack empty");
1519
1520 SourceLocation startLoc = S->getLocStart();
1521 const char *startBuf = SM->getCharacterData(startLoc);
1522 StringRef elementName;
1523 std::string elementTypeAsString;
1524 std::string buf;
1525 buf = "\n{\n\t";
1526 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1527 // type elem;
1528 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1529 QualType ElementType = cast<ValueDecl>(D)->getType();
1530 if (ElementType->isObjCQualifiedIdType() ||
1531 ElementType->isObjCQualifiedInterfaceType())
1532 // Simply use 'id' for all qualified types.
1533 elementTypeAsString = "id";
1534 else
1535 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1536 buf += elementTypeAsString;
1537 buf += " ";
1538 elementName = D->getName();
1539 buf += elementName;
1540 buf += ";\n\t";
1541 }
1542 else {
1543 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1544 elementName = DR->getDecl()->getName();
1545 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1546 if (VD->getType()->isObjCQualifiedIdType() ||
1547 VD->getType()->isObjCQualifiedInterfaceType())
1548 // Simply use 'id' for all qualified types.
1549 elementTypeAsString = "id";
1550 else
1551 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1552 }
1553
1554 // struct __objcFastEnumerationState enumState = { 0 };
1555 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1556 // id __rw_items[16];
1557 buf += "id __rw_items[16];\n\t";
1558 // id l_collection = (id)
1559 buf += "id l_collection = (id)";
1560 // Find start location of 'collection' the hard way!
1561 const char *startCollectionBuf = startBuf;
1562 startCollectionBuf += 3; // skip 'for'
1563 startCollectionBuf = strchr(startCollectionBuf, '(');
1564 startCollectionBuf++; // skip '('
1565 // find 'in' and skip it.
1566 while (*startCollectionBuf != ' ' ||
1567 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1568 (*(startCollectionBuf+3) != ' ' &&
1569 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1570 startCollectionBuf++;
1571 startCollectionBuf += 3;
1572
1573 // Replace: "for (type element in" with string constructed thus far.
1574 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1575 // Replace ')' in for '(' type elem in collection ')' with ';'
1576 SourceLocation rightParenLoc = S->getRParenLoc();
1577 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1578 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1579 buf = ";\n\t";
1580
1581 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1582 // objects:__rw_items count:16];
1583 // which is synthesized into:
1584 // unsigned int limit =
1585 // ((unsigned int (*)
1586 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1587 // (void *)objc_msgSend)((id)l_collection,
1588 // sel_registerName(
1589 // "countByEnumeratingWithState:objects:count:"),
1590 // (struct __objcFastEnumerationState *)&state,
1591 // (id *)__rw_items, (unsigned int)16);
1592 buf += "unsigned long limit =\n\t\t";
1593 SynthCountByEnumWithState(buf);
1594 buf += ";\n\t";
1595 /// if (limit) {
1596 /// unsigned long startMutations = *enumState.mutationsPtr;
1597 /// do {
1598 /// unsigned long counter = 0;
1599 /// do {
1600 /// if (startMutations != *enumState.mutationsPtr)
1601 /// objc_enumerationMutation(l_collection);
1602 /// elem = (type)enumState.itemsPtr[counter++];
1603 buf += "if (limit) {\n\t";
1604 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1605 buf += "do {\n\t\t";
1606 buf += "unsigned long counter = 0;\n\t\t";
1607 buf += "do {\n\t\t\t";
1608 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1609 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1610 buf += elementName;
1611 buf += " = (";
1612 buf += elementTypeAsString;
1613 buf += ")enumState.itemsPtr[counter++];";
1614 // Replace ')' in for '(' type elem in collection ')' with all of these.
1615 ReplaceText(lparenLoc, 1, buf);
1616
1617 /// __continue_label: ;
1618 /// } while (counter < limit);
1619 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1620 /// objects:__rw_items count:16]);
1621 /// elem = nil;
1622 /// __break_label: ;
1623 /// }
1624 /// else
1625 /// elem = nil;
1626 /// }
1627 ///
1628 buf = ";\n\t";
1629 buf += "__continue_label_";
1630 buf += utostr(ObjCBcLabelNo.back());
1631 buf += ": ;";
1632 buf += "\n\t\t";
1633 buf += "} while (counter < limit);\n\t";
1634 buf += "} while (limit = ";
1635 SynthCountByEnumWithState(buf);
1636 buf += ");\n\t";
1637 buf += elementName;
1638 buf += " = ((";
1639 buf += elementTypeAsString;
1640 buf += ")0);\n\t";
1641 buf += "__break_label_";
1642 buf += utostr(ObjCBcLabelNo.back());
1643 buf += ": ;\n\t";
1644 buf += "}\n\t";
1645 buf += "else\n\t\t";
1646 buf += elementName;
1647 buf += " = ((";
1648 buf += elementTypeAsString;
1649 buf += ")0);\n\t";
1650 buf += "}\n";
1651
1652 // Insert all these *after* the statement body.
1653 // FIXME: If this should support Obj-C++, support CXXTryStmt
1654 if (isa<CompoundStmt>(S->getBody())) {
1655 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1656 InsertText(endBodyLoc, buf);
1657 } else {
1658 /* Need to treat single statements specially. For example:
1659 *
1660 * for (A *a in b) if (stuff()) break;
1661 * for (A *a in b) xxxyy;
1662 *
1663 * The following code simply scans ahead to the semi to find the actual end.
1664 */
1665 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1666 const char *semiBuf = strchr(stmtBuf, ';');
1667 assert(semiBuf && "Can't find ';'");
1668 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1669 InsertText(endBodyLoc, buf);
1670 }
1671 Stmts.pop_back();
1672 ObjCBcLabelNo.pop_back();
1673 return 0;
1674}
1675
1676/// RewriteObjCSynchronizedStmt -
1677/// This routine rewrites @synchronized(expr) stmt;
1678/// into:
1679/// objc_sync_enter(expr);
1680/// @try stmt @finally { objc_sync_exit(expr); }
1681///
1682Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1683 // Get the start location and compute the semi location.
1684 SourceLocation startLoc = S->getLocStart();
1685 const char *startBuf = SM->getCharacterData(startLoc);
1686
1687 assert((*startBuf == '@') && "bogus @synchronized location");
1688
1689 std::string buf;
1690 buf = "objc_sync_enter((id)";
1691 const char *lparenBuf = startBuf;
1692 while (*lparenBuf != '(') lparenBuf++;
1693 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
1694 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1695 // the sync expression is typically a message expression that's already
1696 // been rewritten! (which implies the SourceLocation's are invalid).
1697 SourceLocation endLoc = S->getSynchBody()->getLocStart();
1698 const char *endBuf = SM->getCharacterData(endLoc);
1699 while (*endBuf != ')') endBuf--;
1700 SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
1701 buf = ");\n";
1702 // declare a new scope with two variables, _stack and _rethrow.
1703 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1704 buf += "int buf[18/*32-bit i386*/];\n";
1705 buf += "char *pointers[4];} _stack;\n";
1706 buf += "id volatile _rethrow = 0;\n";
1707 buf += "objc_exception_try_enter(&_stack);\n";
1708 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
1709 ReplaceText(rparenLoc, 1, buf);
1710 startLoc = S->getSynchBody()->getLocEnd();
1711 startBuf = SM->getCharacterData(startLoc);
1712
1713 assert((*startBuf == '}') && "bogus @synchronized block");
1714 SourceLocation lastCurlyLoc = startLoc;
1715 buf = "}\nelse {\n";
1716 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1717 buf += "}\n";
1718 buf += "{ /* implicit finally clause */\n";
1719 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1720
1721 std::string syncBuf;
1722 syncBuf += " objc_sync_exit(";
1723
1724 Expr *syncExpr = S->getSynchExpr();
1725 CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1726 ? CK_BitCast :
1727 syncExpr->getType()->isBlockPointerType()
1728 ? CK_BlockPointerToObjCPointerCast
1729 : CK_CPointerToObjCPointerCast;
1730 syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1731 CK, syncExpr);
1732 std::string syncExprBufS;
1733 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
1734 syncExpr->printPretty(syncExprBuf, *Context, 0,
1735 PrintingPolicy(LangOpts));
1736 syncBuf += syncExprBuf.str();
1737 syncBuf += ");";
1738
1739 buf += syncBuf;
1740 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
1741 buf += "}\n";
1742 buf += "}";
1743
1744 ReplaceText(lastCurlyLoc, 1, buf);
1745
1746 bool hasReturns = false;
1747 HasReturnStmts(S->getSynchBody(), hasReturns);
1748 if (hasReturns)
1749 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1750
1751 return 0;
1752}
1753
1754void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1755{
1756 // Perform a bottom up traversal of all children.
1757 for (Stmt::child_range CI = S->children(); CI; ++CI)
1758 if (*CI)
1759 WarnAboutReturnGotoStmts(*CI);
1760
1761 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1762 Diags.Report(Context->getFullLoc(S->getLocStart()),
1763 TryFinallyContainsReturnDiag);
1764 }
1765 return;
1766}
1767
1768void RewriteModernObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1769{
1770 // Perform a bottom up traversal of all children.
1771 for (Stmt::child_range CI = S->children(); CI; ++CI)
1772 if (*CI)
1773 HasReturnStmts(*CI, hasReturns);
1774
1775 if (isa<ReturnStmt>(S))
1776 hasReturns = true;
1777 return;
1778}
1779
1780void RewriteModernObjC::RewriteTryReturnStmts(Stmt *S) {
1781 // Perform a bottom up traversal of all children.
1782 for (Stmt::child_range CI = S->children(); CI; ++CI)
1783 if (*CI) {
1784 RewriteTryReturnStmts(*CI);
1785 }
1786 if (isa<ReturnStmt>(S)) {
1787 SourceLocation startLoc = S->getLocStart();
1788 const char *startBuf = SM->getCharacterData(startLoc);
1789
1790 const char *semiBuf = strchr(startBuf, ';');
1791 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1792 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
1793
1794 std::string buf;
1795 buf = "{ objc_exception_try_exit(&_stack); return";
1796
1797 ReplaceText(startLoc, 6, buf);
1798 InsertText(onePastSemiLoc, "}");
1799 }
1800 return;
1801}
1802
1803void RewriteModernObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1804 // Perform a bottom up traversal of all children.
1805 for (Stmt::child_range CI = S->children(); CI; ++CI)
1806 if (*CI) {
1807 RewriteSyncReturnStmts(*CI, syncExitBuf);
1808 }
1809 if (isa<ReturnStmt>(S)) {
1810 SourceLocation startLoc = S->getLocStart();
1811 const char *startBuf = SM->getCharacterData(startLoc);
1812
1813 const char *semiBuf = strchr(startBuf, ';');
1814 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1815 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
1816
1817 std::string buf;
1818 buf = "{ objc_exception_try_exit(&_stack);";
1819 buf += syncExitBuf;
1820 buf += " return";
1821
1822 ReplaceText(startLoc, 6, buf);
1823 InsertText(onePastSemiLoc, "}");
1824 }
1825 return;
1826}
1827
1828Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
1829 // Get the start location and compute the semi location.
1830 SourceLocation startLoc = S->getLocStart();
1831 const char *startBuf = SM->getCharacterData(startLoc);
1832
1833 assert((*startBuf == '@') && "bogus @try location");
1834
1835 std::string buf;
1836 // declare a new scope with two variables, _stack and _rethrow.
1837 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1838 buf += "int buf[18/*32-bit i386*/];\n";
1839 buf += "char *pointers[4];} _stack;\n";
1840 buf += "id volatile _rethrow = 0;\n";
1841 buf += "objc_exception_try_enter(&_stack);\n";
1842 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
1843
1844 ReplaceText(startLoc, 4, buf);
1845
1846 startLoc = S->getTryBody()->getLocEnd();
1847 startBuf = SM->getCharacterData(startLoc);
1848
1849 assert((*startBuf == '}') && "bogus @try block");
1850
1851 SourceLocation lastCurlyLoc = startLoc;
1852 if (S->getNumCatchStmts()) {
1853 startLoc = startLoc.getLocWithOffset(1);
1854 buf = " /* @catch begin */ else {\n";
1855 buf += " id _caught = objc_exception_extract(&_stack);\n";
1856 buf += " objc_exception_try_enter (&_stack);\n";
1857 buf += " if (_setjmp(_stack.buf))\n";
1858 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1859 buf += " else { /* @catch continue */";
1860
1861 InsertText(startLoc, buf);
1862 } else { /* no catch list */
1863 buf = "}\nelse {\n";
1864 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1865 buf += "}";
1866 ReplaceText(lastCurlyLoc, 1, buf);
1867 }
1868 Stmt *lastCatchBody = 0;
1869 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1870 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
1871 VarDecl *catchDecl = Catch->getCatchParamDecl();
1872
1873 if (I == 0)
1874 buf = "if ("; // we are generating code for the first catch clause
1875 else
1876 buf = "else if (";
1877 startLoc = Catch->getLocStart();
1878 startBuf = SM->getCharacterData(startLoc);
1879
1880 assert((*startBuf == '@') && "bogus @catch location");
1881
1882 const char *lParenLoc = strchr(startBuf, '(');
1883
1884 if (Catch->hasEllipsis()) {
1885 // Now rewrite the body...
1886 lastCatchBody = Catch->getCatchBody();
1887 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1888 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1889 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
1890 "bogus @catch paren location");
1891 assert((*bodyBuf == '{') && "bogus @catch body location");
1892
1893 buf += "1) { id _tmp = _caught;";
1894 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
1895 } else if (catchDecl) {
1896 QualType t = catchDecl->getType();
1897 if (t == Context->getObjCIdType()) {
1898 buf += "1) { ";
1899 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
1900 } else if (const ObjCObjectPointerType *Ptr =
1901 t->getAs<ObjCObjectPointerType>()) {
1902 // Should be a pointer to a class.
1903 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1904 if (IDecl) {
1905 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
1906 buf += IDecl->getNameAsString();
1907 buf += "\"), (struct objc_object *)_caught)) { ";
1908 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
1909 }
1910 }
1911 // Now rewrite the body...
1912 lastCatchBody = Catch->getCatchBody();
1913 SourceLocation rParenLoc = Catch->getRParenLoc();
1914 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1915 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1916 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1917 assert((*rParenBuf == ')') && "bogus @catch paren location");
1918 assert((*bodyBuf == '{') && "bogus @catch body location");
1919
1920 // Here we replace ") {" with "= _caught;" (which initializes and
1921 // declares the @catch parameter).
1922 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
1923 } else {
1924 llvm_unreachable("@catch rewrite bug");
1925 }
1926 }
1927 // Complete the catch list...
1928 if (lastCatchBody) {
1929 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
1930 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1931 "bogus @catch body location");
1932
1933 // Insert the last (implicit) else clause *before* the right curly brace.
1934 bodyLoc = bodyLoc.getLocWithOffset(-1);
1935 buf = "} /* last catch end */\n";
1936 buf += "else {\n";
1937 buf += " _rethrow = _caught;\n";
1938 buf += " objc_exception_try_exit(&_stack);\n";
1939 buf += "} } /* @catch end */\n";
1940 if (!S->getFinallyStmt())
1941 buf += "}\n";
1942 InsertText(bodyLoc, buf);
1943
1944 // Set lastCurlyLoc
1945 lastCurlyLoc = lastCatchBody->getLocEnd();
1946 }
1947 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
1948 startLoc = finalStmt->getLocStart();
1949 startBuf = SM->getCharacterData(startLoc);
1950 assert((*startBuf == '@') && "bogus @finally start");
1951
1952 ReplaceText(startLoc, 8, "/* @finally */");
1953
1954 Stmt *body = finalStmt->getFinallyBody();
1955 SourceLocation startLoc = body->getLocStart();
1956 SourceLocation endLoc = body->getLocEnd();
1957 assert(*SM->getCharacterData(startLoc) == '{' &&
1958 "bogus @finally body location");
1959 assert(*SM->getCharacterData(endLoc) == '}' &&
1960 "bogus @finally body location");
1961
1962 startLoc = startLoc.getLocWithOffset(1);
1963 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
1964 endLoc = endLoc.getLocWithOffset(-1);
1965 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
1966
1967 // Set lastCurlyLoc
1968 lastCurlyLoc = body->getLocEnd();
1969
1970 // Now check for any return/continue/go statements within the @try.
1971 WarnAboutReturnGotoStmts(S->getTryBody());
1972 } else { /* no finally clause - make sure we synthesize an implicit one */
1973 buf = "{ /* implicit finally clause */\n";
1974 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1975 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1976 buf += "}";
1977 ReplaceText(lastCurlyLoc, 1, buf);
1978
1979 // Now check for any return/continue/go statements within the @try.
1980 // The implicit finally clause won't called if the @try contains any
1981 // jump statements.
1982 bool hasReturns = false;
1983 HasReturnStmts(S->getTryBody(), hasReturns);
1984 if (hasReturns)
1985 RewriteTryReturnStmts(S->getTryBody());
1986 }
1987 // Now emit the final closing curly brace...
1988 lastCurlyLoc = lastCurlyLoc.getLocWithOffset(1);
1989 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
1990 return 0;
1991}
1992
1993// This can't be done with ReplaceStmt(S, ThrowExpr), since
1994// the throw expression is typically a message expression that's already
1995// been rewritten! (which implies the SourceLocation's are invalid).
1996Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
1997 // Get the start location and compute the semi location.
1998 SourceLocation startLoc = S->getLocStart();
1999 const char *startBuf = SM->getCharacterData(startLoc);
2000
2001 assert((*startBuf == '@') && "bogus @throw location");
2002
2003 std::string buf;
2004 /* void objc_exception_throw(id) __attribute__((noreturn)); */
2005 if (S->getThrowExpr())
2006 buf = "objc_exception_throw(";
2007 else // add an implicit argument
2008 buf = "objc_exception_throw(_caught";
2009
2010 // handle "@ throw" correctly.
2011 const char *wBuf = strchr(startBuf, 'w');
2012 assert((*wBuf == 'w') && "@throw: can't find 'w'");
2013 ReplaceText(startLoc, wBuf-startBuf+1, buf);
2014
2015 const char *semiBuf = strchr(startBuf, ';');
2016 assert((*semiBuf == ';') && "@throw: can't find ';'");
2017 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
2018 ReplaceText(semiLoc, 1, ");");
2019 return 0;
2020}
2021
2022Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2023 // Create a new string expression.
2024 QualType StrType = Context->getPointerType(Context->CharTy);
2025 std::string StrEncoding;
2026 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
2027 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
2028 StringLiteral::Ascii, false,
2029 StrType, SourceLocation());
2030 ReplaceStmt(Exp, Replacement);
2031
2032 // Replace this subexpr in the parent.
2033 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2034 return Replacement;
2035}
2036
2037Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2038 if (!SelGetUidFunctionDecl)
2039 SynthSelGetUidFunctionDecl();
2040 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2041 // Create a call to sel_registerName("selName").
2042 SmallVector<Expr*, 8> SelExprs;
2043 QualType argType = Context->getPointerType(Context->CharTy);
2044 SelExprs.push_back(StringLiteral::Create(*Context,
2045 Exp->getSelector().getAsString(),
2046 StringLiteral::Ascii, false,
2047 argType, SourceLocation()));
2048 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2049 &SelExprs[0], SelExprs.size());
2050 ReplaceStmt(Exp, SelExp);
2051 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2052 return SelExp;
2053}
2054
2055CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
2056 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2057 SourceLocation EndLoc) {
2058 // Get the type, we will need to reference it in a couple spots.
2059 QualType msgSendType = FD->getType();
2060
2061 // Create a reference to the objc_msgSend() declaration.
2062 DeclRefExpr *DRE =
2063 new (Context) DeclRefExpr(FD, msgSendType, VK_LValue, SourceLocation());
2064
2065 // Now, we cast the reference to a pointer to the objc_msgSend type.
2066 QualType pToFunc = Context->getPointerType(msgSendType);
2067 ImplicitCastExpr *ICE =
2068 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2069 DRE, 0, VK_RValue);
2070
2071 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2072
2073 CallExpr *Exp =
2074 new (Context) CallExpr(*Context, ICE, args, nargs,
2075 FT->getCallResultType(*Context),
2076 VK_RValue, EndLoc);
2077 return Exp;
2078}
2079
2080static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2081 const char *&startRef, const char *&endRef) {
2082 while (startBuf < endBuf) {
2083 if (*startBuf == '<')
2084 startRef = startBuf; // mark the start.
2085 if (*startBuf == '>') {
2086 if (startRef && *startRef == '<') {
2087 endRef = startBuf; // mark the end.
2088 return true;
2089 }
2090 return false;
2091 }
2092 startBuf++;
2093 }
2094 return false;
2095}
2096
2097static void scanToNextArgument(const char *&argRef) {
2098 int angle = 0;
2099 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2100 if (*argRef == '<')
2101 angle++;
2102 else if (*argRef == '>')
2103 angle--;
2104 argRef++;
2105 }
2106 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2107}
2108
2109bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2110 if (T->isObjCQualifiedIdType())
2111 return true;
2112 if (const PointerType *PT = T->getAs<PointerType>()) {
2113 if (PT->getPointeeType()->isObjCQualifiedIdType())
2114 return true;
2115 }
2116 if (T->isObjCObjectPointerType()) {
2117 T = T->getPointeeType();
2118 return T->isObjCQualifiedInterfaceType();
2119 }
2120 if (T->isArrayType()) {
2121 QualType ElemTy = Context->getBaseElementType(T);
2122 return needToScanForQualifiers(ElemTy);
2123 }
2124 return false;
2125}
2126
2127void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2128 QualType Type = E->getType();
2129 if (needToScanForQualifiers(Type)) {
2130 SourceLocation Loc, EndLoc;
2131
2132 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2133 Loc = ECE->getLParenLoc();
2134 EndLoc = ECE->getRParenLoc();
2135 } else {
2136 Loc = E->getLocStart();
2137 EndLoc = E->getLocEnd();
2138 }
2139 // This will defend against trying to rewrite synthesized expressions.
2140 if (Loc.isInvalid() || EndLoc.isInvalid())
2141 return;
2142
2143 const char *startBuf = SM->getCharacterData(Loc);
2144 const char *endBuf = SM->getCharacterData(EndLoc);
2145 const char *startRef = 0, *endRef = 0;
2146 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2147 // Get the locations of the startRef, endRef.
2148 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2149 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2150 // Comment out the protocol references.
2151 InsertText(LessLoc, "/*");
2152 InsertText(GreaterLoc, "*/");
2153 }
2154 }
2155}
2156
2157void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2158 SourceLocation Loc;
2159 QualType Type;
2160 const FunctionProtoType *proto = 0;
2161 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2162 Loc = VD->getLocation();
2163 Type = VD->getType();
2164 }
2165 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2166 Loc = FD->getLocation();
2167 // Check for ObjC 'id' and class types that have been adorned with protocol
2168 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2169 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2170 assert(funcType && "missing function type");
2171 proto = dyn_cast<FunctionProtoType>(funcType);
2172 if (!proto)
2173 return;
2174 Type = proto->getResultType();
2175 }
2176 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2177 Loc = FD->getLocation();
2178 Type = FD->getType();
2179 }
2180 else
2181 return;
2182
2183 if (needToScanForQualifiers(Type)) {
2184 // Since types are unique, we need to scan the buffer.
2185
2186 const char *endBuf = SM->getCharacterData(Loc);
2187 const char *startBuf = endBuf;
2188 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2189 startBuf--; // scan backward (from the decl location) for return type.
2190 const char *startRef = 0, *endRef = 0;
2191 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2192 // Get the locations of the startRef, endRef.
2193 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2194 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2195 // Comment out the protocol references.
2196 InsertText(LessLoc, "/*");
2197 InsertText(GreaterLoc, "*/");
2198 }
2199 }
2200 if (!proto)
2201 return; // most likely, was a variable
2202 // Now check arguments.
2203 const char *startBuf = SM->getCharacterData(Loc);
2204 const char *startFuncBuf = startBuf;
2205 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2206 if (needToScanForQualifiers(proto->getArgType(i))) {
2207 // Since types are unique, we need to scan the buffer.
2208
2209 const char *endBuf = startBuf;
2210 // scan forward (from the decl location) for argument types.
2211 scanToNextArgument(endBuf);
2212 const char *startRef = 0, *endRef = 0;
2213 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2214 // Get the locations of the startRef, endRef.
2215 SourceLocation LessLoc =
2216 Loc.getLocWithOffset(startRef-startFuncBuf);
2217 SourceLocation GreaterLoc =
2218 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2219 // Comment out the protocol references.
2220 InsertText(LessLoc, "/*");
2221 InsertText(GreaterLoc, "*/");
2222 }
2223 startBuf = ++endBuf;
2224 }
2225 else {
2226 // If the function name is derived from a macro expansion, then the
2227 // argument buffer will not follow the name. Need to speak with Chris.
2228 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2229 startBuf++; // scan forward (from the decl location) for argument types.
2230 startBuf++;
2231 }
2232 }
2233}
2234
2235void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2236 QualType QT = ND->getType();
2237 const Type* TypePtr = QT->getAs<Type>();
2238 if (!isa<TypeOfExprType>(TypePtr))
2239 return;
2240 while (isa<TypeOfExprType>(TypePtr)) {
2241 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2242 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2243 TypePtr = QT->getAs<Type>();
2244 }
2245 // FIXME. This will not work for multiple declarators; as in:
2246 // __typeof__(a) b,c,d;
2247 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2248 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2249 const char *startBuf = SM->getCharacterData(DeclLoc);
2250 if (ND->getInit()) {
2251 std::string Name(ND->getNameAsString());
2252 TypeAsString += " " + Name + " = ";
2253 Expr *E = ND->getInit();
2254 SourceLocation startLoc;
2255 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2256 startLoc = ECE->getLParenLoc();
2257 else
2258 startLoc = E->getLocStart();
2259 startLoc = SM->getExpansionLoc(startLoc);
2260 const char *endBuf = SM->getCharacterData(startLoc);
2261 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2262 }
2263 else {
2264 SourceLocation X = ND->getLocEnd();
2265 X = SM->getExpansionLoc(X);
2266 const char *endBuf = SM->getCharacterData(X);
2267 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2268 }
2269}
2270
2271// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2272void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2273 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2274 SmallVector<QualType, 16> ArgTys;
2275 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2276 QualType getFuncType =
2277 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
2278 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2279 SourceLocation(),
2280 SourceLocation(),
2281 SelGetUidIdent, getFuncType, 0,
2282 SC_Extern,
2283 SC_None, false);
2284}
2285
2286void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2287 // declared in <objc/objc.h>
2288 if (FD->getIdentifier() &&
2289 FD->getName() == "sel_registerName") {
2290 SelGetUidFunctionDecl = FD;
2291 return;
2292 }
2293 RewriteObjCQualifiedInterfaceTypes(FD);
2294}
2295
2296void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2297 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2298 const char *argPtr = TypeString.c_str();
2299 if (!strchr(argPtr, '^')) {
2300 Str += TypeString;
2301 return;
2302 }
2303 while (*argPtr) {
2304 Str += (*argPtr == '^' ? '*' : *argPtr);
2305 argPtr++;
2306 }
2307}
2308
2309// FIXME. Consolidate this routine with RewriteBlockPointerType.
2310void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2311 ValueDecl *VD) {
2312 QualType Type = VD->getType();
2313 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2314 const char *argPtr = TypeString.c_str();
2315 int paren = 0;
2316 while (*argPtr) {
2317 switch (*argPtr) {
2318 case '(':
2319 Str += *argPtr;
2320 paren++;
2321 break;
2322 case ')':
2323 Str += *argPtr;
2324 paren--;
2325 break;
2326 case '^':
2327 Str += '*';
2328 if (paren == 1)
2329 Str += VD->getNameAsString();
2330 break;
2331 default:
2332 Str += *argPtr;
2333 break;
2334 }
2335 argPtr++;
2336 }
2337}
2338
2339
2340void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2341 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2342 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2343 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2344 if (!proto)
2345 return;
2346 QualType Type = proto->getResultType();
2347 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2348 FdStr += " ";
2349 FdStr += FD->getName();
2350 FdStr += "(";
2351 unsigned numArgs = proto->getNumArgs();
2352 for (unsigned i = 0; i < numArgs; i++) {
2353 QualType ArgType = proto->getArgType(i);
2354 RewriteBlockPointerType(FdStr, ArgType);
2355 if (i+1 < numArgs)
2356 FdStr += ", ";
2357 }
2358 FdStr += ");\n";
2359 InsertText(FunLocStart, FdStr);
2360 CurFunctionDeclToDeclareForBlock = 0;
2361}
2362
2363// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
2364void RewriteModernObjC::SynthSuperContructorFunctionDecl() {
2365 if (SuperContructorFunctionDecl)
2366 return;
2367 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2368 SmallVector<QualType, 16> ArgTys;
2369 QualType argT = Context->getObjCIdType();
2370 assert(!argT.isNull() && "Can't find 'id' type");
2371 ArgTys.push_back(argT);
2372 ArgTys.push_back(argT);
2373 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2374 &ArgTys[0], ArgTys.size());
2375 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2376 SourceLocation(),
2377 SourceLocation(),
2378 msgSendIdent, msgSendType, 0,
2379 SC_Extern,
2380 SC_None, false);
2381}
2382
2383// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2384void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2385 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2386 SmallVector<QualType, 16> ArgTys;
2387 QualType argT = Context->getObjCIdType();
2388 assert(!argT.isNull() && "Can't find 'id' type");
2389 ArgTys.push_back(argT);
2390 argT = Context->getObjCSelType();
2391 assert(!argT.isNull() && "Can't find 'SEL' type");
2392 ArgTys.push_back(argT);
2393 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2394 &ArgTys[0], ArgTys.size(),
2395 true /*isVariadic*/);
2396 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2397 SourceLocation(),
2398 SourceLocation(),
2399 msgSendIdent, msgSendType, 0,
2400 SC_Extern,
2401 SC_None, false);
2402}
2403
2404// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
2405void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2406 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2407 SmallVector<QualType, 16> ArgTys;
2408 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2409 SourceLocation(), SourceLocation(),
2410 &Context->Idents.get("objc_super"));
2411 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2412 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2413 ArgTys.push_back(argT);
2414 argT = Context->getObjCSelType();
2415 assert(!argT.isNull() && "Can't find 'SEL' type");
2416 ArgTys.push_back(argT);
2417 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2418 &ArgTys[0], ArgTys.size(),
2419 true /*isVariadic*/);
2420 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2421 SourceLocation(),
2422 SourceLocation(),
2423 msgSendIdent, msgSendType, 0,
2424 SC_Extern,
2425 SC_None, false);
2426}
2427
2428// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2429void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2430 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2431 SmallVector<QualType, 16> ArgTys;
2432 QualType argT = Context->getObjCIdType();
2433 assert(!argT.isNull() && "Can't find 'id' type");
2434 ArgTys.push_back(argT);
2435 argT = Context->getObjCSelType();
2436 assert(!argT.isNull() && "Can't find 'SEL' type");
2437 ArgTys.push_back(argT);
2438 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2439 &ArgTys[0], ArgTys.size(),
2440 true /*isVariadic*/);
2441 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2442 SourceLocation(),
2443 SourceLocation(),
2444 msgSendIdent, msgSendType, 0,
2445 SC_Extern,
2446 SC_None, false);
2447}
2448
2449// SynthMsgSendSuperStretFunctionDecl -
2450// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
2451void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2452 IdentifierInfo *msgSendIdent =
2453 &Context->Idents.get("objc_msgSendSuper_stret");
2454 SmallVector<QualType, 16> ArgTys;
2455 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2456 SourceLocation(), SourceLocation(),
2457 &Context->Idents.get("objc_super"));
2458 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2459 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2460 ArgTys.push_back(argT);
2461 argT = Context->getObjCSelType();
2462 assert(!argT.isNull() && "Can't find 'SEL' type");
2463 ArgTys.push_back(argT);
2464 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2465 &ArgTys[0], ArgTys.size(),
2466 true /*isVariadic*/);
2467 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2468 SourceLocation(),
2469 SourceLocation(),
2470 msgSendIdent, msgSendType, 0,
2471 SC_Extern,
2472 SC_None, false);
2473}
2474
2475// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2476void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2477 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2478 SmallVector<QualType, 16> ArgTys;
2479 QualType argT = Context->getObjCIdType();
2480 assert(!argT.isNull() && "Can't find 'id' type");
2481 ArgTys.push_back(argT);
2482 argT = Context->getObjCSelType();
2483 assert(!argT.isNull() && "Can't find 'SEL' type");
2484 ArgTys.push_back(argT);
2485 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2486 &ArgTys[0], ArgTys.size(),
2487 true /*isVariadic*/);
2488 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2489 SourceLocation(),
2490 SourceLocation(),
2491 msgSendIdent, msgSendType, 0,
2492 SC_Extern,
2493 SC_None, false);
2494}
2495
2496// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
2497void RewriteModernObjC::SynthGetClassFunctionDecl() {
2498 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2499 SmallVector<QualType, 16> ArgTys;
2500 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2501 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2502 &ArgTys[0], ArgTys.size());
2503 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2504 SourceLocation(),
2505 SourceLocation(),
2506 getClassIdent, getClassType, 0,
2507 SC_Extern,
2508 SC_None, false);
2509}
2510
2511// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2512void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2513 IdentifierInfo *getSuperClassIdent =
2514 &Context->Idents.get("class_getSuperclass");
2515 SmallVector<QualType, 16> ArgTys;
2516 ArgTys.push_back(Context->getObjCClassType());
2517 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2518 &ArgTys[0], ArgTys.size());
2519 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2520 SourceLocation(),
2521 SourceLocation(),
2522 getSuperClassIdent,
2523 getClassType, 0,
2524 SC_Extern,
2525 SC_None,
2526 false);
2527}
2528
2529// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
2530void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2531 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2532 SmallVector<QualType, 16> ArgTys;
2533 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2534 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2535 &ArgTys[0], ArgTys.size());
2536 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2537 SourceLocation(),
2538 SourceLocation(),
2539 getClassIdent, getClassType, 0,
2540 SC_Extern,
2541 SC_None, false);
2542}
2543
2544Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2545 QualType strType = getConstantStringStructType();
2546
2547 std::string S = "__NSConstantStringImpl_";
2548
2549 std::string tmpName = InFileName;
2550 unsigned i;
2551 for (i=0; i < tmpName.length(); i++) {
2552 char c = tmpName.at(i);
2553 // replace any non alphanumeric characters with '_'.
2554 if (!isalpha(c) && (c < '0' || c > '9'))
2555 tmpName[i] = '_';
2556 }
2557 S += tmpName;
2558 S += "_";
2559 S += utostr(NumObjCStringLiterals++);
2560
2561 Preamble += "static __NSConstantStringImpl " + S;
2562 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2563 Preamble += "0x000007c8,"; // utf8_str
2564 // The pretty printer for StringLiteral handles escape characters properly.
2565 std::string prettyBufS;
2566 llvm::raw_string_ostream prettyBuf(prettyBufS);
2567 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2568 PrintingPolicy(LangOpts));
2569 Preamble += prettyBuf.str();
2570 Preamble += ",";
2571 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2572
2573 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2574 SourceLocation(), &Context->Idents.get(S),
2575 strType, 0, SC_Static, SC_None);
2576 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, VK_LValue,
2577 SourceLocation());
2578 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2579 Context->getPointerType(DRE->getType()),
2580 VK_RValue, OK_Ordinary,
2581 SourceLocation());
2582 // cast to NSConstantString *
2583 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2584 CK_CPointerToObjCPointerCast, Unop);
2585 ReplaceStmt(Exp, cast);
2586 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2587 return cast;
2588}
2589
2590// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
2591QualType RewriteModernObjC::getSuperStructType() {
2592 if (!SuperStructDecl) {
2593 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2594 SourceLocation(), SourceLocation(),
2595 &Context->Idents.get("objc_super"));
2596 QualType FieldTypes[2];
2597
2598 // struct objc_object *receiver;
2599 FieldTypes[0] = Context->getObjCIdType();
2600 // struct objc_class *super;
2601 FieldTypes[1] = Context->getObjCClassType();
2602
2603 // Create fields
2604 for (unsigned i = 0; i < 2; ++i) {
2605 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2606 SourceLocation(),
2607 SourceLocation(), 0,
2608 FieldTypes[i], 0,
2609 /*BitWidth=*/0,
2610 /*Mutable=*/false,
2611 /*HasInit=*/false));
2612 }
2613
2614 SuperStructDecl->completeDefinition();
2615 }
2616 return Context->getTagDeclType(SuperStructDecl);
2617}
2618
2619QualType RewriteModernObjC::getConstantStringStructType() {
2620 if (!ConstantStringDecl) {
2621 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2622 SourceLocation(), SourceLocation(),
2623 &Context->Idents.get("__NSConstantStringImpl"));
2624 QualType FieldTypes[4];
2625
2626 // struct objc_object *receiver;
2627 FieldTypes[0] = Context->getObjCIdType();
2628 // int flags;
2629 FieldTypes[1] = Context->IntTy;
2630 // char *str;
2631 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2632 // long length;
2633 FieldTypes[3] = Context->LongTy;
2634
2635 // Create fields
2636 for (unsigned i = 0; i < 4; ++i) {
2637 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2638 ConstantStringDecl,
2639 SourceLocation(),
2640 SourceLocation(), 0,
2641 FieldTypes[i], 0,
2642 /*BitWidth=*/0,
2643 /*Mutable=*/true,
2644 /*HasInit=*/false));
2645 }
2646
2647 ConstantStringDecl->completeDefinition();
2648 }
2649 return Context->getTagDeclType(ConstantStringDecl);
2650}
2651
2652Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2653 SourceLocation StartLoc,
2654 SourceLocation EndLoc) {
2655 if (!SelGetUidFunctionDecl)
2656 SynthSelGetUidFunctionDecl();
2657 if (!MsgSendFunctionDecl)
2658 SynthMsgSendFunctionDecl();
2659 if (!MsgSendSuperFunctionDecl)
2660 SynthMsgSendSuperFunctionDecl();
2661 if (!MsgSendStretFunctionDecl)
2662 SynthMsgSendStretFunctionDecl();
2663 if (!MsgSendSuperStretFunctionDecl)
2664 SynthMsgSendSuperStretFunctionDecl();
2665 if (!MsgSendFpretFunctionDecl)
2666 SynthMsgSendFpretFunctionDecl();
2667 if (!GetClassFunctionDecl)
2668 SynthGetClassFunctionDecl();
2669 if (!GetSuperClassFunctionDecl)
2670 SynthGetSuperClassFunctionDecl();
2671 if (!GetMetaClassFunctionDecl)
2672 SynthGetMetaClassFunctionDecl();
2673
2674 // default to objc_msgSend().
2675 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2676 // May need to use objc_msgSend_stret() as well.
2677 FunctionDecl *MsgSendStretFlavor = 0;
2678 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2679 QualType resultType = mDecl->getResultType();
2680 if (resultType->isRecordType())
2681 MsgSendStretFlavor = MsgSendStretFunctionDecl;
2682 else if (resultType->isRealFloatingType())
2683 MsgSendFlavor = MsgSendFpretFunctionDecl;
2684 }
2685
2686 // Synthesize a call to objc_msgSend().
2687 SmallVector<Expr*, 8> MsgExprs;
2688 switch (Exp->getReceiverKind()) {
2689 case ObjCMessageExpr::SuperClass: {
2690 MsgSendFlavor = MsgSendSuperFunctionDecl;
2691 if (MsgSendStretFlavor)
2692 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2693 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2694
2695 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2696
2697 SmallVector<Expr*, 4> InitExprs;
2698
2699 // set the receiver to self, the first argument to all methods.
2700 InitExprs.push_back(
2701 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2702 CK_BitCast,
2703 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2704 Context->getObjCIdType(),
2705 VK_RValue,
2706 SourceLocation()))
2707 ); // set the 'receiver'.
2708
2709 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2710 SmallVector<Expr*, 8> ClsExprs;
2711 QualType argType = Context->getPointerType(Context->CharTy);
2712 ClsExprs.push_back(StringLiteral::Create(*Context,
2713 ClassDecl->getIdentifier()->getName(),
2714 StringLiteral::Ascii, false,
2715 argType, SourceLocation()));
2716 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2717 &ClsExprs[0],
2718 ClsExprs.size(),
2719 StartLoc,
2720 EndLoc);
2721 // (Class)objc_getClass("CurrentClass")
2722 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2723 Context->getObjCClassType(),
2724 CK_BitCast, Cls);
2725 ClsExprs.clear();
2726 ClsExprs.push_back(ArgExpr);
2727 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2728 &ClsExprs[0], ClsExprs.size(),
2729 StartLoc, EndLoc);
2730
2731 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2732 // To turn off a warning, type-cast to 'id'
2733 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2734 NoTypeInfoCStyleCastExpr(Context,
2735 Context->getObjCIdType(),
2736 CK_BitCast, Cls));
2737 // struct objc_super
2738 QualType superType = getSuperStructType();
2739 Expr *SuperRep;
2740
2741 if (LangOpts.MicrosoftExt) {
2742 SynthSuperContructorFunctionDecl();
2743 // Simulate a contructor call...
2744 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
2745 superType, VK_LValue,
2746 SourceLocation());
2747 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2748 InitExprs.size(),
2749 superType, VK_LValue,
2750 SourceLocation());
2751 // The code for super is a little tricky to prevent collision with
2752 // the structure definition in the header. The rewriter has it's own
2753 // internal definition (__rw_objc_super) that is uses. This is why
2754 // we need the cast below. For example:
2755 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2756 //
2757 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2758 Context->getPointerType(SuperRep->getType()),
2759 VK_RValue, OK_Ordinary,
2760 SourceLocation());
2761 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2762 Context->getPointerType(superType),
2763 CK_BitCast, SuperRep);
2764 } else {
2765 // (struct objc_super) { <exprs from above> }
2766 InitListExpr *ILE =
2767 new (Context) InitListExpr(*Context, SourceLocation(),
2768 &InitExprs[0], InitExprs.size(),
2769 SourceLocation());
2770 TypeSourceInfo *superTInfo
2771 = Context->getTrivialTypeSourceInfo(superType);
2772 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2773 superType, VK_LValue,
2774 ILE, false);
2775 // struct objc_super *
2776 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2777 Context->getPointerType(SuperRep->getType()),
2778 VK_RValue, OK_Ordinary,
2779 SourceLocation());
2780 }
2781 MsgExprs.push_back(SuperRep);
2782 break;
2783 }
2784
2785 case ObjCMessageExpr::Class: {
2786 SmallVector<Expr*, 8> ClsExprs;
2787 QualType argType = Context->getPointerType(Context->CharTy);
2788 ObjCInterfaceDecl *Class
2789 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
2790 IdentifierInfo *clsName = Class->getIdentifier();
2791 ClsExprs.push_back(StringLiteral::Create(*Context,
2792 clsName->getName(),
2793 StringLiteral::Ascii, false,
2794 argType, SourceLocation()));
2795 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2796 &ClsExprs[0],
2797 ClsExprs.size(),
2798 StartLoc, EndLoc);
2799 MsgExprs.push_back(Cls);
2800 break;
2801 }
2802
2803 case ObjCMessageExpr::SuperInstance:{
2804 MsgSendFlavor = MsgSendSuperFunctionDecl;
2805 if (MsgSendStretFlavor)
2806 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2807 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2808 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2809 SmallVector<Expr*, 4> InitExprs;
2810
2811 InitExprs.push_back(
2812 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2813 CK_BitCast,
2814 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2815 Context->getObjCIdType(),
2816 VK_RValue, SourceLocation()))
2817 ); // set the 'receiver'.
2818
2819 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2820 SmallVector<Expr*, 8> ClsExprs;
2821 QualType argType = Context->getPointerType(Context->CharTy);
2822 ClsExprs.push_back(StringLiteral::Create(*Context,
2823 ClassDecl->getIdentifier()->getName(),
2824 StringLiteral::Ascii, false, argType,
2825 SourceLocation()));
2826 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2827 &ClsExprs[0],
2828 ClsExprs.size(),
2829 StartLoc, EndLoc);
2830 // (Class)objc_getClass("CurrentClass")
2831 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2832 Context->getObjCClassType(),
2833 CK_BitCast, Cls);
2834 ClsExprs.clear();
2835 ClsExprs.push_back(ArgExpr);
2836 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2837 &ClsExprs[0], ClsExprs.size(),
2838 StartLoc, EndLoc);
2839
2840 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2841 // To turn off a warning, type-cast to 'id'
2842 InitExprs.push_back(
2843 // set 'super class', using class_getSuperclass().
2844 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2845 CK_BitCast, Cls));
2846 // struct objc_super
2847 QualType superType = getSuperStructType();
2848 Expr *SuperRep;
2849
2850 if (LangOpts.MicrosoftExt) {
2851 SynthSuperContructorFunctionDecl();
2852 // Simulate a contructor call...
2853 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
2854 superType, VK_LValue,
2855 SourceLocation());
2856 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2857 InitExprs.size(),
2858 superType, VK_LValue, SourceLocation());
2859 // The code for super is a little tricky to prevent collision with
2860 // the structure definition in the header. The rewriter has it's own
2861 // internal definition (__rw_objc_super) that is uses. This is why
2862 // we need the cast below. For example:
2863 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2864 //
2865 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2866 Context->getPointerType(SuperRep->getType()),
2867 VK_RValue, OK_Ordinary,
2868 SourceLocation());
2869 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2870 Context->getPointerType(superType),
2871 CK_BitCast, SuperRep);
2872 } else {
2873 // (struct objc_super) { <exprs from above> }
2874 InitListExpr *ILE =
2875 new (Context) InitListExpr(*Context, SourceLocation(),
2876 &InitExprs[0], InitExprs.size(),
2877 SourceLocation());
2878 TypeSourceInfo *superTInfo
2879 = Context->getTrivialTypeSourceInfo(superType);
2880 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2881 superType, VK_RValue, ILE,
2882 false);
2883 }
2884 MsgExprs.push_back(SuperRep);
2885 break;
2886 }
2887
2888 case ObjCMessageExpr::Instance: {
2889 // Remove all type-casts because it may contain objc-style types; e.g.
2890 // Foo<Proto> *.
2891 Expr *recExpr = Exp->getInstanceReceiver();
2892 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2893 recExpr = CE->getSubExpr();
2894 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
2895 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
2896 ? CK_BlockPointerToObjCPointerCast
2897 : CK_CPointerToObjCPointerCast;
2898
2899 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2900 CK, recExpr);
2901 MsgExprs.push_back(recExpr);
2902 break;
2903 }
2904 }
2905
2906 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
2907 SmallVector<Expr*, 8> SelExprs;
2908 QualType argType = Context->getPointerType(Context->CharTy);
2909 SelExprs.push_back(StringLiteral::Create(*Context,
2910 Exp->getSelector().getAsString(),
2911 StringLiteral::Ascii, false,
2912 argType, SourceLocation()));
2913 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2914 &SelExprs[0], SelExprs.size(),
2915 StartLoc,
2916 EndLoc);
2917 MsgExprs.push_back(SelExp);
2918
2919 // Now push any user supplied arguments.
2920 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
2921 Expr *userExpr = Exp->getArg(i);
2922 // Make all implicit casts explicit...ICE comes in handy:-)
2923 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2924 // Reuse the ICE type, it is exactly what the doctor ordered.
2925 QualType type = ICE->getType();
2926 if (needToScanForQualifiers(type))
2927 type = Context->getObjCIdType();
2928 // Make sure we convert "type (^)(...)" to "type (*)(...)".
2929 (void)convertBlockPointerToFunctionPointer(type);
2930 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2931 CastKind CK;
2932 if (SubExpr->getType()->isIntegralType(*Context) &&
2933 type->isBooleanType()) {
2934 CK = CK_IntegralToBoolean;
2935 } else if (type->isObjCObjectPointerType()) {
2936 if (SubExpr->getType()->isBlockPointerType()) {
2937 CK = CK_BlockPointerToObjCPointerCast;
2938 } else if (SubExpr->getType()->isPointerType()) {
2939 CK = CK_CPointerToObjCPointerCast;
2940 } else {
2941 CK = CK_BitCast;
2942 }
2943 } else {
2944 CK = CK_BitCast;
2945 }
2946
2947 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
2948 }
2949 // Make id<P...> cast into an 'id' cast.
2950 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
2951 if (CE->getType()->isObjCQualifiedIdType()) {
2952 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
2953 userExpr = CE->getSubExpr();
2954 CastKind CK;
2955 if (userExpr->getType()->isIntegralType(*Context)) {
2956 CK = CK_IntegralToPointer;
2957 } else if (userExpr->getType()->isBlockPointerType()) {
2958 CK = CK_BlockPointerToObjCPointerCast;
2959 } else if (userExpr->getType()->isPointerType()) {
2960 CK = CK_CPointerToObjCPointerCast;
2961 } else {
2962 CK = CK_BitCast;
2963 }
2964 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2965 CK, userExpr);
2966 }
2967 }
2968 MsgExprs.push_back(userExpr);
2969 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2970 // out the argument in the original expression (since we aren't deleting
2971 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
2972 //Exp->setArg(i, 0);
2973 }
2974 // Generate the funky cast.
2975 CastExpr *cast;
2976 SmallVector<QualType, 8> ArgTypes;
2977 QualType returnType;
2978
2979 // Push 'id' and 'SEL', the 2 implicit arguments.
2980 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2981 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2982 else
2983 ArgTypes.push_back(Context->getObjCIdType());
2984 ArgTypes.push_back(Context->getObjCSelType());
2985 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
2986 // Push any user argument types.
2987 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2988 E = OMD->param_end(); PI != E; ++PI) {
2989 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
2990 ? Context->getObjCIdType()
2991 : (*PI)->getType();
2992 // Make sure we convert "t (^)(...)" to "t (*)(...)".
2993 (void)convertBlockPointerToFunctionPointer(t);
2994 ArgTypes.push_back(t);
2995 }
2996 returnType = Exp->getType();
2997 convertToUnqualifiedObjCType(returnType);
2998 (void)convertBlockPointerToFunctionPointer(returnType);
2999 } else {
3000 returnType = Context->getObjCIdType();
3001 }
3002 // Get the type, we will need to reference it in a couple spots.
3003 QualType msgSendType = MsgSendFlavor->getType();
3004
3005 // Create a reference to the objc_msgSend() declaration.
3006 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
3007 VK_LValue, SourceLocation());
3008
3009 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3010 // If we don't do this cast, we get the following bizarre warning/note:
3011 // xx.m:13: warning: function called through a non-compatible type
3012 // xx.m:13: note: if this code is reached, the program will abort
3013 cast = NoTypeInfoCStyleCastExpr(Context,
3014 Context->getPointerType(Context->VoidTy),
3015 CK_BitCast, DRE);
3016
3017 // Now do the "normal" pointer to function cast.
3018 QualType castType =
3019 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3020 // If we don't have a method decl, force a variadic cast.
3021 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
3022 castType = Context->getPointerType(castType);
3023 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3024 cast);
3025
3026 // Don't forget the parens to enforce the proper binding.
3027 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3028
3029 const FunctionType *FT = msgSendType->getAs<FunctionType>();
3030 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
3031 MsgExprs.size(),
3032 FT->getResultType(), VK_RValue,
3033 EndLoc);
3034 Stmt *ReplacingStmt = CE;
3035 if (MsgSendStretFlavor) {
3036 // We have the method which returns a struct/union. Must also generate
3037 // call to objc_msgSend_stret and hang both varieties on a conditional
3038 // expression which dictate which one to envoke depending on size of
3039 // method's return type.
3040
3041 // Create a reference to the objc_msgSend_stret() declaration.
3042 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
3043 VK_LValue, SourceLocation());
3044 // Need to cast objc_msgSend_stret to "void *" (see above comment).
3045 cast = NoTypeInfoCStyleCastExpr(Context,
3046 Context->getPointerType(Context->VoidTy),
3047 CK_BitCast, STDRE);
3048 // Now do the "normal" pointer to function cast.
3049 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3050 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
3051 castType = Context->getPointerType(castType);
3052 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3053 cast);
3054
3055 // Don't forget the parens to enforce the proper binding.
3056 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
3057
3058 FT = msgSendType->getAs<FunctionType>();
3059 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
3060 MsgExprs.size(),
3061 FT->getResultType(), VK_RValue,
3062 SourceLocation());
3063
3064 // Build sizeof(returnType)
3065 UnaryExprOrTypeTraitExpr *sizeofExpr =
3066 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3067 Context->getTrivialTypeSourceInfo(returnType),
3068 Context->getSizeType(), SourceLocation(),
3069 SourceLocation());
3070 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3071 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3072 // For X86 it is more complicated and some kind of target specific routine
3073 // is needed to decide what to do.
3074 unsigned IntSize =
3075 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
3076 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3077 llvm::APInt(IntSize, 8),
3078 Context->IntTy,
3079 SourceLocation());
3080 BinaryOperator *lessThanExpr =
3081 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3082 VK_RValue, OK_Ordinary, SourceLocation());
3083 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3084 ConditionalOperator *CondExpr =
3085 new (Context) ConditionalOperator(lessThanExpr,
3086 SourceLocation(), CE,
3087 SourceLocation(), STCE,
3088 returnType, VK_RValue, OK_Ordinary);
3089 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3090 CondExpr);
3091 }
3092 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3093 return ReplacingStmt;
3094}
3095
3096Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3097 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3098 Exp->getLocEnd());
3099
3100 // Now do the actual rewrite.
3101 ReplaceStmt(Exp, ReplacingStmt);
3102
3103 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3104 return ReplacingStmt;
3105}
3106
3107// typedef struct objc_object Protocol;
3108QualType RewriteModernObjC::getProtocolType() {
3109 if (!ProtocolTypeDecl) {
3110 TypeSourceInfo *TInfo
3111 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3112 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3113 SourceLocation(), SourceLocation(),
3114 &Context->Idents.get("Protocol"),
3115 TInfo);
3116 }
3117 return Context->getTypeDeclType(ProtocolTypeDecl);
3118}
3119
3120/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3121/// a synthesized/forward data reference (to the protocol's metadata).
3122/// The forward references (and metadata) are generated in
3123/// RewriteModernObjC::HandleTranslationUnit().
3124Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
3125 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3126 IdentifierInfo *ID = &Context->Idents.get(Name);
3127 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3128 SourceLocation(), ID, getProtocolType(), 0,
3129 SC_Extern, SC_None);
3130 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), VK_LValue,
3131 SourceLocation());
3132 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3133 Context->getPointerType(DRE->getType()),
3134 VK_RValue, OK_Ordinary, SourceLocation());
3135 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3136 CK_BitCast,
3137 DerefExpr);
3138 ReplaceStmt(Exp, castExpr);
3139 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3140 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3141 return castExpr;
3142
3143}
3144
3145bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3146 const char *endBuf) {
3147 while (startBuf < endBuf) {
3148 if (*startBuf == '#') {
3149 // Skip whitespace.
3150 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3151 ;
3152 if (!strncmp(startBuf, "if", strlen("if")) ||
3153 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3154 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3155 !strncmp(startBuf, "define", strlen("define")) ||
3156 !strncmp(startBuf, "undef", strlen("undef")) ||
3157 !strncmp(startBuf, "else", strlen("else")) ||
3158 !strncmp(startBuf, "elif", strlen("elif")) ||
3159 !strncmp(startBuf, "endif", strlen("endif")) ||
3160 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3161 !strncmp(startBuf, "include", strlen("include")) ||
3162 !strncmp(startBuf, "import", strlen("import")) ||
3163 !strncmp(startBuf, "include_next", strlen("include_next")))
3164 return true;
3165 }
3166 startBuf++;
3167 }
3168 return false;
3169}
3170
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003171/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3172/// It handles elaborated types, as well as enum types in the process.
3173void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3174 std::string &Result) {
3175 QualType Type = fieldDecl->getType();
3176 std::string Name = fieldDecl->getNameAsString();
3177
3178 if (Type->isRecordType()) {
3179 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3180 if (RD->isCompleteDefinition()) {
3181 if (RD->isStruct())
3182 Result += "\n\tstruct ";
3183 else if (RD->isUnion())
3184 Result += "\n\tunion ";
3185 else
3186 assert(false && "class not allowed as an ivar type");
3187
3188 Result += RD->getName();
3189 if (TagsDefinedInIvarDecls.count(RD)) {
3190 // This struct is already defined. Do not write its definition again.
3191 Result += " "; Result += Name; Result += ";\n";
3192 return;
3193 }
3194 TagsDefinedInIvarDecls.insert(RD);
3195 Result += " {\n";
3196 for (RecordDecl::field_iterator i = RD->field_begin(),
3197 e = RD->field_end(); i != e; ++i) {
3198 FieldDecl *FD = *i;
3199 RewriteObjCFieldDecl(FD, Result);
3200 }
3201 Result += "\t} ";
3202 Result += Name; Result += ";\n";
3203 return;
3204 }
3205 }
3206 else if (Type->isEnumeralType()) {
3207 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3208 if (ED->isCompleteDefinition()) {
3209 Result += "\n\tenum ";
3210 Result += ED->getName();
3211 if (TagsDefinedInIvarDecls.count(ED)) {
3212 // This enum is already defined. Do not write its definition again.
3213 Result += " "; Result += Name; Result += ";\n";
3214 return;
3215 }
3216 TagsDefinedInIvarDecls.insert(ED);
3217
3218 Result += " {\n";
3219 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3220 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3221 Result += "\t"; Result += EC->getName(); Result += " = ";
3222 llvm::APSInt Val = EC->getInitVal();
3223 Result += Val.toString(10);
3224 Result += ",\n";
3225 }
3226 Result += "\t} ";
3227 Result += Name; Result += ";\n";
3228 return;
3229 }
3230 }
3231
3232 Result += "\t";
3233 convertObjCTypeToCStyleType(Type);
3234
3235 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
3236 Result += Name;
3237 if (fieldDecl->isBitField()) {
3238 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3239 }
3240 Result += ";\n";
3241}
3242
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003243/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3244/// an objective-c class with ivars.
3245void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3246 std::string &Result) {
3247 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3248 assert(CDecl->getName() != "" &&
3249 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003250 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003251 SmallVector<ObjCIvarDecl *, 8> IVars;
3252 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003253 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003254 IVars.push_back(IVD);
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003255
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003256 SourceLocation LocStart = CDecl->getLocStart();
3257 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003258
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003259 const char *startBuf = SM->getCharacterData(LocStart);
3260 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003261
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003262 // If no ivars and no root or if its root, directly or indirectly,
3263 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003264 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003265 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3266 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3267 ReplaceText(LocStart, endBuf-startBuf, Result);
3268 return;
3269 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003270
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003271 Result += "\nstruct ";
3272 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003273 Result += "_IMPL {\n";
3274
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003275 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003276 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3277 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3278 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003279 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003280 TagsDefinedInIvarDecls.clear();
3281 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3282 RewriteObjCFieldDecl(IVars[i], Result);
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00003283
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003284 Result += "};\n";
3285 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3286 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003287 // Mark this struct as having been generated.
3288 if (!ObjCSynthesizedStructs.insert(CDecl))
3289 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003290}
3291
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003292/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3293/// have been referenced in an ivar access expression.
3294void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3295 std::string &Result) {
3296 // write out ivar offset symbols which have been referenced in an ivar
3297 // access expression.
3298 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3299 if (Ivars.empty())
3300 return;
3301 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
3302 e = Ivars.end(); i != e; i++) {
3303 ObjCIvarDecl *IvarDecl = (*i);
3304 Result += "\nextern unsigned long OBJC_IVAR_$_";
3305 Result += CDecl->getName(); Result += "_";
3306 Result += IvarDecl->getName(); Result += ";";
3307 }
3308}
3309
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003310//===----------------------------------------------------------------------===//
3311// Meta Data Emission
3312//===----------------------------------------------------------------------===//
3313
3314
3315/// RewriteImplementations - This routine rewrites all method implementations
3316/// and emits meta-data.
3317
3318void RewriteModernObjC::RewriteImplementations() {
3319 int ClsDefCount = ClassImplementation.size();
3320 int CatDefCount = CategoryImplementation.size();
3321
3322 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003323 for (int i = 0; i < ClsDefCount; i++) {
3324 ObjCImplementationDecl *OIMP = ClassImplementation[i];
3325 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
3326 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00003327 assert(false &&
3328 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003329 RewriteImplementationDecl(OIMP);
3330 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003331
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003332 for (int i = 0; i < CatDefCount; i++) {
3333 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
3334 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
3335 if (CDecl->isImplicitInterfaceDecl())
3336 assert(false &&
3337 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003338 RewriteImplementationDecl(CIMP);
3339 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003340}
3341
3342void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
3343 const std::string &Name,
3344 ValueDecl *VD, bool def) {
3345 assert(BlockByRefDeclNo.count(VD) &&
3346 "RewriteByRefString: ByRef decl missing");
3347 if (def)
3348 ResultStr += "struct ";
3349 ResultStr += "__Block_byref_" + Name +
3350 "_" + utostr(BlockByRefDeclNo[VD]) ;
3351}
3352
3353static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3354 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3355 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3356 return false;
3357}
3358
3359std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3360 StringRef funcName,
3361 std::string Tag) {
3362 const FunctionType *AFT = CE->getFunctionType();
3363 QualType RT = AFT->getResultType();
3364 std::string StructRef = "struct " + Tag;
3365 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
3366 funcName.str() + "_" + "block_func_" + utostr(i);
3367
3368 BlockDecl *BD = CE->getBlockDecl();
3369
3370 if (isa<FunctionNoProtoType>(AFT)) {
3371 // No user-supplied arguments. Still need to pass in a pointer to the
3372 // block (to reference imported block decl refs).
3373 S += "(" + StructRef + " *__cself)";
3374 } else if (BD->param_empty()) {
3375 S += "(" + StructRef + " *__cself)";
3376 } else {
3377 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
3378 assert(FT && "SynthesizeBlockFunc: No function proto");
3379 S += '(';
3380 // first add the implicit argument.
3381 S += StructRef + " *__cself, ";
3382 std::string ParamStr;
3383 for (BlockDecl::param_iterator AI = BD->param_begin(),
3384 E = BD->param_end(); AI != E; ++AI) {
3385 if (AI != BD->param_begin()) S += ", ";
3386 ParamStr = (*AI)->getNameAsString();
3387 QualType QT = (*AI)->getType();
3388 if (convertBlockPointerToFunctionPointer(QT))
3389 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
3390 else
3391 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
3392 S += ParamStr;
3393 }
3394 if (FT->isVariadic()) {
3395 if (!BD->param_empty()) S += ", ";
3396 S += "...";
3397 }
3398 S += ')';
3399 }
3400 S += " {\n";
3401
3402 // Create local declarations to avoid rewriting all closure decl ref exprs.
3403 // First, emit a declaration for all "by ref" decls.
3404 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3405 E = BlockByRefDecls.end(); I != E; ++I) {
3406 S += " ";
3407 std::string Name = (*I)->getNameAsString();
3408 std::string TypeString;
3409 RewriteByRefString(TypeString, Name, (*I));
3410 TypeString += " *";
3411 Name = TypeString + Name;
3412 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
3413 }
3414 // Next, emit a declaration for all "by copy" declarations.
3415 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3416 E = BlockByCopyDecls.end(); I != E; ++I) {
3417 S += " ";
3418 // Handle nested closure invocation. For example:
3419 //
3420 // void (^myImportedClosure)(void);
3421 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3422 //
3423 // void (^anotherClosure)(void);
3424 // anotherClosure = ^(void) {
3425 // myImportedClosure(); // import and invoke the closure
3426 // };
3427 //
3428 if (isTopLevelBlockPointerType((*I)->getType())) {
3429 RewriteBlockPointerTypeVariable(S, (*I));
3430 S += " = (";
3431 RewriteBlockPointerType(S, (*I)->getType());
3432 S += ")";
3433 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3434 }
3435 else {
3436 std::string Name = (*I)->getNameAsString();
3437 QualType QT = (*I)->getType();
3438 if (HasLocalVariableExternalStorage(*I))
3439 QT = Context->getPointerType(QT);
3440 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
3441 S += Name + " = __cself->" +
3442 (*I)->getNameAsString() + "; // bound by copy\n";
3443 }
3444 }
3445 std::string RewrittenStr = RewrittenBlockExprs[CE];
3446 const char *cstr = RewrittenStr.c_str();
3447 while (*cstr++ != '{') ;
3448 S += cstr;
3449 S += "\n";
3450 return S;
3451}
3452
3453std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3454 StringRef funcName,
3455 std::string Tag) {
3456 std::string StructRef = "struct " + Tag;
3457 std::string S = "static void __";
3458
3459 S += funcName;
3460 S += "_block_copy_" + utostr(i);
3461 S += "(" + StructRef;
3462 S += "*dst, " + StructRef;
3463 S += "*src) {";
3464 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3465 E = ImportedBlockDecls.end(); I != E; ++I) {
3466 ValueDecl *VD = (*I);
3467 S += "_Block_object_assign((void*)&dst->";
3468 S += (*I)->getNameAsString();
3469 S += ", (void*)src->";
3470 S += (*I)->getNameAsString();
3471 if (BlockByRefDeclsPtrSet.count((*I)))
3472 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3473 else if (VD->getType()->isBlockPointerType())
3474 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3475 else
3476 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3477 }
3478 S += "}\n";
3479
3480 S += "\nstatic void __";
3481 S += funcName;
3482 S += "_block_dispose_" + utostr(i);
3483 S += "(" + StructRef;
3484 S += "*src) {";
3485 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3486 E = ImportedBlockDecls.end(); I != E; ++I) {
3487 ValueDecl *VD = (*I);
3488 S += "_Block_object_dispose((void*)src->";
3489 S += (*I)->getNameAsString();
3490 if (BlockByRefDeclsPtrSet.count((*I)))
3491 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3492 else if (VD->getType()->isBlockPointerType())
3493 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3494 else
3495 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3496 }
3497 S += "}\n";
3498 return S;
3499}
3500
3501std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3502 std::string Desc) {
3503 std::string S = "\nstruct " + Tag;
3504 std::string Constructor = " " + Tag;
3505
3506 S += " {\n struct __block_impl impl;\n";
3507 S += " struct " + Desc;
3508 S += "* Desc;\n";
3509
3510 Constructor += "(void *fp, "; // Invoke function pointer.
3511 Constructor += "struct " + Desc; // Descriptor pointer.
3512 Constructor += " *desc";
3513
3514 if (BlockDeclRefs.size()) {
3515 // Output all "by copy" declarations.
3516 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3517 E = BlockByCopyDecls.end(); I != E; ++I) {
3518 S += " ";
3519 std::string FieldName = (*I)->getNameAsString();
3520 std::string ArgName = "_" + FieldName;
3521 // Handle nested closure invocation. For example:
3522 //
3523 // void (^myImportedBlock)(void);
3524 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3525 //
3526 // void (^anotherBlock)(void);
3527 // anotherBlock = ^(void) {
3528 // myImportedBlock(); // import and invoke the closure
3529 // };
3530 //
3531 if (isTopLevelBlockPointerType((*I)->getType())) {
3532 S += "struct __block_impl *";
3533 Constructor += ", void *" + ArgName;
3534 } else {
3535 QualType QT = (*I)->getType();
3536 if (HasLocalVariableExternalStorage(*I))
3537 QT = Context->getPointerType(QT);
3538 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3539 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
3540 Constructor += ", " + ArgName;
3541 }
3542 S += FieldName + ";\n";
3543 }
3544 // Output all "by ref" declarations.
3545 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3546 E = BlockByRefDecls.end(); I != E; ++I) {
3547 S += " ";
3548 std::string FieldName = (*I)->getNameAsString();
3549 std::string ArgName = "_" + FieldName;
3550 {
3551 std::string TypeString;
3552 RewriteByRefString(TypeString, FieldName, (*I));
3553 TypeString += " *";
3554 FieldName = TypeString + FieldName;
3555 ArgName = TypeString + ArgName;
3556 Constructor += ", " + ArgName;
3557 }
3558 S += FieldName + "; // by ref\n";
3559 }
3560 // Finish writing the constructor.
3561 Constructor += ", int flags=0)";
3562 // Initialize all "by copy" arguments.
3563 bool firsTime = true;
3564 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3565 E = BlockByCopyDecls.end(); I != E; ++I) {
3566 std::string Name = (*I)->getNameAsString();
3567 if (firsTime) {
3568 Constructor += " : ";
3569 firsTime = false;
3570 }
3571 else
3572 Constructor += ", ";
3573 if (isTopLevelBlockPointerType((*I)->getType()))
3574 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3575 else
3576 Constructor += Name + "(_" + Name + ")";
3577 }
3578 // Initialize all "by ref" arguments.
3579 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3580 E = BlockByRefDecls.end(); I != E; ++I) {
3581 std::string Name = (*I)->getNameAsString();
3582 if (firsTime) {
3583 Constructor += " : ";
3584 firsTime = false;
3585 }
3586 else
3587 Constructor += ", ";
3588 Constructor += Name + "(_" + Name + "->__forwarding)";
3589 }
3590
3591 Constructor += " {\n";
3592 if (GlobalVarDecl)
3593 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3594 else
3595 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3596 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3597
3598 Constructor += " Desc = desc;\n";
3599 } else {
3600 // Finish writing the constructor.
3601 Constructor += ", int flags=0) {\n";
3602 if (GlobalVarDecl)
3603 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3604 else
3605 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3606 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3607 Constructor += " Desc = desc;\n";
3608 }
3609 Constructor += " ";
3610 Constructor += "}\n";
3611 S += Constructor;
3612 S += "};\n";
3613 return S;
3614}
3615
3616std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
3617 std::string ImplTag, int i,
3618 StringRef FunName,
3619 unsigned hasCopy) {
3620 std::string S = "\nstatic struct " + DescTag;
3621
3622 S += " {\n unsigned long reserved;\n";
3623 S += " unsigned long Block_size;\n";
3624 if (hasCopy) {
3625 S += " void (*copy)(struct ";
3626 S += ImplTag; S += "*, struct ";
3627 S += ImplTag; S += "*);\n";
3628
3629 S += " void (*dispose)(struct ";
3630 S += ImplTag; S += "*);\n";
3631 }
3632 S += "} ";
3633
3634 S += DescTag + "_DATA = { 0, sizeof(struct ";
3635 S += ImplTag + ")";
3636 if (hasCopy) {
3637 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3638 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
3639 }
3640 S += "};\n";
3641 return S;
3642}
3643
3644void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3645 StringRef FunName) {
3646 // Insert declaration for the function in which block literal is used.
3647 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
3648 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
3649 bool RewriteSC = (GlobalVarDecl &&
3650 !Blocks.empty() &&
3651 GlobalVarDecl->getStorageClass() == SC_Static &&
3652 GlobalVarDecl->getType().getCVRQualifiers());
3653 if (RewriteSC) {
3654 std::string SC(" void __");
3655 SC += GlobalVarDecl->getNameAsString();
3656 SC += "() {}";
3657 InsertText(FunLocStart, SC);
3658 }
3659
3660 // Insert closures that were part of the function.
3661 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3662 CollectBlockDeclRefInfo(Blocks[i]);
3663 // Need to copy-in the inner copied-in variables not actually used in this
3664 // block.
3665 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
3666 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
3667 ValueDecl *VD = Exp->getDecl();
3668 BlockDeclRefs.push_back(Exp);
3669 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
3670 BlockByCopyDeclsPtrSet.insert(VD);
3671 BlockByCopyDecls.push_back(VD);
3672 }
3673 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
3674 BlockByRefDeclsPtrSet.insert(VD);
3675 BlockByRefDecls.push_back(VD);
3676 }
3677 // imported objects in the inner blocks not used in the outer
3678 // blocks must be copied/disposed in the outer block as well.
3679 if (Exp->isByRef() ||
3680 VD->getType()->isObjCObjectPointerType() ||
3681 VD->getType()->isBlockPointerType())
3682 ImportedBlockDecls.insert(VD);
3683 }
3684
3685 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3686 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
3687
3688 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
3689
3690 InsertText(FunLocStart, CI);
3691
3692 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
3693
3694 InsertText(FunLocStart, CF);
3695
3696 if (ImportedBlockDecls.size()) {
3697 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
3698 InsertText(FunLocStart, HF);
3699 }
3700 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3701 ImportedBlockDecls.size() > 0);
3702 InsertText(FunLocStart, BD);
3703
3704 BlockDeclRefs.clear();
3705 BlockByRefDecls.clear();
3706 BlockByRefDeclsPtrSet.clear();
3707 BlockByCopyDecls.clear();
3708 BlockByCopyDeclsPtrSet.clear();
3709 ImportedBlockDecls.clear();
3710 }
3711 if (RewriteSC) {
3712 // Must insert any 'const/volatile/static here. Since it has been
3713 // removed as result of rewriting of block literals.
3714 std::string SC;
3715 if (GlobalVarDecl->getStorageClass() == SC_Static)
3716 SC = "static ";
3717 if (GlobalVarDecl->getType().isConstQualified())
3718 SC += "const ";
3719 if (GlobalVarDecl->getType().isVolatileQualified())
3720 SC += "volatile ";
3721 if (GlobalVarDecl->getType().isRestrictQualified())
3722 SC += "restrict ";
3723 InsertText(FunLocStart, SC);
3724 }
3725
3726 Blocks.clear();
3727 InnerDeclRefsCount.clear();
3728 InnerDeclRefs.clear();
3729 RewrittenBlockExprs.clear();
3730}
3731
3732void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3733 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
3734 StringRef FuncName = FD->getName();
3735
3736 SynthesizeBlockLiterals(FunLocStart, FuncName);
3737}
3738
3739static void BuildUniqueMethodName(std::string &Name,
3740 ObjCMethodDecl *MD) {
3741 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3742 Name = IFace->getName();
3743 Name += "__" + MD->getSelector().getAsString();
3744 // Convert colons to underscores.
3745 std::string::size_type loc = 0;
3746 while ((loc = Name.find(":", loc)) != std::string::npos)
3747 Name.replace(loc, 1, "_");
3748}
3749
3750void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
3751 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3752 //SourceLocation FunLocStart = MD->getLocStart();
3753 SourceLocation FunLocStart = MD->getLocStart();
3754 std::string FuncName;
3755 BuildUniqueMethodName(FuncName, MD);
3756 SynthesizeBlockLiterals(FunLocStart, FuncName);
3757}
3758
3759void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
3760 for (Stmt::child_range CI = S->children(); CI; ++CI)
3761 if (*CI) {
3762 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3763 GetBlockDeclRefExprs(CBE->getBody());
3764 else
3765 GetBlockDeclRefExprs(*CI);
3766 }
3767 // Handle specific things.
3768 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
3769 // FIXME: Handle enums.
3770 if (!isa<FunctionDecl>(CDRE->getDecl()))
3771 BlockDeclRefs.push_back(CDRE);
3772 }
3773 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
3774 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
3775 BlockDeclRefExpr *BDRE =
3776 new (Context)BlockDeclRefExpr(cast<VarDecl>(DRE->getDecl()),
3777 DRE->getType(),
3778 VK_LValue, DRE->getLocation(), false);
3779 BlockDeclRefs.push_back(BDRE);
3780 }
3781
3782 return;
3783}
3784
3785void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
3786 SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
3787 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
3788 for (Stmt::child_range CI = S->children(); CI; ++CI)
3789 if (*CI) {
3790 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
3791 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
3792 GetInnerBlockDeclRefExprs(CBE->getBody(),
3793 InnerBlockDeclRefs,
3794 InnerContexts);
3795 }
3796 else
3797 GetInnerBlockDeclRefExprs(*CI,
3798 InnerBlockDeclRefs,
3799 InnerContexts);
3800
3801 }
3802 // Handle specific things.
3803 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
3804 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
3805 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
3806 InnerBlockDeclRefs.push_back(CDRE);
3807 }
3808 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3809 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
3810 if (Var->isFunctionOrMethodVarDecl())
3811 ImportedLocalExternalDecls.insert(Var);
3812 }
3813
3814 return;
3815}
3816
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003817/// convertObjCTypeToCStyleType - This routine converts such objc types
3818/// as qualified objects, and blocks to their closest c/c++ types that
3819/// it can. It returns true if input type was modified.
3820bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
3821 QualType oldT = T;
3822 convertBlockPointerToFunctionPointer(T);
3823 if (T->isFunctionPointerType()) {
3824 QualType PointeeTy;
3825 if (const PointerType* PT = T->getAs<PointerType>()) {
3826 PointeeTy = PT->getPointeeType();
3827 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
3828 T = convertFunctionTypeOfBlocks(FT);
3829 T = Context->getPointerType(T);
3830 }
3831 }
3832 }
3833
3834 convertToUnqualifiedObjCType(T);
3835 return T != oldT;
3836}
3837
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003838/// convertFunctionTypeOfBlocks - This routine converts a function type
3839/// whose result type may be a block pointer or whose argument type(s)
3840/// might be block pointers to an equivalent function type replacing
3841/// all block pointers to function pointers.
3842QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3843 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3844 // FTP will be null for closures that don't take arguments.
3845 // Generate a funky cast.
3846 SmallVector<QualType, 8> ArgTypes;
3847 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003848 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003849
3850 if (FTP) {
3851 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3852 E = FTP->arg_type_end(); I && (I != E); ++I) {
3853 QualType t = *I;
3854 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003855 if (convertObjCTypeToCStyleType(t))
3856 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003857 ArgTypes.push_back(t);
3858 }
3859 }
3860 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003861 if (modified)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003862 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
3863 else FuncType = QualType(FT, 0);
3864 return FuncType;
3865}
3866
3867Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
3868 // Navigate to relevant type information.
3869 const BlockPointerType *CPT = 0;
3870
3871 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
3872 CPT = DRE->getType()->getAs<BlockPointerType>();
3873 } else if (const BlockDeclRefExpr *CDRE =
3874 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
3875 CPT = CDRE->getType()->getAs<BlockPointerType>();
3876 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
3877 CPT = MExpr->getType()->getAs<BlockPointerType>();
3878 }
3879 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3880 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3881 }
3882 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3883 CPT = IEXPR->getType()->getAs<BlockPointerType>();
3884 else if (const ConditionalOperator *CEXPR =
3885 dyn_cast<ConditionalOperator>(BlockExp)) {
3886 Expr *LHSExp = CEXPR->getLHS();
3887 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3888 Expr *RHSExp = CEXPR->getRHS();
3889 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3890 Expr *CONDExp = CEXPR->getCond();
3891 ConditionalOperator *CondExpr =
3892 new (Context) ConditionalOperator(CONDExp,
3893 SourceLocation(), cast<Expr>(LHSStmt),
3894 SourceLocation(), cast<Expr>(RHSStmt),
3895 Exp->getType(), VK_RValue, OK_Ordinary);
3896 return CondExpr;
3897 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3898 CPT = IRE->getType()->getAs<BlockPointerType>();
3899 } else if (const PseudoObjectExpr *POE
3900 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3901 CPT = POE->getType()->castAs<BlockPointerType>();
3902 } else {
3903 assert(1 && "RewriteBlockClass: Bad type");
3904 }
3905 assert(CPT && "RewriteBlockClass: Bad type");
3906 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
3907 assert(FT && "RewriteBlockClass: Bad type");
3908 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3909 // FTP will be null for closures that don't take arguments.
3910
3911 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3912 SourceLocation(), SourceLocation(),
3913 &Context->Idents.get("__block_impl"));
3914 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
3915
3916 // Generate a funky cast.
3917 SmallVector<QualType, 8> ArgTypes;
3918
3919 // Push the block argument type.
3920 ArgTypes.push_back(PtrBlock);
3921 if (FTP) {
3922 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3923 E = FTP->arg_type_end(); I && (I != E); ++I) {
3924 QualType t = *I;
3925 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3926 if (!convertBlockPointerToFunctionPointer(t))
3927 convertToUnqualifiedObjCType(t);
3928 ArgTypes.push_back(t);
3929 }
3930 }
3931 // Now do the pointer to function cast.
3932 QualType PtrToFuncCastType
3933 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
3934
3935 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
3936
3937 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
3938 CK_BitCast,
3939 const_cast<Expr*>(BlockExp));
3940 // Don't forget the parens to enforce the proper binding.
3941 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3942 BlkCast);
3943 //PE->dump();
3944
3945 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3946 SourceLocation(),
3947 &Context->Idents.get("FuncPtr"),
3948 Context->VoidPtrTy, 0,
3949 /*BitWidth=*/0, /*Mutable=*/true,
3950 /*HasInit=*/false);
3951 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
3952 FD->getType(), VK_LValue,
3953 OK_Ordinary);
3954
3955
3956 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
3957 CK_BitCast, ME);
3958 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3959
3960 SmallVector<Expr*, 8> BlkExprs;
3961 // Add the implicit argument.
3962 BlkExprs.push_back(BlkCast);
3963 // Add the user arguments.
3964 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3965 E = Exp->arg_end(); I != E; ++I) {
3966 BlkExprs.push_back(*I);
3967 }
3968 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
3969 BlkExprs.size(),
3970 Exp->getType(), VK_RValue,
3971 SourceLocation());
3972 return CE;
3973}
3974
3975// We need to return the rewritten expression to handle cases where the
3976// BlockDeclRefExpr is embedded in another expression being rewritten.
3977// For example:
3978//
3979// int main() {
3980// __block Foo *f;
3981// __block int i;
3982//
3983// void (^myblock)() = ^() {
3984// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
3985// i = 77;
3986// };
3987//}
3988Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
3989 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
3990 // for each DeclRefExp where BYREFVAR is name of the variable.
3991 ValueDecl *VD;
3992 bool isArrow = true;
3993 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
3994 VD = BDRE->getDecl();
3995 else {
3996 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
3997 isArrow = false;
3998 }
3999
4000 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4001 SourceLocation(),
4002 &Context->Idents.get("__forwarding"),
4003 Context->VoidPtrTy, 0,
4004 /*BitWidth=*/0, /*Mutable=*/true,
4005 /*HasInit=*/false);
4006 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4007 FD, SourceLocation(),
4008 FD->getType(), VK_LValue,
4009 OK_Ordinary);
4010
4011 StringRef Name = VD->getName();
4012 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
4013 &Context->Idents.get(Name),
4014 Context->VoidPtrTy, 0,
4015 /*BitWidth=*/0, /*Mutable=*/true,
4016 /*HasInit=*/false);
4017 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4018 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4019
4020
4021
4022 // Need parens to enforce precedence.
4023 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4024 DeclRefExp->getExprLoc(),
4025 ME);
4026 ReplaceStmt(DeclRefExp, PE);
4027 return PE;
4028}
4029
4030// Rewrites the imported local variable V with external storage
4031// (static, extern, etc.) as *V
4032//
4033Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4034 ValueDecl *VD = DRE->getDecl();
4035 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4036 if (!ImportedLocalExternalDecls.count(Var))
4037 return DRE;
4038 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4039 VK_LValue, OK_Ordinary,
4040 DRE->getLocation());
4041 // Need parens to enforce precedence.
4042 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4043 Exp);
4044 ReplaceStmt(DRE, PE);
4045 return PE;
4046}
4047
4048void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4049 SourceLocation LocStart = CE->getLParenLoc();
4050 SourceLocation LocEnd = CE->getRParenLoc();
4051
4052 // Need to avoid trying to rewrite synthesized casts.
4053 if (LocStart.isInvalid())
4054 return;
4055 // Need to avoid trying to rewrite casts contained in macros.
4056 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4057 return;
4058
4059 const char *startBuf = SM->getCharacterData(LocStart);
4060 const char *endBuf = SM->getCharacterData(LocEnd);
4061 QualType QT = CE->getType();
4062 const Type* TypePtr = QT->getAs<Type>();
4063 if (isa<TypeOfExprType>(TypePtr)) {
4064 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4065 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4066 std::string TypeAsString = "(";
4067 RewriteBlockPointerType(TypeAsString, QT);
4068 TypeAsString += ")";
4069 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4070 return;
4071 }
4072 // advance the location to startArgList.
4073 const char *argPtr = startBuf;
4074
4075 while (*argPtr++ && (argPtr < endBuf)) {
4076 switch (*argPtr) {
4077 case '^':
4078 // Replace the '^' with '*'.
4079 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4080 ReplaceText(LocStart, 1, "*");
4081 break;
4082 }
4083 }
4084 return;
4085}
4086
4087void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4088 SourceLocation DeclLoc = FD->getLocation();
4089 unsigned parenCount = 0;
4090
4091 // We have 1 or more arguments that have closure pointers.
4092 const char *startBuf = SM->getCharacterData(DeclLoc);
4093 const char *startArgList = strchr(startBuf, '(');
4094
4095 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4096
4097 parenCount++;
4098 // advance the location to startArgList.
4099 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4100 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4101
4102 const char *argPtr = startArgList;
4103
4104 while (*argPtr++ && parenCount) {
4105 switch (*argPtr) {
4106 case '^':
4107 // Replace the '^' with '*'.
4108 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4109 ReplaceText(DeclLoc, 1, "*");
4110 break;
4111 case '(':
4112 parenCount++;
4113 break;
4114 case ')':
4115 parenCount--;
4116 break;
4117 }
4118 }
4119 return;
4120}
4121
4122bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4123 const FunctionProtoType *FTP;
4124 const PointerType *PT = QT->getAs<PointerType>();
4125 if (PT) {
4126 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4127 } else {
4128 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4129 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4130 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4131 }
4132 if (FTP) {
4133 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4134 E = FTP->arg_type_end(); I != E; ++I)
4135 if (isTopLevelBlockPointerType(*I))
4136 return true;
4137 }
4138 return false;
4139}
4140
4141bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4142 const FunctionProtoType *FTP;
4143 const PointerType *PT = QT->getAs<PointerType>();
4144 if (PT) {
4145 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4146 } else {
4147 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4148 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4149 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4150 }
4151 if (FTP) {
4152 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4153 E = FTP->arg_type_end(); I != E; ++I) {
4154 if ((*I)->isObjCQualifiedIdType())
4155 return true;
4156 if ((*I)->isObjCObjectPointerType() &&
4157 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4158 return true;
4159 }
4160
4161 }
4162 return false;
4163}
4164
4165void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4166 const char *&RParen) {
4167 const char *argPtr = strchr(Name, '(');
4168 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4169
4170 LParen = argPtr; // output the start.
4171 argPtr++; // skip past the left paren.
4172 unsigned parenCount = 1;
4173
4174 while (*argPtr && parenCount) {
4175 switch (*argPtr) {
4176 case '(': parenCount++; break;
4177 case ')': parenCount--; break;
4178 default: break;
4179 }
4180 if (parenCount) argPtr++;
4181 }
4182 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4183 RParen = argPtr; // output the end
4184}
4185
4186void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4187 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4188 RewriteBlockPointerFunctionArgs(FD);
4189 return;
4190 }
4191 // Handle Variables and Typedefs.
4192 SourceLocation DeclLoc = ND->getLocation();
4193 QualType DeclT;
4194 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4195 DeclT = VD->getType();
4196 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4197 DeclT = TDD->getUnderlyingType();
4198 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4199 DeclT = FD->getType();
4200 else
4201 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4202
4203 const char *startBuf = SM->getCharacterData(DeclLoc);
4204 const char *endBuf = startBuf;
4205 // scan backward (from the decl location) for the end of the previous decl.
4206 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4207 startBuf--;
4208 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4209 std::string buf;
4210 unsigned OrigLength=0;
4211 // *startBuf != '^' if we are dealing with a pointer to function that
4212 // may take block argument types (which will be handled below).
4213 if (*startBuf == '^') {
4214 // Replace the '^' with '*', computing a negative offset.
4215 buf = '*';
4216 startBuf++;
4217 OrigLength++;
4218 }
4219 while (*startBuf != ')') {
4220 buf += *startBuf;
4221 startBuf++;
4222 OrigLength++;
4223 }
4224 buf += ')';
4225 OrigLength++;
4226
4227 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4228 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4229 // Replace the '^' with '*' for arguments.
4230 // Replace id<P> with id/*<>*/
4231 DeclLoc = ND->getLocation();
4232 startBuf = SM->getCharacterData(DeclLoc);
4233 const char *argListBegin, *argListEnd;
4234 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4235 while (argListBegin < argListEnd) {
4236 if (*argListBegin == '^')
4237 buf += '*';
4238 else if (*argListBegin == '<') {
4239 buf += "/*";
4240 buf += *argListBegin++;
4241 OrigLength++;;
4242 while (*argListBegin != '>') {
4243 buf += *argListBegin++;
4244 OrigLength++;
4245 }
4246 buf += *argListBegin;
4247 buf += "*/";
4248 }
4249 else
4250 buf += *argListBegin;
4251 argListBegin++;
4252 OrigLength++;
4253 }
4254 buf += ')';
4255 OrigLength++;
4256 }
4257 ReplaceText(Start, OrigLength, buf);
4258
4259 return;
4260}
4261
4262
4263/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4264/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4265/// struct Block_byref_id_object *src) {
4266/// _Block_object_assign (&_dest->object, _src->object,
4267/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4268/// [|BLOCK_FIELD_IS_WEAK]) // object
4269/// _Block_object_assign(&_dest->object, _src->object,
4270/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4271/// [|BLOCK_FIELD_IS_WEAK]) // block
4272/// }
4273/// And:
4274/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4275/// _Block_object_dispose(_src->object,
4276/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4277/// [|BLOCK_FIELD_IS_WEAK]) // object
4278/// _Block_object_dispose(_src->object,
4279/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4280/// [|BLOCK_FIELD_IS_WEAK]) // block
4281/// }
4282
4283std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4284 int flag) {
4285 std::string S;
4286 if (CopyDestroyCache.count(flag))
4287 return S;
4288 CopyDestroyCache.insert(flag);
4289 S = "static void __Block_byref_id_object_copy_";
4290 S += utostr(flag);
4291 S += "(void *dst, void *src) {\n";
4292
4293 // offset into the object pointer is computed as:
4294 // void * + void* + int + int + void* + void *
4295 unsigned IntSize =
4296 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4297 unsigned VoidPtrSize =
4298 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4299
4300 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4301 S += " _Block_object_assign((char*)dst + ";
4302 S += utostr(offset);
4303 S += ", *(void * *) ((char*)src + ";
4304 S += utostr(offset);
4305 S += "), ";
4306 S += utostr(flag);
4307 S += ");\n}\n";
4308
4309 S += "static void __Block_byref_id_object_dispose_";
4310 S += utostr(flag);
4311 S += "(void *src) {\n";
4312 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4313 S += utostr(offset);
4314 S += "), ";
4315 S += utostr(flag);
4316 S += ");\n}\n";
4317 return S;
4318}
4319
4320/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4321/// the declaration into:
4322/// struct __Block_byref_ND {
4323/// void *__isa; // NULL for everything except __weak pointers
4324/// struct __Block_byref_ND *__forwarding;
4325/// int32_t __flags;
4326/// int32_t __size;
4327/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4328/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4329/// typex ND;
4330/// };
4331///
4332/// It then replaces declaration of ND variable with:
4333/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4334/// __size=sizeof(struct __Block_byref_ND),
4335/// ND=initializer-if-any};
4336///
4337///
4338void RewriteModernObjC::RewriteByRefVar(VarDecl *ND) {
4339 // Insert declaration for the function in which block literal is
4340 // used.
4341 if (CurFunctionDeclToDeclareForBlock)
4342 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
4343 int flag = 0;
4344 int isa = 0;
4345 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4346 if (DeclLoc.isInvalid())
4347 // If type location is missing, it is because of missing type (a warning).
4348 // Use variable's location which is good for this case.
4349 DeclLoc = ND->getLocation();
4350 const char *startBuf = SM->getCharacterData(DeclLoc);
4351 SourceLocation X = ND->getLocEnd();
4352 X = SM->getExpansionLoc(X);
4353 const char *endBuf = SM->getCharacterData(X);
4354 std::string Name(ND->getNameAsString());
4355 std::string ByrefType;
4356 RewriteByRefString(ByrefType, Name, ND, true);
4357 ByrefType += " {\n";
4358 ByrefType += " void *__isa;\n";
4359 RewriteByRefString(ByrefType, Name, ND);
4360 ByrefType += " *__forwarding;\n";
4361 ByrefType += " int __flags;\n";
4362 ByrefType += " int __size;\n";
4363 // Add void *__Block_byref_id_object_copy;
4364 // void *__Block_byref_id_object_dispose; if needed.
4365 QualType Ty = ND->getType();
4366 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4367 if (HasCopyAndDispose) {
4368 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4369 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4370 }
4371
4372 QualType T = Ty;
4373 (void)convertBlockPointerToFunctionPointer(T);
4374 T.getAsStringInternal(Name, Context->getPrintingPolicy());
4375
4376 ByrefType += " " + Name + ";\n";
4377 ByrefType += "};\n";
4378 // Insert this type in global scope. It is needed by helper function.
4379 SourceLocation FunLocStart;
4380 if (CurFunctionDef)
4381 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4382 else {
4383 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4384 FunLocStart = CurMethodDef->getLocStart();
4385 }
4386 InsertText(FunLocStart, ByrefType);
4387 if (Ty.isObjCGCWeak()) {
4388 flag |= BLOCK_FIELD_IS_WEAK;
4389 isa = 1;
4390 }
4391
4392 if (HasCopyAndDispose) {
4393 flag = BLOCK_BYREF_CALLER;
4394 QualType Ty = ND->getType();
4395 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4396 if (Ty->isBlockPointerType())
4397 flag |= BLOCK_FIELD_IS_BLOCK;
4398 else
4399 flag |= BLOCK_FIELD_IS_OBJECT;
4400 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
4401 if (!HF.empty())
4402 InsertText(FunLocStart, HF);
4403 }
4404
4405 // struct __Block_byref_ND ND =
4406 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4407 // initializer-if-any};
4408 bool hasInit = (ND->getInit() != 0);
4409 unsigned flags = 0;
4410 if (HasCopyAndDispose)
4411 flags |= BLOCK_HAS_COPY_DISPOSE;
4412 Name = ND->getNameAsString();
4413 ByrefType.clear();
4414 RewriteByRefString(ByrefType, Name, ND);
4415 std::string ForwardingCastType("(");
4416 ForwardingCastType += ByrefType + " *)";
4417 if (!hasInit) {
4418 ByrefType += " " + Name + " = {(void*)";
4419 ByrefType += utostr(isa);
4420 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4421 ByrefType += utostr(flags);
4422 ByrefType += ", ";
4423 ByrefType += "sizeof(";
4424 RewriteByRefString(ByrefType, Name, ND);
4425 ByrefType += ")";
4426 if (HasCopyAndDispose) {
4427 ByrefType += ", __Block_byref_id_object_copy_";
4428 ByrefType += utostr(flag);
4429 ByrefType += ", __Block_byref_id_object_dispose_";
4430 ByrefType += utostr(flag);
4431 }
4432 ByrefType += "};\n";
4433 unsigned nameSize = Name.size();
4434 // for block or function pointer declaration. Name is aleady
4435 // part of the declaration.
4436 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4437 nameSize = 1;
4438 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
4439 }
4440 else {
4441 SourceLocation startLoc;
4442 Expr *E = ND->getInit();
4443 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4444 startLoc = ECE->getLParenLoc();
4445 else
4446 startLoc = E->getLocStart();
4447 startLoc = SM->getExpansionLoc(startLoc);
4448 endBuf = SM->getCharacterData(startLoc);
4449 ByrefType += " " + Name;
4450 ByrefType += " = {(void*)";
4451 ByrefType += utostr(isa);
4452 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4453 ByrefType += utostr(flags);
4454 ByrefType += ", ";
4455 ByrefType += "sizeof(";
4456 RewriteByRefString(ByrefType, Name, ND);
4457 ByrefType += "), ";
4458 if (HasCopyAndDispose) {
4459 ByrefType += "__Block_byref_id_object_copy_";
4460 ByrefType += utostr(flag);
4461 ByrefType += ", __Block_byref_id_object_dispose_";
4462 ByrefType += utostr(flag);
4463 ByrefType += ", ";
4464 }
4465 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
4466
4467 // Complete the newly synthesized compound expression by inserting a right
4468 // curly brace before the end of the declaration.
4469 // FIXME: This approach avoids rewriting the initializer expression. It
4470 // also assumes there is only one declarator. For example, the following
4471 // isn't currently supported by this routine (in general):
4472 //
4473 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4474 //
4475 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4476 const char *semiBuf = strchr(startInitializerBuf, ';');
4477 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4478 SourceLocation semiLoc =
4479 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
4480
4481 InsertText(semiLoc, "}");
4482 }
4483 return;
4484}
4485
4486void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4487 // Add initializers for any closure decl refs.
4488 GetBlockDeclRefExprs(Exp->getBody());
4489 if (BlockDeclRefs.size()) {
4490 // Unique all "by copy" declarations.
4491 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4492 if (!BlockDeclRefs[i]->isByRef()) {
4493 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4494 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4495 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4496 }
4497 }
4498 // Unique all "by ref" declarations.
4499 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4500 if (BlockDeclRefs[i]->isByRef()) {
4501 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4502 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4503 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4504 }
4505 }
4506 // Find any imported blocks...they will need special attention.
4507 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4508 if (BlockDeclRefs[i]->isByRef() ||
4509 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4510 BlockDeclRefs[i]->getType()->isBlockPointerType())
4511 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4512 }
4513}
4514
4515FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
4516 IdentifierInfo *ID = &Context->Idents.get(name);
4517 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
4518 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4519 SourceLocation(), ID, FType, 0, SC_Extern,
4520 SC_None, false, false);
4521}
4522
4523Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
4524 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
4525 const BlockDecl *block = Exp->getBlockDecl();
4526 Blocks.push_back(Exp);
4527
4528 CollectBlockDeclRefInfo(Exp);
4529
4530 // Add inner imported variables now used in current block.
4531 int countOfInnerDecls = 0;
4532 if (!InnerBlockDeclRefs.empty()) {
4533 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
4534 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
4535 ValueDecl *VD = Exp->getDecl();
4536 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4537 // We need to save the copied-in variables in nested
4538 // blocks because it is needed at the end for some of the API generations.
4539 // See SynthesizeBlockLiterals routine.
4540 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4541 BlockDeclRefs.push_back(Exp);
4542 BlockByCopyDeclsPtrSet.insert(VD);
4543 BlockByCopyDecls.push_back(VD);
4544 }
4545 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4546 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4547 BlockDeclRefs.push_back(Exp);
4548 BlockByRefDeclsPtrSet.insert(VD);
4549 BlockByRefDecls.push_back(VD);
4550 }
4551 }
4552 // Find any imported blocks...they will need special attention.
4553 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
4554 if (InnerBlockDeclRefs[i]->isByRef() ||
4555 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4556 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4557 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
4558 }
4559 InnerDeclRefsCount.push_back(countOfInnerDecls);
4560
4561 std::string FuncName;
4562
4563 if (CurFunctionDef)
4564 FuncName = CurFunctionDef->getNameAsString();
4565 else if (CurMethodDef)
4566 BuildUniqueMethodName(FuncName, CurMethodDef);
4567 else if (GlobalVarDecl)
4568 FuncName = std::string(GlobalVarDecl->getNameAsString());
4569
4570 std::string BlockNumber = utostr(Blocks.size()-1);
4571
4572 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4573 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4574
4575 // Get a pointer to the function type so we can cast appropriately.
4576 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4577 QualType FType = Context->getPointerType(BFT);
4578
4579 FunctionDecl *FD;
4580 Expr *NewRep;
4581
4582 // Simulate a contructor call...
4583 FD = SynthBlockInitFunctionDecl(Tag);
4584 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, VK_RValue,
4585 SourceLocation());
4586
4587 SmallVector<Expr*, 4> InitExprs;
4588
4589 // Initialize the block function.
4590 FD = SynthBlockInitFunctionDecl(Func);
4591 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4592 SourceLocation());
4593 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4594 CK_BitCast, Arg);
4595 InitExprs.push_back(castExpr);
4596
4597 // Initialize the block descriptor.
4598 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
4599
4600 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
4601 SourceLocation(), SourceLocation(),
4602 &Context->Idents.get(DescData.c_str()),
4603 Context->VoidPtrTy, 0,
4604 SC_Static, SC_None);
4605 UnaryOperator *DescRefExpr =
4606 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD,
4607 Context->VoidPtrTy,
4608 VK_LValue,
4609 SourceLocation()),
4610 UO_AddrOf,
4611 Context->getPointerType(Context->VoidPtrTy),
4612 VK_RValue, OK_Ordinary,
4613 SourceLocation());
4614 InitExprs.push_back(DescRefExpr);
4615
4616 // Add initializers for any closure decl refs.
4617 if (BlockDeclRefs.size()) {
4618 Expr *Exp;
4619 // Output all "by copy" declarations.
4620 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4621 E = BlockByCopyDecls.end(); I != E; ++I) {
4622 if (isObjCType((*I)->getType())) {
4623 // FIXME: Conform to ABI ([[obj retain] autorelease]).
4624 FD = SynthBlockInitFunctionDecl((*I)->getName());
4625 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4626 SourceLocation());
4627 if (HasLocalVariableExternalStorage(*I)) {
4628 QualType QT = (*I)->getType();
4629 QT = Context->getPointerType(QT);
4630 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4631 OK_Ordinary, SourceLocation());
4632 }
4633 } else if (isTopLevelBlockPointerType((*I)->getType())) {
4634 FD = SynthBlockInitFunctionDecl((*I)->getName());
4635 Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4636 SourceLocation());
4637 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4638 CK_BitCast, Arg);
4639 } else {
4640 FD = SynthBlockInitFunctionDecl((*I)->getName());
4641 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4642 SourceLocation());
4643 if (HasLocalVariableExternalStorage(*I)) {
4644 QualType QT = (*I)->getType();
4645 QT = Context->getPointerType(QT);
4646 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4647 OK_Ordinary, SourceLocation());
4648 }
4649
4650 }
4651 InitExprs.push_back(Exp);
4652 }
4653 // Output all "by ref" declarations.
4654 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4655 E = BlockByRefDecls.end(); I != E; ++I) {
4656 ValueDecl *ND = (*I);
4657 std::string Name(ND->getNameAsString());
4658 std::string RecName;
4659 RewriteByRefString(RecName, Name, ND, true);
4660 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4661 + sizeof("struct"));
4662 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4663 SourceLocation(), SourceLocation(),
4664 II);
4665 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4666 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4667
4668 FD = SynthBlockInitFunctionDecl((*I)->getName());
4669 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4670 SourceLocation());
4671 bool isNestedCapturedVar = false;
4672 if (block)
4673 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
4674 ce = block->capture_end(); ci != ce; ++ci) {
4675 const VarDecl *variable = ci->getVariable();
4676 if (variable == ND && ci->isNested()) {
4677 assert (ci->isByRef() &&
4678 "SynthBlockInitExpr - captured block variable is not byref");
4679 isNestedCapturedVar = true;
4680 break;
4681 }
4682 }
4683 // captured nested byref variable has its address passed. Do not take
4684 // its address again.
4685 if (!isNestedCapturedVar)
4686 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
4687 Context->getPointerType(Exp->getType()),
4688 VK_RValue, OK_Ordinary, SourceLocation());
4689 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
4690 InitExprs.push_back(Exp);
4691 }
4692 }
4693 if (ImportedBlockDecls.size()) {
4694 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4695 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
4696 unsigned IntSize =
4697 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4698 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4699 Context->IntTy, SourceLocation());
4700 InitExprs.push_back(FlagExp);
4701 }
4702 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4703 FType, VK_LValue, SourceLocation());
4704 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
4705 Context->getPointerType(NewRep->getType()),
4706 VK_RValue, OK_Ordinary, SourceLocation());
4707 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
4708 NewRep);
4709 BlockDeclRefs.clear();
4710 BlockByRefDecls.clear();
4711 BlockByRefDeclsPtrSet.clear();
4712 BlockByCopyDecls.clear();
4713 BlockByCopyDeclsPtrSet.clear();
4714 ImportedBlockDecls.clear();
4715 return NewRep;
4716}
4717
4718bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4719 if (const ObjCForCollectionStmt * CS =
4720 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4721 return CS->getElement() == DS;
4722 return false;
4723}
4724
4725//===----------------------------------------------------------------------===//
4726// Function Body / Expression rewriting
4727//===----------------------------------------------------------------------===//
4728
4729Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4730 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4731 isa<DoStmt>(S) || isa<ForStmt>(S))
4732 Stmts.push_back(S);
4733 else if (isa<ObjCForCollectionStmt>(S)) {
4734 Stmts.push_back(S);
4735 ObjCBcLabelNo.push_back(++BcLabelCount);
4736 }
4737
4738 // Pseudo-object operations and ivar references need special
4739 // treatment because we're going to recursively rewrite them.
4740 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4741 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4742 return RewritePropertyOrImplicitSetter(PseudoOp);
4743 } else {
4744 return RewritePropertyOrImplicitGetter(PseudoOp);
4745 }
4746 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4747 return RewriteObjCIvarRefExpr(IvarRefExpr);
4748 }
4749
4750 SourceRange OrigStmtRange = S->getSourceRange();
4751
4752 // Perform a bottom up rewrite of all children.
4753 for (Stmt::child_range CI = S->children(); CI; ++CI)
4754 if (*CI) {
4755 Stmt *childStmt = (*CI);
4756 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
4757 if (newStmt) {
4758 *CI = newStmt;
4759 }
4760 }
4761
4762 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4763 SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
4764 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4765 InnerContexts.insert(BE->getBlockDecl());
4766 ImportedLocalExternalDecls.clear();
4767 GetInnerBlockDeclRefExprs(BE->getBody(),
4768 InnerBlockDeclRefs, InnerContexts);
4769 // Rewrite the block body in place.
4770 Stmt *SaveCurrentBody = CurrentBody;
4771 CurrentBody = BE->getBody();
4772 PropParentMap = 0;
4773 // block literal on rhs of a property-dot-sytax assignment
4774 // must be replaced by its synthesize ast so getRewrittenText
4775 // works as expected. In this case, what actually ends up on RHS
4776 // is the blockTranscribed which is the helper function for the
4777 // block literal; as in: self.c = ^() {[ace ARR];};
4778 bool saveDisableReplaceStmt = DisableReplaceStmt;
4779 DisableReplaceStmt = false;
4780 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4781 DisableReplaceStmt = saveDisableReplaceStmt;
4782 CurrentBody = SaveCurrentBody;
4783 PropParentMap = 0;
4784 ImportedLocalExternalDecls.clear();
4785 // Now we snarf the rewritten text and stash it away for later use.
4786 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
4787 RewrittenBlockExprs[BE] = Str;
4788
4789 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4790
4791 //blockTranscribed->dump();
4792 ReplaceStmt(S, blockTranscribed);
4793 return blockTranscribed;
4794 }
4795 // Handle specific things.
4796 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4797 return RewriteAtEncode(AtEncode);
4798
4799 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4800 return RewriteAtSelector(AtSelector);
4801
4802 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4803 return RewriteObjCStringLiteral(AtString);
4804
4805 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
4806#if 0
4807 // Before we rewrite it, put the original message expression in a comment.
4808 SourceLocation startLoc = MessExpr->getLocStart();
4809 SourceLocation endLoc = MessExpr->getLocEnd();
4810
4811 const char *startBuf = SM->getCharacterData(startLoc);
4812 const char *endBuf = SM->getCharacterData(endLoc);
4813
4814 std::string messString;
4815 messString += "// ";
4816 messString.append(startBuf, endBuf-startBuf+1);
4817 messString += "\n";
4818
4819 // FIXME: Missing definition of
4820 // InsertText(clang::SourceLocation, char const*, unsigned int).
4821 // InsertText(startLoc, messString.c_str(), messString.size());
4822 // Tried this, but it didn't work either...
4823 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
4824#endif
4825 return RewriteMessageExpr(MessExpr);
4826 }
4827
4828 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4829 return RewriteObjCTryStmt(StmtTry);
4830
4831 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4832 return RewriteObjCSynchronizedStmt(StmtTry);
4833
4834 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4835 return RewriteObjCThrowStmt(StmtThrow);
4836
4837 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4838 return RewriteObjCProtocolExpr(ProtocolExp);
4839
4840 if (ObjCForCollectionStmt *StmtForCollection =
4841 dyn_cast<ObjCForCollectionStmt>(S))
4842 return RewriteObjCForCollectionStmt(StmtForCollection,
4843 OrigStmtRange.getEnd());
4844 if (BreakStmt *StmtBreakStmt =
4845 dyn_cast<BreakStmt>(S))
4846 return RewriteBreakStmt(StmtBreakStmt);
4847 if (ContinueStmt *StmtContinueStmt =
4848 dyn_cast<ContinueStmt>(S))
4849 return RewriteContinueStmt(StmtContinueStmt);
4850
4851 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4852 // and cast exprs.
4853 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4854 // FIXME: What we're doing here is modifying the type-specifier that
4855 // precedes the first Decl. In the future the DeclGroup should have
4856 // a separate type-specifier that we can rewrite.
4857 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4858 // the context of an ObjCForCollectionStmt. For example:
4859 // NSArray *someArray;
4860 // for (id <FooProtocol> index in someArray) ;
4861 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4862 // and it depends on the original text locations/positions.
4863 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
4864 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4865
4866 // Blocks rewrite rules.
4867 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4868 DI != DE; ++DI) {
4869 Decl *SD = *DI;
4870 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
4871 if (isTopLevelBlockPointerType(ND->getType()))
4872 RewriteBlockPointerDecl(ND);
4873 else if (ND->getType()->isFunctionPointerType())
4874 CheckFunctionPointerDecl(ND->getType(), ND);
4875 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
4876 if (VD->hasAttr<BlocksAttr>()) {
4877 static unsigned uniqueByrefDeclCount = 0;
4878 assert(!BlockByRefDeclNo.count(ND) &&
4879 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4880 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
4881 RewriteByRefVar(VD);
4882 }
4883 else
4884 RewriteTypeOfDecl(VD);
4885 }
4886 }
4887 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
4888 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4889 RewriteBlockPointerDecl(TD);
4890 else if (TD->getUnderlyingType()->isFunctionPointerType())
4891 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4892 }
4893 }
4894 }
4895
4896 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4897 RewriteObjCQualifiedInterfaceTypes(CE);
4898
4899 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4900 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4901 assert(!Stmts.empty() && "Statement stack is empty");
4902 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4903 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4904 && "Statement stack mismatch");
4905 Stmts.pop_back();
4906 }
4907 // Handle blocks rewriting.
4908 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4909 if (BDRE->isByRef())
4910 return RewriteBlockDeclRefExpr(BDRE);
4911 }
4912 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4913 ValueDecl *VD = DRE->getDecl();
4914 if (VD->hasAttr<BlocksAttr>())
4915 return RewriteBlockDeclRefExpr(DRE);
4916 if (HasLocalVariableExternalStorage(VD))
4917 return RewriteLocalVariableExternalStorage(DRE);
4918 }
4919
4920 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4921 if (CE->getCallee()->getType()->isBlockPointerType()) {
4922 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
4923 ReplaceStmt(S, BlockCall);
4924 return BlockCall;
4925 }
4926 }
4927 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
4928 RewriteCastExpr(CE);
4929 }
4930#if 0
4931 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4932 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4933 ICE->getSubExpr(),
4934 SourceLocation());
4935 // Get the new text.
4936 std::string SStr;
4937 llvm::raw_string_ostream Buf(SStr);
4938 Replacement->printPretty(Buf, *Context);
4939 const std::string &Str = Buf.str();
4940
4941 printf("CAST = %s\n", &Str[0]);
4942 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4943 delete S;
4944 return Replacement;
4945 }
4946#endif
4947 // Return this stmt unmodified.
4948 return S;
4949}
4950
4951void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
4952 for (RecordDecl::field_iterator i = RD->field_begin(),
4953 e = RD->field_end(); i != e; ++i) {
4954 FieldDecl *FD = *i;
4955 if (isTopLevelBlockPointerType(FD->getType()))
4956 RewriteBlockPointerDecl(FD);
4957 if (FD->getType()->isObjCQualifiedIdType() ||
4958 FD->getType()->isObjCQualifiedInterfaceType())
4959 RewriteObjCQualifiedInterfaceTypes(FD);
4960 }
4961}
4962
4963/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4964/// main file of the input.
4965void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
4966 switch (D->getKind()) {
4967 case Decl::Function: {
4968 FunctionDecl *FD = cast<FunctionDecl>(D);
4969 if (FD->isOverloadedOperator())
4970 return;
4971
4972 // Since function prototypes don't have ParmDecl's, we check the function
4973 // prototype. This enables us to rewrite function declarations and
4974 // definitions using the same code.
4975 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
4976
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00004977 if (!FD->isThisDeclarationADefinition())
4978 break;
4979
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004980 // FIXME: If this should support Obj-C++, support CXXTryStmt
4981 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4982 CurFunctionDef = FD;
4983 CurFunctionDeclToDeclareForBlock = FD;
4984 CurrentBody = Body;
4985 Body =
4986 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4987 FD->setBody(Body);
4988 CurrentBody = 0;
4989 if (PropParentMap) {
4990 delete PropParentMap;
4991 PropParentMap = 0;
4992 }
4993 // This synthesizes and inserts the block "impl" struct, invoke function,
4994 // and any copy/dispose helper functions.
4995 InsertBlockLiteralsWithinFunction(FD);
4996 CurFunctionDef = 0;
4997 CurFunctionDeclToDeclareForBlock = 0;
4998 }
4999 break;
5000 }
5001 case Decl::ObjCMethod: {
5002 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5003 if (CompoundStmt *Body = MD->getCompoundBody()) {
5004 CurMethodDef = MD;
5005 CurrentBody = Body;
5006 Body =
5007 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5008 MD->setBody(Body);
5009 CurrentBody = 0;
5010 if (PropParentMap) {
5011 delete PropParentMap;
5012 PropParentMap = 0;
5013 }
5014 InsertBlockLiteralsWithinMethod(MD);
5015 CurMethodDef = 0;
5016 }
5017 break;
5018 }
5019 case Decl::ObjCImplementation: {
5020 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5021 ClassImplementation.push_back(CI);
5022 break;
5023 }
5024 case Decl::ObjCCategoryImpl: {
5025 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5026 CategoryImplementation.push_back(CI);
5027 break;
5028 }
5029 case Decl::Var: {
5030 VarDecl *VD = cast<VarDecl>(D);
5031 RewriteObjCQualifiedInterfaceTypes(VD);
5032 if (isTopLevelBlockPointerType(VD->getType()))
5033 RewriteBlockPointerDecl(VD);
5034 else if (VD->getType()->isFunctionPointerType()) {
5035 CheckFunctionPointerDecl(VD->getType(), VD);
5036 if (VD->getInit()) {
5037 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5038 RewriteCastExpr(CE);
5039 }
5040 }
5041 } else if (VD->getType()->isRecordType()) {
5042 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5043 if (RD->isCompleteDefinition())
5044 RewriteRecordBody(RD);
5045 }
5046 if (VD->getInit()) {
5047 GlobalVarDecl = VD;
5048 CurrentBody = VD->getInit();
5049 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5050 CurrentBody = 0;
5051 if (PropParentMap) {
5052 delete PropParentMap;
5053 PropParentMap = 0;
5054 }
5055 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5056 GlobalVarDecl = 0;
5057
5058 // This is needed for blocks.
5059 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5060 RewriteCastExpr(CE);
5061 }
5062 }
5063 break;
5064 }
5065 case Decl::TypeAlias:
5066 case Decl::Typedef: {
5067 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5068 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5069 RewriteBlockPointerDecl(TD);
5070 else if (TD->getUnderlyingType()->isFunctionPointerType())
5071 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5072 }
5073 break;
5074 }
5075 case Decl::CXXRecord:
5076 case Decl::Record: {
5077 RecordDecl *RD = cast<RecordDecl>(D);
5078 if (RD->isCompleteDefinition())
5079 RewriteRecordBody(RD);
5080 break;
5081 }
5082 default:
5083 break;
5084 }
5085 // Nothing yet.
5086}
5087
5088void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5089 if (Diags.hasErrorOccurred())
5090 return;
5091
5092 RewriteInclude();
5093
5094 // Here's a great place to add any extra declarations that may be needed.
5095 // Write out meta data for each @protocol(<expr>).
5096 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
5097 E = ProtocolExprDecls.end(); I != E; ++I)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005098 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005099
5100 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian57317782012-02-21 23:58:41 +00005101 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5102 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5103 // Write struct declaration for the class matching its ivar declarations.
5104 // Note that for modern abi, this is postponed until the end of TU
5105 // because class extensions and the implementation might declare their own
5106 // private ivars.
5107 RewriteInterfaceDecl(CDecl);
5108 }
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00005109
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005110 if (ClassImplementation.size() || CategoryImplementation.size())
5111 RewriteImplementations();
5112
5113 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5114 // we are done.
5115 if (const RewriteBuffer *RewriteBuf =
5116 Rewrite.getRewriteBufferFor(MainFileID)) {
5117 //printf("Changed:\n");
5118 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5119 } else {
5120 llvm::errs() << "No changes\n";
5121 }
5122
5123 if (ClassImplementation.size() || CategoryImplementation.size() ||
5124 ProtocolExprDecls.size()) {
5125 // Rewrite Objective-c meta data*
5126 std::string ResultStr;
5127 RewriteMetaDataIntoBuffer(ResultStr);
5128 // Emit metadata.
5129 *OutFile << ResultStr;
5130 }
5131 OutFile->flush();
5132}
5133
5134void RewriteModernObjC::Initialize(ASTContext &context) {
5135 InitializeCommon(context);
5136
5137 // declaring objc_selector outside the parameter list removes a silly
5138 // scope related warning...
5139 if (IsHeader)
5140 Preamble = "#pragma once\n";
5141 Preamble += "struct objc_selector; struct objc_class;\n";
5142 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
5143 Preamble += "struct objc_object *superClass; ";
5144 if (LangOpts.MicrosoftExt) {
5145 // Add a constructor for creating temporary objects.
5146 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
5147 ": ";
5148 Preamble += "object(o), superClass(s) {} ";
5149 }
5150 Preamble += "};\n";
5151 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5152 Preamble += "typedef struct objc_object Protocol;\n";
5153 Preamble += "#define _REWRITER_typedef_Protocol\n";
5154 Preamble += "#endif\n";
5155 if (LangOpts.MicrosoftExt) {
5156 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5157 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
5158 } else
5159 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
5160 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
5161 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5162 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
5163 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5164 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
5165 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5166 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
5167 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5168 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
5169 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5170 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5171 Preamble += "(const char *);\n";
5172 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5173 Preamble += "(struct objc_class *);\n";
5174 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5175 Preamble += "(const char *);\n";
5176 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
5177 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
5178 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
5179 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
5180 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
5181 Preamble += "(struct objc_class *, struct objc_object *);\n";
5182 // @synchronized hooks.
5183 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
5184 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
5185 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5186 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5187 Preamble += "struct __objcFastEnumerationState {\n\t";
5188 Preamble += "unsigned long state;\n\t";
5189 Preamble += "void **itemsPtr;\n\t";
5190 Preamble += "unsigned long *mutationsPtr;\n\t";
5191 Preamble += "unsigned long extra[5];\n};\n";
5192 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5193 Preamble += "#define __FASTENUMERATIONSTATE\n";
5194 Preamble += "#endif\n";
5195 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5196 Preamble += "struct __NSConstantStringImpl {\n";
5197 Preamble += " int *isa;\n";
5198 Preamble += " int flags;\n";
5199 Preamble += " char *str;\n";
5200 Preamble += " long length;\n";
5201 Preamble += "};\n";
5202 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5203 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5204 Preamble += "#else\n";
5205 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5206 Preamble += "#endif\n";
5207 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5208 Preamble += "#endif\n";
5209 // Blocks preamble.
5210 Preamble += "#ifndef BLOCK_IMPL\n";
5211 Preamble += "#define BLOCK_IMPL\n";
5212 Preamble += "struct __block_impl {\n";
5213 Preamble += " void *isa;\n";
5214 Preamble += " int Flags;\n";
5215 Preamble += " int Reserved;\n";
5216 Preamble += " void *FuncPtr;\n";
5217 Preamble += "};\n";
5218 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5219 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5220 Preamble += "extern \"C\" __declspec(dllexport) "
5221 "void _Block_object_assign(void *, const void *, const int);\n";
5222 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5223 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5224 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5225 Preamble += "#else\n";
5226 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5227 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5228 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5229 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5230 Preamble += "#endif\n";
5231 Preamble += "#endif\n";
5232 if (LangOpts.MicrosoftExt) {
5233 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5234 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5235 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5236 Preamble += "#define __attribute__(X)\n";
5237 Preamble += "#endif\n";
5238 Preamble += "#define __weak\n";
5239 }
5240 else {
5241 Preamble += "#define __block\n";
5242 Preamble += "#define __weak\n";
5243 }
5244 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5245 // as this avoids warning in any 64bit/32bit compilation model.
5246 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5247}
5248
5249/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5250/// ivar offset.
5251void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5252 std::string &Result) {
5253 if (ivar->isBitField()) {
5254 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5255 // place all bitfields at offset 0.
5256 Result += "0";
5257 } else {
5258 Result += "__OFFSETOFIVAR__(struct ";
5259 Result += ivar->getContainingInterface()->getNameAsString();
5260 if (LangOpts.MicrosoftExt)
5261 Result += "_IMPL";
5262 Result += ", ";
5263 Result += ivar->getNameAsString();
5264 Result += ")";
5265 }
5266}
5267
5268/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
5269/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005270/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005271/// char *attributes;
5272/// }
5273
5274/// struct _prop_list_t {
5275/// uint32_t entsize; // sizeof(struct _prop_t)
5276/// uint32_t count_of_properties;
5277/// struct _prop_t prop_list[count_of_properties];
5278/// }
5279
5280/// struct _protocol_t;
5281
5282/// struct _protocol_list_t {
5283/// long protocol_count; // Note, this is 32/64 bit
5284/// struct _protocol_t * protocol_list[protocol_count];
5285/// }
5286
5287/// struct _objc_method {
5288/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005289/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005290/// char *_imp;
5291/// }
5292
5293/// struct _method_list_t {
5294/// uint32_t entsize; // sizeof(struct _objc_method)
5295/// uint32_t method_count;
5296/// struct _objc_method method_list[method_count];
5297/// }
5298
5299/// struct _protocol_t {
5300/// id isa; // NULL
5301/// const char * const protocol_name;
5302/// const struct _protocol_list_t * protocol_list; // super protocols
5303/// const struct method_list_t * const instance_methods;
5304/// const struct method_list_t * const class_methods;
5305/// const struct method_list_t *optionalInstanceMethods;
5306/// const struct method_list_t *optionalClassMethods;
5307/// const struct _prop_list_t * properties;
5308/// const uint32_t size; // sizeof(struct _protocol_t)
5309/// const uint32_t flags; // = 0
5310/// const char ** extendedMethodTypes;
5311/// }
5312
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005313/// struct _ivar_t {
5314/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00005315/// const char *name;
5316/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005317/// uint32_t alignment;
5318/// uint32_t size;
5319/// }
5320
5321/// struct _ivar_list_t {
5322/// uint32 entsize; // sizeof(struct _ivar_t)
5323/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00005324/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005325/// }
5326
5327/// struct _class_ro_t {
5328/// uint32_t const flags;
5329/// uint32_t const instanceStart;
5330/// uint32_t const instanceSize;
5331/// uint32_t const reserved; // only when building for 64bit targets
5332/// const uint8_t * const ivarLayout;
5333/// const char *const name;
5334/// const struct _method_list_t * const baseMethods;
Fariborz Jahanian0a525342012-02-14 19:31:35 +00005335/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005336/// const struct _ivar_list_t *const ivars;
5337/// const uint8_t * const weakIvarLayout;
5338/// const struct _prop_list_t * const properties;
5339/// }
5340
5341/// struct _class_t {
5342/// struct _class_t *isa;
5343/// struct _class_t * const superclass;
5344/// void *cache;
5345/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005346/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005347/// }
5348
5349/// struct _category_t {
5350/// const char * const name;
5351/// struct _class_t *const cls;
5352/// const struct _method_list_t * const instance_methods;
5353/// const struct _method_list_t * const class_methods;
5354/// const struct _protocol_list_t * const protocols;
5355/// const struct _prop_list_t * const properties;
5356/// }
5357
5358/// MessageRefTy - LLVM for:
5359/// struct _message_ref_t {
5360/// IMP messenger;
5361/// SEL name;
5362/// };
5363
5364/// SuperMessageRefTy - LLVM for:
5365/// struct _super_message_ref_t {
5366/// SUPER_IMP messenger;
5367/// SEL name;
5368/// };
5369
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005370static void WriteModernMetadataDeclarations(std::string &Result) {
5371 static bool meta_data_declared = false;
5372 if (meta_data_declared)
5373 return;
5374
5375 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005376 Result += "\tconst char *name;\n";
5377 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005378 Result += "};\n";
5379
5380 Result += "\nstruct _protocol_t;\n";
5381
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005382 Result += "\nstruct _objc_method {\n";
5383 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005384 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005385 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005386 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005387
5388 Result += "\nstruct _protocol_t {\n";
5389 Result += "\tvoid * isa; // NULL\n";
5390 Result += "\tconst char * const protocol_name;\n";
5391 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
5392 Result += "\tconst struct method_list_t * const instance_methods;\n";
5393 Result += "\tconst struct method_list_t * const class_methods;\n";
5394 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
5395 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
5396 Result += "\tconst struct _prop_list_t * properties;\n";
5397 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
5398 Result += "\tconst unsigned int flags; // = 0\n";
5399 Result += "\tconst char ** extendedMethodTypes;\n";
5400 Result += "};\n";
5401
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005402 Result += "\nstruct _ivar_t {\n";
5403 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005404 Result += "\tconst char *name;\n";
5405 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005406 Result += "\tunsigned int alignment;\n";
5407 Result += "\tunsigned int size;\n";
5408 Result += "};\n";
5409
5410 Result += "\nstruct _class_ro_t {\n";
5411 Result += "\tunsigned int const flags;\n";
5412 Result += "\tunsigned int instanceStart;\n";
5413 Result += "\tunsigned int const instanceSize;\n";
5414 Result += "\tunsigned int const reserved; // only when building for 64bit targets\n";
5415 Result += "\tconst unsigned char * const ivarLayout;\n";
5416 Result += "\tconst char *const name;\n";
5417 Result += "\tconst struct _method_list_t * const baseMethods;\n";
5418 Result += "\tconst struct _objc_protocol_list *const baseProtocols;\n";
5419 Result += "\tconst struct _ivar_list_t *const ivars;\n";
5420 Result += "\tconst unsigned char *const weakIvarLayout;\n";
5421 Result += "\tconst struct _prop_list_t *const properties;\n";
5422 Result += "};\n";
5423
5424 Result += "\nstruct _class_t {\n";
5425 Result += "\tstruct _class_t *isa;\n";
5426 Result += "\tstruct _class_t *const superclass;\n";
5427 Result += "\tvoid *cache;\n";
5428 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005429 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005430 Result += "};\n";
5431
5432 Result += "\nstruct _category_t {\n";
5433 Result += "\tconst char * const name;\n";
5434 Result += "\tstruct _class_t *const cls;\n";
5435 Result += "\tconst struct _method_list_t *const instance_methods;\n";
5436 Result += "\tconst struct _method_list_t *const class_methods;\n";
5437 Result += "\tconst struct _protocol_list_t *const protocols;\n";
5438 Result += "\tconst struct _prop_list_t *const properties;\n";
5439 Result += "};\n";
5440
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005441 Result += "extern void *_objc_empty_cache;\n";
5442 Result += "extern void *_objc_empty_vtable;\n";
5443
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005444 meta_data_declared = true;
5445}
5446
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005447static void Write_protocol_list_t_TypeDecl(std::string &Result,
5448 long super_protocol_count) {
5449 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
5450 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
5451 Result += "\tstruct _protocol_t *super_protocols[";
5452 Result += utostr(super_protocol_count); Result += "];\n";
5453 Result += "}";
5454}
5455
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005456static void Write_method_list_t_TypeDecl(std::string &Result,
5457 unsigned int method_count) {
5458 Result += "struct /*_method_list_t*/"; Result += " {\n";
5459 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
5460 Result += "\tunsigned int method_count;\n";
5461 Result += "\tstruct _objc_method method_list[";
5462 Result += utostr(method_count); Result += "];\n";
5463 Result += "}";
5464}
5465
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005466static void Write__prop_list_t_TypeDecl(std::string &Result,
5467 unsigned int property_count) {
5468 Result += "struct /*_prop_list_t*/"; Result += " {\n";
5469 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5470 Result += "\tunsigned int count_of_properties;\n";
5471 Result += "\tstruct _prop_t prop_list[";
5472 Result += utostr(property_count); Result += "];\n";
5473 Result += "}";
5474}
5475
Fariborz Jahanianae932952012-02-10 20:47:10 +00005476static void Write__ivar_list_t_TypeDecl(std::string &Result,
5477 unsigned int ivar_count) {
5478 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
5479 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5480 Result += "\tunsigned int count;\n";
5481 Result += "\tstruct _ivar_t ivar_list[";
5482 Result += utostr(ivar_count); Result += "];\n";
5483 Result += "}";
5484}
5485
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005486static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
5487 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
5488 StringRef VarName,
5489 StringRef ProtocolName) {
5490 if (SuperProtocols.size() > 0) {
5491 Result += "\nstatic ";
5492 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
5493 Result += " "; Result += VarName;
5494 Result += ProtocolName;
5495 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5496 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
5497 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
5498 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
5499 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
5500 Result += SuperPD->getNameAsString();
5501 if (i == e-1)
5502 Result += "\n};\n";
5503 else
5504 Result += ",\n";
5505 }
5506 }
5507}
5508
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005509static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
5510 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005511 ArrayRef<ObjCMethodDecl *> Methods,
5512 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005513 StringRef TopLevelDeclName,
5514 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005515 if (Methods.size() > 0) {
5516 Result += "\nstatic ";
5517 Write_method_list_t_TypeDecl(Result, Methods.size());
5518 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005519 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005520 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5521 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
5522 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
5523 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
5524 ObjCMethodDecl *MD = Methods[i];
5525 if (i == 0)
5526 Result += "\t{{(struct objc_selector *)\"";
5527 else
5528 Result += "\t{(struct objc_selector *)\"";
5529 Result += (MD)->getSelector().getAsString(); Result += "\"";
5530 Result += ", ";
5531 std::string MethodTypeString;
5532 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
5533 Result += "\""; Result += MethodTypeString; Result += "\"";
5534 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005535 if (!MethodImpl)
5536 Result += "0";
5537 else {
5538 Result += "(void *)";
5539 Result += RewriteObj.MethodInternalNames[MD];
5540 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005541 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005542 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005543 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005544 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005545 }
5546 Result += "};\n";
5547 }
5548}
5549
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005550static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005551 ASTContext *Context, std::string &Result,
5552 ArrayRef<ObjCPropertyDecl *> Properties,
5553 const Decl *Container,
5554 StringRef VarName,
5555 StringRef ProtocolName) {
5556 if (Properties.size() > 0) {
5557 Result += "\nstatic ";
5558 Write__prop_list_t_TypeDecl(Result, Properties.size());
5559 Result += " "; Result += VarName;
5560 Result += ProtocolName;
5561 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5562 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
5563 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
5564 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
5565 ObjCPropertyDecl *PropDecl = Properties[i];
5566 if (i == 0)
5567 Result += "\t{{\"";
5568 else
5569 Result += "\t{\"";
5570 Result += PropDecl->getName(); Result += "\",";
5571 std::string PropertyTypeString, QuotePropertyTypeString;
5572 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
5573 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
5574 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
5575 if (i == e-1)
5576 Result += "}}\n";
5577 else
5578 Result += "},\n";
5579 }
5580 Result += "};\n";
5581 }
5582}
5583
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005584// Metadata flags
5585enum MetaDataDlags {
5586 CLS = 0x0,
5587 CLS_META = 0x1,
5588 CLS_ROOT = 0x2,
5589 OBJC2_CLS_HIDDEN = 0x10,
5590 CLS_EXCEPTION = 0x20,
5591
5592 /// (Obsolete) ARC-specific: this class has a .release_ivars method
5593 CLS_HAS_IVAR_RELEASER = 0x40,
5594 /// class was compiled with -fobjc-arr
5595 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
5596};
5597
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005598static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
5599 unsigned int flags,
5600 const std::string &InstanceStart,
5601 const std::string &InstanceSize,
5602 ArrayRef<ObjCMethodDecl *>baseMethods,
5603 ArrayRef<ObjCProtocolDecl *>baseProtocols,
5604 ArrayRef<ObjCIvarDecl *>ivars,
5605 ArrayRef<ObjCPropertyDecl *>Properties,
5606 StringRef VarName,
5607 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005608 Result += "\nstatic struct _class_ro_t ";
5609 Result += VarName; Result += ClassName;
5610 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5611 Result += "\t";
5612 Result += llvm::utostr(flags); Result += ", ";
5613 Result += InstanceStart; Result += ", ";
5614 Result += InstanceSize; Result += ", \n";
5615 Result += "\t";
5616 // uint32_t const reserved; // only when building for 64bit targets
5617 Result += "(unsigned int)0, \n\t";
5618 // const uint8_t * const ivarLayout;
5619 Result += "0, \n\t";
5620 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005621 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005622 if (baseMethods.size() > 0) {
5623 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005624 if (metaclass)
5625 Result += "_OBJC_$_CLASS_METHODS_";
5626 else
5627 Result += "_OBJC_$_INSTANCE_METHODS_";
5628 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005629 Result += ",\n\t";
5630 }
5631 else
5632 Result += "0, \n\t";
5633
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005634 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005635 Result += "(const struct _objc_protocol_list *)&";
5636 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
5637 Result += ",\n\t";
5638 }
5639 else
5640 Result += "0, \n\t";
5641
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005642 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005643 Result += "(const struct _ivar_list_t *)&";
5644 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
5645 Result += ",\n\t";
5646 }
5647 else
5648 Result += "0, \n\t";
5649
5650 // weakIvarLayout
5651 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005652 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005653 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00005654 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005655 Result += ",\n";
5656 }
5657 else
5658 Result += "0, \n";
5659
5660 Result += "};\n";
5661}
5662
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005663static void Write_class_t(ASTContext *Context, std::string &Result,
5664 StringRef VarName,
5665 const ObjCInterfaceDecl *CDecl, bool metadata) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005666
5667 if (metadata && !CDecl->getSuperClass()) {
5668 // Need to handle a case of use of forward declaration.
5669 Result += "\nextern struct _class_t OBJC_CLASS_$_";
5670 Result += CDecl->getNameAsString();
5671 Result += ";\n";
5672 }
5673 // Also, for possibility of 'super' metadata class not having been defined yet.
5674 if (CDecl->getSuperClass()) {
5675 Result += "\nextern struct _class_t "; Result += VarName;
5676 Result += CDecl->getSuperClass()->getNameAsString();
5677 Result += ";\n";
5678 }
5679
5680 Result += "\nstruct _class_t "; Result += VarName; Result += CDecl->getNameAsString();
5681 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
5682 Result += "\t";
5683 if (metadata) {
5684 if (CDecl->getSuperClass()) {
5685 Result += "&"; Result += VarName;
5686 Result += CDecl->getSuperClass()->getNameAsString();
5687 Result += ",\n\t";
5688 Result += "&"; Result += VarName;
5689 Result += CDecl->getSuperClass()->getNameAsString();
5690 Result += ",\n\t";
5691 }
5692 else {
5693 Result += "&"; Result += VarName;
5694 Result += CDecl->getNameAsString();
5695 Result += ",\n\t";
5696 Result += "&OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
5697 Result += ",\n\t";
5698 }
5699 }
5700 else {
5701 Result += "&OBJC_METACLASS_$_";
5702 Result += CDecl->getNameAsString();
5703 Result += ",\n\t";
5704 if (CDecl->getSuperClass()) {
5705 Result += "&"; Result += VarName;
5706 Result += CDecl->getSuperClass()->getNameAsString();
5707 Result += ",\n\t";
5708 }
5709 else
5710 Result += "0,\n\t";
5711 }
5712 Result += "(void *)&_objc_empty_cache,\n\t";
5713 Result += "(void *)&_objc_empty_vtable,\n\t";
5714 if (metadata)
5715 Result += "&_OBJC_METACLASS_RO_$_";
5716 else
5717 Result += "&_OBJC_CLASS_RO_$_";
5718 Result += CDecl->getNameAsString();
5719 Result += ",\n};\n";
5720}
5721
Fariborz Jahanian61186122012-02-17 18:40:41 +00005722static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
5723 std::string &Result,
5724 StringRef CatName,
5725 StringRef ClassName,
5726 ArrayRef<ObjCMethodDecl *> InstanceMethods,
5727 ArrayRef<ObjCMethodDecl *> ClassMethods,
5728 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
5729 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00005730 // must declare an extern class object in case this class is not implemented
5731 // in this TU.
5732 Result += "\nextern struct _class_t ";
5733 Result += "OBJC_CLASS_$_"; Result += ClassName;
5734 Result += ";\n";
5735
Fariborz Jahanian61186122012-02-17 18:40:41 +00005736 Result += "\nstatic struct _category_t ";
5737 Result += "_OBJC_$_CATEGORY_";
5738 Result += ClassName; Result += "_$_"; Result += CatName;
5739 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
5740 Result += "{\n";
5741 Result += "\t\""; Result += ClassName; Result += "\",\n";
5742 Result += "\t&"; Result += "OBJC_CLASS_$_"; Result += ClassName;
5743 Result += ",\n";
5744 if (InstanceMethods.size() > 0) {
5745 Result += "\t(const struct _method_list_t *)&";
5746 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
5747 Result += ClassName; Result += "_$_"; Result += CatName;
5748 Result += ",\n";
5749 }
5750 else
5751 Result += "\t0,\n";
5752
5753 if (ClassMethods.size() > 0) {
5754 Result += "\t(const struct _method_list_t *)&";
5755 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
5756 Result += ClassName; Result += "_$_"; Result += CatName;
5757 Result += ",\n";
5758 }
5759 else
5760 Result += "\t0,\n";
5761
5762 if (RefedProtocols.size() > 0) {
5763 Result += "\t(const struct _protocol_list_t *)&";
5764 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
5765 Result += ClassName; Result += "_$_"; Result += CatName;
5766 Result += ",\n";
5767 }
5768 else
5769 Result += "\t0,\n";
5770
5771 if (ClassProperties.size() > 0) {
5772 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
5773 Result += ClassName; Result += "_$_"; Result += CatName;
5774 Result += ",\n";
5775 }
5776 else
5777 Result += "\t0,\n";
5778
5779 Result += "};\n";
5780}
5781
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00005782static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
5783 ASTContext *Context, std::string &Result,
5784 ArrayRef<ObjCMethodDecl *> Methods,
5785 StringRef VarName,
5786 StringRef ProtocolName) {
5787 if (Methods.size() == 0)
5788 return;
5789
5790 Result += "\nstatic const char *";
5791 Result += VarName; Result += ProtocolName;
5792 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
5793 Result += "{\n";
5794 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
5795 ObjCMethodDecl *MD = Methods[i];
5796 std::string MethodTypeString, QuoteMethodTypeString;
5797 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
5798 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
5799 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
5800 if (i == e-1)
5801 Result += "\n};\n";
5802 else {
5803 Result += ",\n";
5804 }
5805 }
5806}
5807
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005808static void Write_IvarOffsetVar(std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005809 ArrayRef<ObjCIvarDecl *> Ivars,
5810 StringRef VarName,
5811 StringRef ClassName) {
5812 // FIXME. visibilty of offset symbols may have to be set; for Darwin
5813 // this is what happens:
5814 /**
5815 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
5816 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
5817 Class->getVisibility() == HiddenVisibility)
5818 Visibility shoud be: HiddenVisibility;
5819 else
5820 Visibility shoud be: DefaultVisibility;
5821 */
5822
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005823 Result += "\n";
5824 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
5825 ObjCIvarDecl *IvarDecl = Ivars[i];
5826 Result += "unsigned long int "; Result += VarName;
5827 Result += ClassName; Result += "_";
5828 Result += IvarDecl->getName();
5829 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
5830 Result += " = ";
5831 if (IvarDecl->isBitField()) {
5832 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5833 // place all bitfields at offset 0.
5834 Result += "0;\n";
5835 }
5836 else {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005837 Result += "__OFFSETOFIVAR__(struct ";
5838 Result += ClassName;
5839 Result += "_IMPL, ";
5840 Result += IvarDecl->getName(); Result += ");\n";
5841 }
5842 }
5843}
5844
Fariborz Jahanianae932952012-02-10 20:47:10 +00005845static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
5846 ASTContext *Context, std::string &Result,
5847 ArrayRef<ObjCIvarDecl *> Ivars,
5848 StringRef VarName,
5849 StringRef ClassName) {
5850 if (Ivars.size() > 0) {
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005851 Write_IvarOffsetVar(Result, Ivars, "OBJC_IVAR_$_", ClassName);
5852
Fariborz Jahanianae932952012-02-10 20:47:10 +00005853 Result += "\nstatic ";
5854 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
5855 Result += " "; Result += VarName;
5856 Result += ClassName;
5857 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5858 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
5859 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
5860 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
5861 ObjCIvarDecl *IvarDecl = Ivars[i];
5862 if (i == 0)
5863 Result += "\t{{";
5864 else
5865 Result += "\t {";
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005866
5867 Result += "(unsigned long int *)&OBJC_IVAR_$_";
5868 Result += ClassName; Result += "_"; Result += IvarDecl->getName();
5869 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005870
5871 Result += "\""; Result += IvarDecl->getName(); Result += "\", ";
5872 std::string IvarTypeString, QuoteIvarTypeString;
5873 Context->getObjCEncodingForType(IvarDecl->getType(), IvarTypeString,
5874 IvarDecl);
5875 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
5876 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
5877
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00005878 // FIXME. this alignment represents the host alignment and need be changed to
5879 // represent the target alignment.
5880 unsigned Align = Context->getTypeAlign(IvarDecl->getType())/8;
5881 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00005882 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00005883 CharUnits Size = Context->getTypeSizeInChars(IvarDecl->getType());
5884 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00005885 if (i == e-1)
5886 Result += "}}\n";
5887 else
5888 Result += "},\n";
5889 }
5890 Result += "};\n";
5891 }
5892}
5893
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005894/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005895void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
5896 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005897
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005898 // Do not synthesize the protocol more than once.
5899 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
5900 return;
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005901 WriteModernMetadataDeclarations(Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005902
5903 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
5904 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005905 // Must write out all protocol definitions in current qualifier list,
5906 // and in their nested qualifiers before writing out current definition.
5907 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
5908 E = PDecl->protocol_end(); I != E; ++I)
5909 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005910
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005911 // Construct method lists.
5912 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
5913 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
5914 for (ObjCProtocolDecl::instmeth_iterator
5915 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
5916 I != E; ++I) {
5917 ObjCMethodDecl *MD = *I;
5918 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
5919 OptInstanceMethods.push_back(MD);
5920 } else {
5921 InstanceMethods.push_back(MD);
5922 }
5923 }
5924
5925 for (ObjCProtocolDecl::classmeth_iterator
5926 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
5927 I != E; ++I) {
5928 ObjCMethodDecl *MD = *I;
5929 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
5930 OptClassMethods.push_back(MD);
5931 } else {
5932 ClassMethods.push_back(MD);
5933 }
5934 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00005935 std::vector<ObjCMethodDecl *> AllMethods;
5936 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
5937 AllMethods.push_back(InstanceMethods[i]);
5938 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
5939 AllMethods.push_back(ClassMethods[i]);
5940 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
5941 AllMethods.push_back(OptInstanceMethods[i]);
5942 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
5943 AllMethods.push_back(OptClassMethods[i]);
5944
5945 Write__extendedMethodTypes_initializer(*this, Context, Result,
5946 AllMethods,
5947 "_OBJC_PROTOCOL_METHOD_TYPES_",
5948 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005949 // Protocol's super protocol list
5950 std::vector<ObjCProtocolDecl *> SuperProtocols;
5951 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
5952 E = PDecl->protocol_end(); I != E; ++I)
5953 SuperProtocols.push_back(*I);
5954
5955 Write_protocol_list_initializer(Context, Result, SuperProtocols,
5956 "_OBJC_PROTOCOL_REFS_",
5957 PDecl->getNameAsString());
5958
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005959 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005960 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005961 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005962
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005963 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005964 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005965 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005966
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005967 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005968 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005969 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005970
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005971 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005972 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005973 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005974
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005975 // Protocol's property metadata.
5976 std::vector<ObjCPropertyDecl *> ProtocolProperties;
5977 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
5978 E = PDecl->prop_end(); I != E; ++I)
5979 ProtocolProperties.push_back(*I);
5980
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005981 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005982 /* Container */0,
5983 "_OBJC_PROTOCOL_PROPERTIES_",
5984 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005985
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005986 // Writer out root metadata for current protocol: struct _protocol_t
5987 Result += "\nstatic struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005988 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005989 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
5990 Result += "\t0,\n"; // id is; is null
5991 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005992 if (SuperProtocols.size() > 0) {
5993 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
5994 Result += PDecl->getNameAsString(); Result += ",\n";
5995 }
5996 else
5997 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005998 if (InstanceMethods.size() > 0) {
5999 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
6000 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006001 }
6002 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006003 Result += "\t0,\n";
6004
6005 if (ClassMethods.size() > 0) {
6006 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
6007 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006008 }
6009 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006010 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006011
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006012 if (OptInstanceMethods.size() > 0) {
6013 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
6014 Result += PDecl->getNameAsString(); Result += ",\n";
6015 }
6016 else
6017 Result += "\t0,\n";
6018
6019 if (OptClassMethods.size() > 0) {
6020 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
6021 Result += PDecl->getNameAsString(); Result += ",\n";
6022 }
6023 else
6024 Result += "\t0,\n";
6025
6026 if (ProtocolProperties.size() > 0) {
6027 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
6028 Result += PDecl->getNameAsString(); Result += ",\n";
6029 }
6030 else
6031 Result += "\t0,\n";
6032
6033 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6034 Result += "\t0,\n";
6035
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006036 if (AllMethods.size() > 0) {
6037 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6038 Result += PDecl->getNameAsString();
6039 Result += "\n};\n";
6040 }
6041 else
6042 Result += "\t0\n};\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006043
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006044 // Mark this protocol as having been generated.
6045 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
6046 llvm_unreachable("protocol already synthesized");
6047
6048}
6049
6050void RewriteModernObjC::RewriteObjCProtocolListMetaData(
6051 const ObjCList<ObjCProtocolDecl> &Protocols,
6052 StringRef prefix, StringRef ClassName,
6053 std::string &Result) {
6054 if (Protocols.empty()) return;
6055
6056 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006057 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006058
6059 // Output the top lovel protocol meta-data for the class.
6060 /* struct _objc_protocol_list {
6061 struct _objc_protocol_list *next;
6062 int protocol_count;
6063 struct _objc_protocol *class_protocols[];
6064 }
6065 */
6066 Result += "\nstatic struct {\n";
6067 Result += "\tstruct _objc_protocol_list *next;\n";
6068 Result += "\tint protocol_count;\n";
6069 Result += "\tstruct _objc_protocol *class_protocols[";
6070 Result += utostr(Protocols.size());
6071 Result += "];\n} _OBJC_";
6072 Result += prefix;
6073 Result += "_PROTOCOLS_";
6074 Result += ClassName;
6075 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
6076 "{\n\t0, ";
6077 Result += utostr(Protocols.size());
6078 Result += "\n";
6079
6080 Result += "\t,{&_OBJC_PROTOCOL_";
6081 Result += Protocols[0]->getNameAsString();
6082 Result += " \n";
6083
6084 for (unsigned i = 1; i != Protocols.size(); i++) {
6085 Result += "\t ,&_OBJC_PROTOCOL_";
6086 Result += Protocols[i]->getNameAsString();
6087 Result += "\n";
6088 }
6089 Result += "\t }\n};\n";
6090}
6091
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006092/// hasObjCExceptionAttribute - Return true if this class or any super
6093/// class has the __objc_exception__ attribute.
6094/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
6095static bool hasObjCExceptionAttribute(ASTContext &Context,
6096 const ObjCInterfaceDecl *OID) {
6097 if (OID->hasAttr<ObjCExceptionAttr>())
6098 return true;
6099 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
6100 return hasObjCExceptionAttribute(Context, Super);
6101 return false;
6102}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006103
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006104void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
6105 std::string &Result) {
6106 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6107
6108 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00006109 if (CDecl->isImplicitInterfaceDecl())
6110 assert(false &&
6111 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006112
Fariborz Jahanianae932952012-02-10 20:47:10 +00006113 WriteModernMetadataDeclarations(Result);
6114 SmallVector<ObjCIvarDecl *, 8> IVars;
6115
6116 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6117 IVD; IVD = IVD->getNextIvar()) {
6118 // Ignore unnamed bit-fields.
6119 if (!IVD->getDeclName())
6120 continue;
6121 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006122 }
6123
Fariborz Jahanianae932952012-02-10 20:47:10 +00006124 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006125 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanianae932952012-02-10 20:47:10 +00006126 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006127
6128 // Build _objc_method_list for class's instance methods if needed
6129 SmallVector<ObjCMethodDecl *, 32>
6130 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6131
6132 // If any of our property implementations have associated getters or
6133 // setters, produce metadata for them as well.
6134 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6135 PropEnd = IDecl->propimpl_end();
6136 Prop != PropEnd; ++Prop) {
6137 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6138 continue;
6139 if (!(*Prop)->getPropertyIvarDecl())
6140 continue;
6141 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
6142 if (!PD)
6143 continue;
6144 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
6145 if (!Getter->isDefined())
6146 InstanceMethods.push_back(Getter);
6147 if (PD->isReadOnly())
6148 continue;
6149 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
6150 if (!Setter->isDefined())
6151 InstanceMethods.push_back(Setter);
6152 }
6153
6154 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6155 "_OBJC_$_INSTANCE_METHODS_",
6156 IDecl->getNameAsString(), true);
6157
6158 SmallVector<ObjCMethodDecl *, 32>
6159 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6160
6161 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6162 "_OBJC_$_CLASS_METHODS_",
6163 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00006164
6165 // Protocols referenced in class declaration?
6166 // Protocol's super protocol list
6167 std::vector<ObjCProtocolDecl *> RefedProtocols;
6168 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
6169 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6170 E = Protocols.end();
6171 I != E; ++I) {
6172 RefedProtocols.push_back(*I);
6173 // Must write out all protocol definitions in current qualifier list,
6174 // and in their nested qualifiers before writing out current definition.
6175 RewriteObjCProtocolMetaData(*I, Result);
6176 }
6177
6178 Write_protocol_list_initializer(Context, Result,
6179 RefedProtocols,
6180 "_OBJC_CLASS_PROTOCOLS_$_",
6181 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006182
6183 // Protocol's property metadata.
6184 std::vector<ObjCPropertyDecl *> ClassProperties;
6185 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6186 E = CDecl->prop_end(); I != E; ++I)
6187 ClassProperties.push_back(*I);
6188
6189 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
6190 /* Container */0,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006191 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006192 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006193
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006194
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006195 // Data for initializing _class_ro_t metaclass meta-data
6196 uint32_t flags = CLS_META;
6197 std::string InstanceSize;
6198 std::string InstanceStart;
6199
6200
6201 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
6202 if (classIsHidden)
6203 flags |= OBJC2_CLS_HIDDEN;
6204
6205 if (!CDecl->getSuperClass())
6206 // class is root
6207 flags |= CLS_ROOT;
6208 InstanceSize = "sizeof(struct _class_t)";
6209 InstanceStart = InstanceSize;
6210 Write__class_ro_t_initializer(Context, Result, flags,
6211 InstanceStart, InstanceSize,
6212 ClassMethods,
6213 0,
6214 0,
6215 0,
6216 "_OBJC_METACLASS_RO_$_",
6217 CDecl->getNameAsString());
6218
6219
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006220 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006221 flags = CLS;
6222 if (classIsHidden)
6223 flags |= OBJC2_CLS_HIDDEN;
6224
6225 if (hasObjCExceptionAttribute(*Context, CDecl))
6226 flags |= CLS_EXCEPTION;
6227
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006228 if (!CDecl->getSuperClass())
6229 // class is root
6230 flags |= CLS_ROOT;
6231
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006232 InstanceSize.clear();
6233 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006234 if (!ObjCSynthesizedStructs.count(CDecl)) {
6235 InstanceSize = "0";
6236 InstanceStart = "0";
6237 }
6238 else {
6239 InstanceSize = "sizeof(struct ";
6240 InstanceSize += CDecl->getNameAsString();
6241 InstanceSize += "_IMPL)";
6242
6243 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6244 if (IVD) {
6245 InstanceStart += "__OFFSETOFIVAR__(struct ";
6246 InstanceStart += CDecl->getNameAsString();
6247 InstanceStart += "_IMPL, ";
6248 InstanceStart += IVD->getNameAsString();
6249 InstanceStart += ")";
6250 }
6251 else
6252 InstanceStart = InstanceSize;
6253 }
6254 Write__class_ro_t_initializer(Context, Result, flags,
6255 InstanceStart, InstanceSize,
6256 InstanceMethods,
6257 RefedProtocols,
6258 IVars,
6259 ClassProperties,
6260 "_OBJC_CLASS_RO_$_",
6261 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006262
6263 Write_class_t(Context, Result,
6264 "OBJC_METACLASS_$_",
6265 CDecl, /*metaclass*/true);
6266
6267 Write_class_t(Context, Result,
6268 "OBJC_CLASS_$_",
6269 CDecl, /*metaclass*/false);
6270
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006271}
6272
6273void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
6274 int ClsDefCount = ClassImplementation.size();
6275 int CatDefCount = CategoryImplementation.size();
6276
6277 // For each implemented class, write out all its meta data.
6278 for (int i = 0; i < ClsDefCount; i++)
6279 RewriteObjCClassMetaData(ClassImplementation[i], Result);
6280
6281 // For each implemented category, write out all its meta data.
6282 for (int i = 0; i < CatDefCount; i++)
6283 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
6284
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006285 if (ClsDefCount > 0) {
6286 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
6287 Result += llvm::utostr(ClsDefCount); Result += "]";
6288 Result +=
6289 " __attribute__((used, section (\"__DATA, __objc_classlist,"
6290 "regular,no_dead_strip\")))= {\n";
6291 for (int i = 0; i < ClsDefCount; i++) {
6292 Result += "\t&OBJC_CLASS_$_";
6293 Result += ClassImplementation[i]->getNameAsString();
6294 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006295 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006296 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006297 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00006298
6299 if (CatDefCount > 0) {
6300 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
6301 Result += llvm::utostr(CatDefCount); Result += "]";
6302 Result +=
6303 " __attribute__((used, section (\"__DATA, __objc_catlist,"
6304 "regular,no_dead_strip\")))= {\n";
6305 for (int i = 0; i < CatDefCount; i++) {
6306 Result += "\t&_OBJC_$_CATEGORY_";
6307 Result +=
6308 CategoryImplementation[i]->getClassInterface()->getNameAsString();
6309 Result += "_$_";
6310 Result += CategoryImplementation[i]->getNameAsString();
6311 Result += ",\n";
6312 }
6313 Result += "};\n";
6314 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006315}
6316
6317/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
6318/// implementation.
6319void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
6320 std::string &Result) {
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006321 WriteModernMetadataDeclarations(Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006322 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
6323 // Find category declaration for this implementation.
Fariborz Jahanian61186122012-02-17 18:40:41 +00006324 ObjCCategoryDecl *CDecl=0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006325 for (CDecl = ClassDecl->getCategoryList(); CDecl;
6326 CDecl = CDecl->getNextClassCategory())
6327 if (CDecl->getIdentifier() == IDecl->getIdentifier())
6328 break;
6329
6330 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00006331 FullCategoryName += "_$_";
6332 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006333
6334 // Build _objc_method_list for class's instance methods if needed
6335 SmallVector<ObjCMethodDecl *, 32>
6336 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6337
6338 // If any of our property implementations have associated getters or
6339 // setters, produce metadata for them as well.
6340 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6341 PropEnd = IDecl->propimpl_end();
6342 Prop != PropEnd; ++Prop) {
6343 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6344 continue;
6345 if (!(*Prop)->getPropertyIvarDecl())
6346 continue;
6347 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
6348 if (!PD)
6349 continue;
6350 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
6351 InstanceMethods.push_back(Getter);
6352 if (PD->isReadOnly())
6353 continue;
6354 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
6355 InstanceMethods.push_back(Setter);
6356 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006357
Fariborz Jahanian61186122012-02-17 18:40:41 +00006358 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6359 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
6360 FullCategoryName, true);
6361
6362 SmallVector<ObjCMethodDecl *, 32>
6363 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6364
6365 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6366 "_OBJC_$_CATEGORY_CLASS_METHODS_",
6367 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006368
6369 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00006370 // Protocol's super protocol list
6371 std::vector<ObjCProtocolDecl *> RefedProtocols;
6372 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
6373 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6374 E = Protocols.end();
6375 I != E; ++I) {
6376 RefedProtocols.push_back(*I);
6377 // Must write out all protocol definitions in current qualifier list,
6378 // and in their nested qualifiers before writing out current definition.
6379 RewriteObjCProtocolMetaData(*I, Result);
6380 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006381
Fariborz Jahanian61186122012-02-17 18:40:41 +00006382 Write_protocol_list_initializer(Context, Result,
6383 RefedProtocols,
6384 "_OBJC_CATEGORY_PROTOCOLS_$_",
6385 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006386
Fariborz Jahanian61186122012-02-17 18:40:41 +00006387 // Protocol's property metadata.
6388 std::vector<ObjCPropertyDecl *> ClassProperties;
6389 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6390 E = CDecl->prop_end(); I != E; ++I)
6391 ClassProperties.push_back(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006392
Fariborz Jahanian61186122012-02-17 18:40:41 +00006393 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
6394 /* Container */0,
6395 "_OBJC_$_PROP_LIST_",
6396 FullCategoryName);
6397
6398 Write_category_t(*this, Context, Result,
6399 CDecl->getNameAsString(),
6400 ClassDecl->getNameAsString(),
6401 InstanceMethods,
6402 ClassMethods,
6403 RefedProtocols,
6404 ClassProperties);
6405
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006406}
6407
6408// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
6409/// class methods.
6410template<typename MethodIterator>
6411void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
6412 MethodIterator MethodEnd,
6413 bool IsInstanceMethod,
6414 StringRef prefix,
6415 StringRef ClassName,
6416 std::string &Result) {
6417 if (MethodBegin == MethodEnd) return;
6418
6419 if (!objc_impl_method) {
6420 /* struct _objc_method {
6421 SEL _cmd;
6422 char *method_types;
6423 void *_imp;
6424 }
6425 */
6426 Result += "\nstruct _objc_method {\n";
6427 Result += "\tSEL _cmd;\n";
6428 Result += "\tchar *method_types;\n";
6429 Result += "\tvoid *_imp;\n";
6430 Result += "};\n";
6431
6432 objc_impl_method = true;
6433 }
6434
6435 // Build _objc_method_list for class's methods if needed
6436
6437 /* struct {
6438 struct _objc_method_list *next_method;
6439 int method_count;
6440 struct _objc_method method_list[];
6441 }
6442 */
6443 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
6444 Result += "\nstatic struct {\n";
6445 Result += "\tstruct _objc_method_list *next_method;\n";
6446 Result += "\tint method_count;\n";
6447 Result += "\tstruct _objc_method method_list[";
6448 Result += utostr(NumMethods);
6449 Result += "];\n} _OBJC_";
6450 Result += prefix;
6451 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
6452 Result += "_METHODS_";
6453 Result += ClassName;
6454 Result += " __attribute__ ((used, section (\"__OBJC, __";
6455 Result += IsInstanceMethod ? "inst" : "cls";
6456 Result += "_meth\")))= ";
6457 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
6458
6459 Result += "\t,{{(SEL)\"";
6460 Result += (*MethodBegin)->getSelector().getAsString().c_str();
6461 std::string MethodTypeString;
6462 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
6463 Result += "\", \"";
6464 Result += MethodTypeString;
6465 Result += "\", (void *)";
6466 Result += MethodInternalNames[*MethodBegin];
6467 Result += "}\n";
6468 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
6469 Result += "\t ,{(SEL)\"";
6470 Result += (*MethodBegin)->getSelector().getAsString().c_str();
6471 std::string MethodTypeString;
6472 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
6473 Result += "\", \"";
6474 Result += MethodTypeString;
6475 Result += "\", (void *)";
6476 Result += MethodInternalNames[*MethodBegin];
6477 Result += "}\n";
6478 }
6479 Result += "\t }\n};\n";
6480}
6481
6482Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
6483 SourceRange OldRange = IV->getSourceRange();
6484 Expr *BaseExpr = IV->getBase();
6485
6486 // Rewrite the base, but without actually doing replaces.
6487 {
6488 DisableReplaceStmtScope S(*this);
6489 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
6490 IV->setBase(BaseExpr);
6491 }
6492
6493 ObjCIvarDecl *D = IV->getDecl();
6494
6495 Expr *Replacement = IV;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006496
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006497 if (BaseExpr->getType()->isObjCObjectPointerType()) {
6498 const ObjCInterfaceType *iFaceDecl =
6499 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
6500 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
6501 // lookup which class implements the instance variable.
6502 ObjCInterfaceDecl *clsDeclared = 0;
6503 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
6504 clsDeclared);
6505 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
6506
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006507 // Build name of symbol holding ivar offset.
6508 std::string IvarOffsetName = "OBJC_IVAR_$_";
6509 IvarOffsetName += clsDeclared->getIdentifier()->getName();
6510 IvarOffsetName += "_";
6511 IvarOffsetName += D->getName();
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00006512 ReferencedIvars[clsDeclared].insert(D);
6513
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006514 // cast offset to "char *".
6515 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
6516 Context->getPointerType(Context->CharTy),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006517 CK_BitCast,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006518 BaseExpr);
6519 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
6520 SourceLocation(), &Context->Idents.get(IvarOffsetName),
6521 Context->UnsignedLongTy, 0, SC_Extern, SC_None);
6522 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, Context->UnsignedLongTy, VK_LValue,
6523 SourceLocation());
6524 BinaryOperator *addExpr =
6525 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
6526 Context->getPointerType(Context->CharTy),
6527 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006528 // Don't forget the parens to enforce the proper binding.
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006529 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
6530 SourceLocation(),
6531 addExpr);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00006532 QualType IvarT = D->getType();
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00006533 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00006534 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006535
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006536 castExpr = NoTypeInfoCStyleCastExpr(Context,
6537 castT,
6538 CK_BitCast,
6539 PE);
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00006540 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006541 VK_LValue, OK_Ordinary,
6542 SourceLocation());
6543 PE = new (Context) ParenExpr(OldRange.getBegin(),
6544 OldRange.getEnd(),
6545 Exp);
6546
6547 Replacement = PE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006548 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006549
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006550 ReplaceStmtWithRange(IV, Replacement, OldRange);
6551 return Replacement;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006552}
6553