blob: db1f5ff4713e89ca54f7c2df775393217accfc61 [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();
3253 IVD; IVD = IVD->getNextIvar()) {
3254 // Ignore unnamed bit-fields.
3255 if (!IVD->getDeclName())
3256 continue;
3257 IVars.push_back(IVD);
3258 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003259 SourceLocation LocStart = CDecl->getLocStart();
3260 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003261
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003262 const char *startBuf = SM->getCharacterData(LocStart);
3263 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003264
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003265 // If no ivars and no root or if its root, directly or indirectly,
3266 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003267 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003268 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3269 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3270 ReplaceText(LocStart, endBuf-startBuf, Result);
3271 return;
3272 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003273
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003274 Result += "\nstruct ";
3275 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003276 Result += "_IMPL {\n";
3277
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003278 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003279 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3280 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3281 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003282 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003283 TagsDefinedInIvarDecls.clear();
3284 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3285 RewriteObjCFieldDecl(IVars[i], Result);
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00003286
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003287 Result += "};\n";
3288 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3289 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003290 // Mark this struct as having been generated.
3291 if (!ObjCSynthesizedStructs.insert(CDecl))
3292 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003293}
3294
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003295/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3296/// have been referenced in an ivar access expression.
3297void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3298 std::string &Result) {
3299 // write out ivar offset symbols which have been referenced in an ivar
3300 // access expression.
3301 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3302 if (Ivars.empty())
3303 return;
3304 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
3305 e = Ivars.end(); i != e; i++) {
3306 ObjCIvarDecl *IvarDecl = (*i);
3307 Result += "\nextern unsigned long OBJC_IVAR_$_";
3308 Result += CDecl->getName(); Result += "_";
3309 Result += IvarDecl->getName(); Result += ";";
3310 }
3311}
3312
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003313//===----------------------------------------------------------------------===//
3314// Meta Data Emission
3315//===----------------------------------------------------------------------===//
3316
3317
3318/// RewriteImplementations - This routine rewrites all method implementations
3319/// and emits meta-data.
3320
3321void RewriteModernObjC::RewriteImplementations() {
3322 int ClsDefCount = ClassImplementation.size();
3323 int CatDefCount = CategoryImplementation.size();
3324
3325 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003326 for (int i = 0; i < ClsDefCount; i++) {
3327 ObjCImplementationDecl *OIMP = ClassImplementation[i];
3328 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
3329 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00003330 assert(false &&
3331 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003332 RewriteImplementationDecl(OIMP);
3333 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003334
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003335 for (int i = 0; i < CatDefCount; i++) {
3336 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
3337 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
3338 if (CDecl->isImplicitInterfaceDecl())
3339 assert(false &&
3340 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003341 RewriteImplementationDecl(CIMP);
3342 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003343}
3344
3345void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
3346 const std::string &Name,
3347 ValueDecl *VD, bool def) {
3348 assert(BlockByRefDeclNo.count(VD) &&
3349 "RewriteByRefString: ByRef decl missing");
3350 if (def)
3351 ResultStr += "struct ";
3352 ResultStr += "__Block_byref_" + Name +
3353 "_" + utostr(BlockByRefDeclNo[VD]) ;
3354}
3355
3356static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3357 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3358 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3359 return false;
3360}
3361
3362std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3363 StringRef funcName,
3364 std::string Tag) {
3365 const FunctionType *AFT = CE->getFunctionType();
3366 QualType RT = AFT->getResultType();
3367 std::string StructRef = "struct " + Tag;
3368 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
3369 funcName.str() + "_" + "block_func_" + utostr(i);
3370
3371 BlockDecl *BD = CE->getBlockDecl();
3372
3373 if (isa<FunctionNoProtoType>(AFT)) {
3374 // No user-supplied arguments. Still need to pass in a pointer to the
3375 // block (to reference imported block decl refs).
3376 S += "(" + StructRef + " *__cself)";
3377 } else if (BD->param_empty()) {
3378 S += "(" + StructRef + " *__cself)";
3379 } else {
3380 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
3381 assert(FT && "SynthesizeBlockFunc: No function proto");
3382 S += '(';
3383 // first add the implicit argument.
3384 S += StructRef + " *__cself, ";
3385 std::string ParamStr;
3386 for (BlockDecl::param_iterator AI = BD->param_begin(),
3387 E = BD->param_end(); AI != E; ++AI) {
3388 if (AI != BD->param_begin()) S += ", ";
3389 ParamStr = (*AI)->getNameAsString();
3390 QualType QT = (*AI)->getType();
3391 if (convertBlockPointerToFunctionPointer(QT))
3392 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
3393 else
3394 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
3395 S += ParamStr;
3396 }
3397 if (FT->isVariadic()) {
3398 if (!BD->param_empty()) S += ", ";
3399 S += "...";
3400 }
3401 S += ')';
3402 }
3403 S += " {\n";
3404
3405 // Create local declarations to avoid rewriting all closure decl ref exprs.
3406 // First, emit a declaration for all "by ref" decls.
3407 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3408 E = BlockByRefDecls.end(); I != E; ++I) {
3409 S += " ";
3410 std::string Name = (*I)->getNameAsString();
3411 std::string TypeString;
3412 RewriteByRefString(TypeString, Name, (*I));
3413 TypeString += " *";
3414 Name = TypeString + Name;
3415 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
3416 }
3417 // Next, emit a declaration for all "by copy" declarations.
3418 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3419 E = BlockByCopyDecls.end(); I != E; ++I) {
3420 S += " ";
3421 // Handle nested closure invocation. For example:
3422 //
3423 // void (^myImportedClosure)(void);
3424 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3425 //
3426 // void (^anotherClosure)(void);
3427 // anotherClosure = ^(void) {
3428 // myImportedClosure(); // import and invoke the closure
3429 // };
3430 //
3431 if (isTopLevelBlockPointerType((*I)->getType())) {
3432 RewriteBlockPointerTypeVariable(S, (*I));
3433 S += " = (";
3434 RewriteBlockPointerType(S, (*I)->getType());
3435 S += ")";
3436 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3437 }
3438 else {
3439 std::string Name = (*I)->getNameAsString();
3440 QualType QT = (*I)->getType();
3441 if (HasLocalVariableExternalStorage(*I))
3442 QT = Context->getPointerType(QT);
3443 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
3444 S += Name + " = __cself->" +
3445 (*I)->getNameAsString() + "; // bound by copy\n";
3446 }
3447 }
3448 std::string RewrittenStr = RewrittenBlockExprs[CE];
3449 const char *cstr = RewrittenStr.c_str();
3450 while (*cstr++ != '{') ;
3451 S += cstr;
3452 S += "\n";
3453 return S;
3454}
3455
3456std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3457 StringRef funcName,
3458 std::string Tag) {
3459 std::string StructRef = "struct " + Tag;
3460 std::string S = "static void __";
3461
3462 S += funcName;
3463 S += "_block_copy_" + utostr(i);
3464 S += "(" + StructRef;
3465 S += "*dst, " + StructRef;
3466 S += "*src) {";
3467 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3468 E = ImportedBlockDecls.end(); I != E; ++I) {
3469 ValueDecl *VD = (*I);
3470 S += "_Block_object_assign((void*)&dst->";
3471 S += (*I)->getNameAsString();
3472 S += ", (void*)src->";
3473 S += (*I)->getNameAsString();
3474 if (BlockByRefDeclsPtrSet.count((*I)))
3475 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3476 else if (VD->getType()->isBlockPointerType())
3477 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3478 else
3479 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3480 }
3481 S += "}\n";
3482
3483 S += "\nstatic void __";
3484 S += funcName;
3485 S += "_block_dispose_" + utostr(i);
3486 S += "(" + StructRef;
3487 S += "*src) {";
3488 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3489 E = ImportedBlockDecls.end(); I != E; ++I) {
3490 ValueDecl *VD = (*I);
3491 S += "_Block_object_dispose((void*)src->";
3492 S += (*I)->getNameAsString();
3493 if (BlockByRefDeclsPtrSet.count((*I)))
3494 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3495 else if (VD->getType()->isBlockPointerType())
3496 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3497 else
3498 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3499 }
3500 S += "}\n";
3501 return S;
3502}
3503
3504std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3505 std::string Desc) {
3506 std::string S = "\nstruct " + Tag;
3507 std::string Constructor = " " + Tag;
3508
3509 S += " {\n struct __block_impl impl;\n";
3510 S += " struct " + Desc;
3511 S += "* Desc;\n";
3512
3513 Constructor += "(void *fp, "; // Invoke function pointer.
3514 Constructor += "struct " + Desc; // Descriptor pointer.
3515 Constructor += " *desc";
3516
3517 if (BlockDeclRefs.size()) {
3518 // Output all "by copy" declarations.
3519 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3520 E = BlockByCopyDecls.end(); I != E; ++I) {
3521 S += " ";
3522 std::string FieldName = (*I)->getNameAsString();
3523 std::string ArgName = "_" + FieldName;
3524 // Handle nested closure invocation. For example:
3525 //
3526 // void (^myImportedBlock)(void);
3527 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3528 //
3529 // void (^anotherBlock)(void);
3530 // anotherBlock = ^(void) {
3531 // myImportedBlock(); // import and invoke the closure
3532 // };
3533 //
3534 if (isTopLevelBlockPointerType((*I)->getType())) {
3535 S += "struct __block_impl *";
3536 Constructor += ", void *" + ArgName;
3537 } else {
3538 QualType QT = (*I)->getType();
3539 if (HasLocalVariableExternalStorage(*I))
3540 QT = Context->getPointerType(QT);
3541 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3542 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
3543 Constructor += ", " + ArgName;
3544 }
3545 S += FieldName + ";\n";
3546 }
3547 // Output all "by ref" declarations.
3548 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3549 E = BlockByRefDecls.end(); I != E; ++I) {
3550 S += " ";
3551 std::string FieldName = (*I)->getNameAsString();
3552 std::string ArgName = "_" + FieldName;
3553 {
3554 std::string TypeString;
3555 RewriteByRefString(TypeString, FieldName, (*I));
3556 TypeString += " *";
3557 FieldName = TypeString + FieldName;
3558 ArgName = TypeString + ArgName;
3559 Constructor += ", " + ArgName;
3560 }
3561 S += FieldName + "; // by ref\n";
3562 }
3563 // Finish writing the constructor.
3564 Constructor += ", int flags=0)";
3565 // Initialize all "by copy" arguments.
3566 bool firsTime = true;
3567 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3568 E = BlockByCopyDecls.end(); I != E; ++I) {
3569 std::string Name = (*I)->getNameAsString();
3570 if (firsTime) {
3571 Constructor += " : ";
3572 firsTime = false;
3573 }
3574 else
3575 Constructor += ", ";
3576 if (isTopLevelBlockPointerType((*I)->getType()))
3577 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3578 else
3579 Constructor += Name + "(_" + Name + ")";
3580 }
3581 // Initialize all "by ref" arguments.
3582 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3583 E = BlockByRefDecls.end(); I != E; ++I) {
3584 std::string Name = (*I)->getNameAsString();
3585 if (firsTime) {
3586 Constructor += " : ";
3587 firsTime = false;
3588 }
3589 else
3590 Constructor += ", ";
3591 Constructor += Name + "(_" + Name + "->__forwarding)";
3592 }
3593
3594 Constructor += " {\n";
3595 if (GlobalVarDecl)
3596 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3597 else
3598 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3599 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3600
3601 Constructor += " Desc = desc;\n";
3602 } else {
3603 // Finish writing the constructor.
3604 Constructor += ", int flags=0) {\n";
3605 if (GlobalVarDecl)
3606 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3607 else
3608 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3609 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3610 Constructor += " Desc = desc;\n";
3611 }
3612 Constructor += " ";
3613 Constructor += "}\n";
3614 S += Constructor;
3615 S += "};\n";
3616 return S;
3617}
3618
3619std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
3620 std::string ImplTag, int i,
3621 StringRef FunName,
3622 unsigned hasCopy) {
3623 std::string S = "\nstatic struct " + DescTag;
3624
3625 S += " {\n unsigned long reserved;\n";
3626 S += " unsigned long Block_size;\n";
3627 if (hasCopy) {
3628 S += " void (*copy)(struct ";
3629 S += ImplTag; S += "*, struct ";
3630 S += ImplTag; S += "*);\n";
3631
3632 S += " void (*dispose)(struct ";
3633 S += ImplTag; S += "*);\n";
3634 }
3635 S += "} ";
3636
3637 S += DescTag + "_DATA = { 0, sizeof(struct ";
3638 S += ImplTag + ")";
3639 if (hasCopy) {
3640 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3641 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
3642 }
3643 S += "};\n";
3644 return S;
3645}
3646
3647void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3648 StringRef FunName) {
3649 // Insert declaration for the function in which block literal is used.
3650 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
3651 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
3652 bool RewriteSC = (GlobalVarDecl &&
3653 !Blocks.empty() &&
3654 GlobalVarDecl->getStorageClass() == SC_Static &&
3655 GlobalVarDecl->getType().getCVRQualifiers());
3656 if (RewriteSC) {
3657 std::string SC(" void __");
3658 SC += GlobalVarDecl->getNameAsString();
3659 SC += "() {}";
3660 InsertText(FunLocStart, SC);
3661 }
3662
3663 // Insert closures that were part of the function.
3664 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3665 CollectBlockDeclRefInfo(Blocks[i]);
3666 // Need to copy-in the inner copied-in variables not actually used in this
3667 // block.
3668 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
3669 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
3670 ValueDecl *VD = Exp->getDecl();
3671 BlockDeclRefs.push_back(Exp);
3672 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
3673 BlockByCopyDeclsPtrSet.insert(VD);
3674 BlockByCopyDecls.push_back(VD);
3675 }
3676 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
3677 BlockByRefDeclsPtrSet.insert(VD);
3678 BlockByRefDecls.push_back(VD);
3679 }
3680 // imported objects in the inner blocks not used in the outer
3681 // blocks must be copied/disposed in the outer block as well.
3682 if (Exp->isByRef() ||
3683 VD->getType()->isObjCObjectPointerType() ||
3684 VD->getType()->isBlockPointerType())
3685 ImportedBlockDecls.insert(VD);
3686 }
3687
3688 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3689 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
3690
3691 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
3692
3693 InsertText(FunLocStart, CI);
3694
3695 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
3696
3697 InsertText(FunLocStart, CF);
3698
3699 if (ImportedBlockDecls.size()) {
3700 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
3701 InsertText(FunLocStart, HF);
3702 }
3703 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3704 ImportedBlockDecls.size() > 0);
3705 InsertText(FunLocStart, BD);
3706
3707 BlockDeclRefs.clear();
3708 BlockByRefDecls.clear();
3709 BlockByRefDeclsPtrSet.clear();
3710 BlockByCopyDecls.clear();
3711 BlockByCopyDeclsPtrSet.clear();
3712 ImportedBlockDecls.clear();
3713 }
3714 if (RewriteSC) {
3715 // Must insert any 'const/volatile/static here. Since it has been
3716 // removed as result of rewriting of block literals.
3717 std::string SC;
3718 if (GlobalVarDecl->getStorageClass() == SC_Static)
3719 SC = "static ";
3720 if (GlobalVarDecl->getType().isConstQualified())
3721 SC += "const ";
3722 if (GlobalVarDecl->getType().isVolatileQualified())
3723 SC += "volatile ";
3724 if (GlobalVarDecl->getType().isRestrictQualified())
3725 SC += "restrict ";
3726 InsertText(FunLocStart, SC);
3727 }
3728
3729 Blocks.clear();
3730 InnerDeclRefsCount.clear();
3731 InnerDeclRefs.clear();
3732 RewrittenBlockExprs.clear();
3733}
3734
3735void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3736 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
3737 StringRef FuncName = FD->getName();
3738
3739 SynthesizeBlockLiterals(FunLocStart, FuncName);
3740}
3741
3742static void BuildUniqueMethodName(std::string &Name,
3743 ObjCMethodDecl *MD) {
3744 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3745 Name = IFace->getName();
3746 Name += "__" + MD->getSelector().getAsString();
3747 // Convert colons to underscores.
3748 std::string::size_type loc = 0;
3749 while ((loc = Name.find(":", loc)) != std::string::npos)
3750 Name.replace(loc, 1, "_");
3751}
3752
3753void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
3754 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3755 //SourceLocation FunLocStart = MD->getLocStart();
3756 SourceLocation FunLocStart = MD->getLocStart();
3757 std::string FuncName;
3758 BuildUniqueMethodName(FuncName, MD);
3759 SynthesizeBlockLiterals(FunLocStart, FuncName);
3760}
3761
3762void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
3763 for (Stmt::child_range CI = S->children(); CI; ++CI)
3764 if (*CI) {
3765 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3766 GetBlockDeclRefExprs(CBE->getBody());
3767 else
3768 GetBlockDeclRefExprs(*CI);
3769 }
3770 // Handle specific things.
3771 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
3772 // FIXME: Handle enums.
3773 if (!isa<FunctionDecl>(CDRE->getDecl()))
3774 BlockDeclRefs.push_back(CDRE);
3775 }
3776 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
3777 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
3778 BlockDeclRefExpr *BDRE =
3779 new (Context)BlockDeclRefExpr(cast<VarDecl>(DRE->getDecl()),
3780 DRE->getType(),
3781 VK_LValue, DRE->getLocation(), false);
3782 BlockDeclRefs.push_back(BDRE);
3783 }
3784
3785 return;
3786}
3787
3788void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
3789 SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
3790 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
3791 for (Stmt::child_range CI = S->children(); CI; ++CI)
3792 if (*CI) {
3793 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
3794 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
3795 GetInnerBlockDeclRefExprs(CBE->getBody(),
3796 InnerBlockDeclRefs,
3797 InnerContexts);
3798 }
3799 else
3800 GetInnerBlockDeclRefExprs(*CI,
3801 InnerBlockDeclRefs,
3802 InnerContexts);
3803
3804 }
3805 // Handle specific things.
3806 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
3807 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
3808 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
3809 InnerBlockDeclRefs.push_back(CDRE);
3810 }
3811 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3812 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
3813 if (Var->isFunctionOrMethodVarDecl())
3814 ImportedLocalExternalDecls.insert(Var);
3815 }
3816
3817 return;
3818}
3819
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003820/// convertObjCTypeToCStyleType - This routine converts such objc types
3821/// as qualified objects, and blocks to their closest c/c++ types that
3822/// it can. It returns true if input type was modified.
3823bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
3824 QualType oldT = T;
3825 convertBlockPointerToFunctionPointer(T);
3826 if (T->isFunctionPointerType()) {
3827 QualType PointeeTy;
3828 if (const PointerType* PT = T->getAs<PointerType>()) {
3829 PointeeTy = PT->getPointeeType();
3830 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
3831 T = convertFunctionTypeOfBlocks(FT);
3832 T = Context->getPointerType(T);
3833 }
3834 }
3835 }
3836
3837 convertToUnqualifiedObjCType(T);
3838 return T != oldT;
3839}
3840
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003841/// convertFunctionTypeOfBlocks - This routine converts a function type
3842/// whose result type may be a block pointer or whose argument type(s)
3843/// might be block pointers to an equivalent function type replacing
3844/// all block pointers to function pointers.
3845QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3846 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3847 // FTP will be null for closures that don't take arguments.
3848 // Generate a funky cast.
3849 SmallVector<QualType, 8> ArgTypes;
3850 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003851 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003852
3853 if (FTP) {
3854 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3855 E = FTP->arg_type_end(); I && (I != E); ++I) {
3856 QualType t = *I;
3857 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003858 if (convertObjCTypeToCStyleType(t))
3859 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003860 ArgTypes.push_back(t);
3861 }
3862 }
3863 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003864 if (modified)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003865 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
3866 else FuncType = QualType(FT, 0);
3867 return FuncType;
3868}
3869
3870Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
3871 // Navigate to relevant type information.
3872 const BlockPointerType *CPT = 0;
3873
3874 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
3875 CPT = DRE->getType()->getAs<BlockPointerType>();
3876 } else if (const BlockDeclRefExpr *CDRE =
3877 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
3878 CPT = CDRE->getType()->getAs<BlockPointerType>();
3879 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
3880 CPT = MExpr->getType()->getAs<BlockPointerType>();
3881 }
3882 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3883 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3884 }
3885 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3886 CPT = IEXPR->getType()->getAs<BlockPointerType>();
3887 else if (const ConditionalOperator *CEXPR =
3888 dyn_cast<ConditionalOperator>(BlockExp)) {
3889 Expr *LHSExp = CEXPR->getLHS();
3890 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3891 Expr *RHSExp = CEXPR->getRHS();
3892 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3893 Expr *CONDExp = CEXPR->getCond();
3894 ConditionalOperator *CondExpr =
3895 new (Context) ConditionalOperator(CONDExp,
3896 SourceLocation(), cast<Expr>(LHSStmt),
3897 SourceLocation(), cast<Expr>(RHSStmt),
3898 Exp->getType(), VK_RValue, OK_Ordinary);
3899 return CondExpr;
3900 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3901 CPT = IRE->getType()->getAs<BlockPointerType>();
3902 } else if (const PseudoObjectExpr *POE
3903 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3904 CPT = POE->getType()->castAs<BlockPointerType>();
3905 } else {
3906 assert(1 && "RewriteBlockClass: Bad type");
3907 }
3908 assert(CPT && "RewriteBlockClass: Bad type");
3909 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
3910 assert(FT && "RewriteBlockClass: Bad type");
3911 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3912 // FTP will be null for closures that don't take arguments.
3913
3914 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3915 SourceLocation(), SourceLocation(),
3916 &Context->Idents.get("__block_impl"));
3917 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
3918
3919 // Generate a funky cast.
3920 SmallVector<QualType, 8> ArgTypes;
3921
3922 // Push the block argument type.
3923 ArgTypes.push_back(PtrBlock);
3924 if (FTP) {
3925 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3926 E = FTP->arg_type_end(); I && (I != E); ++I) {
3927 QualType t = *I;
3928 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3929 if (!convertBlockPointerToFunctionPointer(t))
3930 convertToUnqualifiedObjCType(t);
3931 ArgTypes.push_back(t);
3932 }
3933 }
3934 // Now do the pointer to function cast.
3935 QualType PtrToFuncCastType
3936 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
3937
3938 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
3939
3940 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
3941 CK_BitCast,
3942 const_cast<Expr*>(BlockExp));
3943 // Don't forget the parens to enforce the proper binding.
3944 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3945 BlkCast);
3946 //PE->dump();
3947
3948 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3949 SourceLocation(),
3950 &Context->Idents.get("FuncPtr"),
3951 Context->VoidPtrTy, 0,
3952 /*BitWidth=*/0, /*Mutable=*/true,
3953 /*HasInit=*/false);
3954 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
3955 FD->getType(), VK_LValue,
3956 OK_Ordinary);
3957
3958
3959 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
3960 CK_BitCast, ME);
3961 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3962
3963 SmallVector<Expr*, 8> BlkExprs;
3964 // Add the implicit argument.
3965 BlkExprs.push_back(BlkCast);
3966 // Add the user arguments.
3967 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3968 E = Exp->arg_end(); I != E; ++I) {
3969 BlkExprs.push_back(*I);
3970 }
3971 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
3972 BlkExprs.size(),
3973 Exp->getType(), VK_RValue,
3974 SourceLocation());
3975 return CE;
3976}
3977
3978// We need to return the rewritten expression to handle cases where the
3979// BlockDeclRefExpr is embedded in another expression being rewritten.
3980// For example:
3981//
3982// int main() {
3983// __block Foo *f;
3984// __block int i;
3985//
3986// void (^myblock)() = ^() {
3987// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
3988// i = 77;
3989// };
3990//}
3991Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
3992 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
3993 // for each DeclRefExp where BYREFVAR is name of the variable.
3994 ValueDecl *VD;
3995 bool isArrow = true;
3996 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
3997 VD = BDRE->getDecl();
3998 else {
3999 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4000 isArrow = false;
4001 }
4002
4003 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4004 SourceLocation(),
4005 &Context->Idents.get("__forwarding"),
4006 Context->VoidPtrTy, 0,
4007 /*BitWidth=*/0, /*Mutable=*/true,
4008 /*HasInit=*/false);
4009 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4010 FD, SourceLocation(),
4011 FD->getType(), VK_LValue,
4012 OK_Ordinary);
4013
4014 StringRef Name = VD->getName();
4015 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
4016 &Context->Idents.get(Name),
4017 Context->VoidPtrTy, 0,
4018 /*BitWidth=*/0, /*Mutable=*/true,
4019 /*HasInit=*/false);
4020 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4021 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4022
4023
4024
4025 // Need parens to enforce precedence.
4026 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4027 DeclRefExp->getExprLoc(),
4028 ME);
4029 ReplaceStmt(DeclRefExp, PE);
4030 return PE;
4031}
4032
4033// Rewrites the imported local variable V with external storage
4034// (static, extern, etc.) as *V
4035//
4036Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4037 ValueDecl *VD = DRE->getDecl();
4038 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4039 if (!ImportedLocalExternalDecls.count(Var))
4040 return DRE;
4041 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4042 VK_LValue, OK_Ordinary,
4043 DRE->getLocation());
4044 // Need parens to enforce precedence.
4045 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4046 Exp);
4047 ReplaceStmt(DRE, PE);
4048 return PE;
4049}
4050
4051void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4052 SourceLocation LocStart = CE->getLParenLoc();
4053 SourceLocation LocEnd = CE->getRParenLoc();
4054
4055 // Need to avoid trying to rewrite synthesized casts.
4056 if (LocStart.isInvalid())
4057 return;
4058 // Need to avoid trying to rewrite casts contained in macros.
4059 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4060 return;
4061
4062 const char *startBuf = SM->getCharacterData(LocStart);
4063 const char *endBuf = SM->getCharacterData(LocEnd);
4064 QualType QT = CE->getType();
4065 const Type* TypePtr = QT->getAs<Type>();
4066 if (isa<TypeOfExprType>(TypePtr)) {
4067 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4068 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4069 std::string TypeAsString = "(";
4070 RewriteBlockPointerType(TypeAsString, QT);
4071 TypeAsString += ")";
4072 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4073 return;
4074 }
4075 // advance the location to startArgList.
4076 const char *argPtr = startBuf;
4077
4078 while (*argPtr++ && (argPtr < endBuf)) {
4079 switch (*argPtr) {
4080 case '^':
4081 // Replace the '^' with '*'.
4082 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4083 ReplaceText(LocStart, 1, "*");
4084 break;
4085 }
4086 }
4087 return;
4088}
4089
4090void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4091 SourceLocation DeclLoc = FD->getLocation();
4092 unsigned parenCount = 0;
4093
4094 // We have 1 or more arguments that have closure pointers.
4095 const char *startBuf = SM->getCharacterData(DeclLoc);
4096 const char *startArgList = strchr(startBuf, '(');
4097
4098 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4099
4100 parenCount++;
4101 // advance the location to startArgList.
4102 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4103 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4104
4105 const char *argPtr = startArgList;
4106
4107 while (*argPtr++ && parenCount) {
4108 switch (*argPtr) {
4109 case '^':
4110 // Replace the '^' with '*'.
4111 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4112 ReplaceText(DeclLoc, 1, "*");
4113 break;
4114 case '(':
4115 parenCount++;
4116 break;
4117 case ')':
4118 parenCount--;
4119 break;
4120 }
4121 }
4122 return;
4123}
4124
4125bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4126 const FunctionProtoType *FTP;
4127 const PointerType *PT = QT->getAs<PointerType>();
4128 if (PT) {
4129 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4130 } else {
4131 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4132 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4133 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4134 }
4135 if (FTP) {
4136 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4137 E = FTP->arg_type_end(); I != E; ++I)
4138 if (isTopLevelBlockPointerType(*I))
4139 return true;
4140 }
4141 return false;
4142}
4143
4144bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4145 const FunctionProtoType *FTP;
4146 const PointerType *PT = QT->getAs<PointerType>();
4147 if (PT) {
4148 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4149 } else {
4150 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4151 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4152 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4153 }
4154 if (FTP) {
4155 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4156 E = FTP->arg_type_end(); I != E; ++I) {
4157 if ((*I)->isObjCQualifiedIdType())
4158 return true;
4159 if ((*I)->isObjCObjectPointerType() &&
4160 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4161 return true;
4162 }
4163
4164 }
4165 return false;
4166}
4167
4168void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4169 const char *&RParen) {
4170 const char *argPtr = strchr(Name, '(');
4171 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4172
4173 LParen = argPtr; // output the start.
4174 argPtr++; // skip past the left paren.
4175 unsigned parenCount = 1;
4176
4177 while (*argPtr && parenCount) {
4178 switch (*argPtr) {
4179 case '(': parenCount++; break;
4180 case ')': parenCount--; break;
4181 default: break;
4182 }
4183 if (parenCount) argPtr++;
4184 }
4185 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4186 RParen = argPtr; // output the end
4187}
4188
4189void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4190 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4191 RewriteBlockPointerFunctionArgs(FD);
4192 return;
4193 }
4194 // Handle Variables and Typedefs.
4195 SourceLocation DeclLoc = ND->getLocation();
4196 QualType DeclT;
4197 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4198 DeclT = VD->getType();
4199 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4200 DeclT = TDD->getUnderlyingType();
4201 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4202 DeclT = FD->getType();
4203 else
4204 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4205
4206 const char *startBuf = SM->getCharacterData(DeclLoc);
4207 const char *endBuf = startBuf;
4208 // scan backward (from the decl location) for the end of the previous decl.
4209 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4210 startBuf--;
4211 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4212 std::string buf;
4213 unsigned OrigLength=0;
4214 // *startBuf != '^' if we are dealing with a pointer to function that
4215 // may take block argument types (which will be handled below).
4216 if (*startBuf == '^') {
4217 // Replace the '^' with '*', computing a negative offset.
4218 buf = '*';
4219 startBuf++;
4220 OrigLength++;
4221 }
4222 while (*startBuf != ')') {
4223 buf += *startBuf;
4224 startBuf++;
4225 OrigLength++;
4226 }
4227 buf += ')';
4228 OrigLength++;
4229
4230 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4231 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4232 // Replace the '^' with '*' for arguments.
4233 // Replace id<P> with id/*<>*/
4234 DeclLoc = ND->getLocation();
4235 startBuf = SM->getCharacterData(DeclLoc);
4236 const char *argListBegin, *argListEnd;
4237 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4238 while (argListBegin < argListEnd) {
4239 if (*argListBegin == '^')
4240 buf += '*';
4241 else if (*argListBegin == '<') {
4242 buf += "/*";
4243 buf += *argListBegin++;
4244 OrigLength++;;
4245 while (*argListBegin != '>') {
4246 buf += *argListBegin++;
4247 OrigLength++;
4248 }
4249 buf += *argListBegin;
4250 buf += "*/";
4251 }
4252 else
4253 buf += *argListBegin;
4254 argListBegin++;
4255 OrigLength++;
4256 }
4257 buf += ')';
4258 OrigLength++;
4259 }
4260 ReplaceText(Start, OrigLength, buf);
4261
4262 return;
4263}
4264
4265
4266/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4267/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4268/// struct Block_byref_id_object *src) {
4269/// _Block_object_assign (&_dest->object, _src->object,
4270/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4271/// [|BLOCK_FIELD_IS_WEAK]) // object
4272/// _Block_object_assign(&_dest->object, _src->object,
4273/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4274/// [|BLOCK_FIELD_IS_WEAK]) // block
4275/// }
4276/// And:
4277/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4278/// _Block_object_dispose(_src->object,
4279/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4280/// [|BLOCK_FIELD_IS_WEAK]) // object
4281/// _Block_object_dispose(_src->object,
4282/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4283/// [|BLOCK_FIELD_IS_WEAK]) // block
4284/// }
4285
4286std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4287 int flag) {
4288 std::string S;
4289 if (CopyDestroyCache.count(flag))
4290 return S;
4291 CopyDestroyCache.insert(flag);
4292 S = "static void __Block_byref_id_object_copy_";
4293 S += utostr(flag);
4294 S += "(void *dst, void *src) {\n";
4295
4296 // offset into the object pointer is computed as:
4297 // void * + void* + int + int + void* + void *
4298 unsigned IntSize =
4299 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4300 unsigned VoidPtrSize =
4301 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4302
4303 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4304 S += " _Block_object_assign((char*)dst + ";
4305 S += utostr(offset);
4306 S += ", *(void * *) ((char*)src + ";
4307 S += utostr(offset);
4308 S += "), ";
4309 S += utostr(flag);
4310 S += ");\n}\n";
4311
4312 S += "static void __Block_byref_id_object_dispose_";
4313 S += utostr(flag);
4314 S += "(void *src) {\n";
4315 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4316 S += utostr(offset);
4317 S += "), ";
4318 S += utostr(flag);
4319 S += ");\n}\n";
4320 return S;
4321}
4322
4323/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4324/// the declaration into:
4325/// struct __Block_byref_ND {
4326/// void *__isa; // NULL for everything except __weak pointers
4327/// struct __Block_byref_ND *__forwarding;
4328/// int32_t __flags;
4329/// int32_t __size;
4330/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4331/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4332/// typex ND;
4333/// };
4334///
4335/// It then replaces declaration of ND variable with:
4336/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4337/// __size=sizeof(struct __Block_byref_ND),
4338/// ND=initializer-if-any};
4339///
4340///
4341void RewriteModernObjC::RewriteByRefVar(VarDecl *ND) {
4342 // Insert declaration for the function in which block literal is
4343 // used.
4344 if (CurFunctionDeclToDeclareForBlock)
4345 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
4346 int flag = 0;
4347 int isa = 0;
4348 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4349 if (DeclLoc.isInvalid())
4350 // If type location is missing, it is because of missing type (a warning).
4351 // Use variable's location which is good for this case.
4352 DeclLoc = ND->getLocation();
4353 const char *startBuf = SM->getCharacterData(DeclLoc);
4354 SourceLocation X = ND->getLocEnd();
4355 X = SM->getExpansionLoc(X);
4356 const char *endBuf = SM->getCharacterData(X);
4357 std::string Name(ND->getNameAsString());
4358 std::string ByrefType;
4359 RewriteByRefString(ByrefType, Name, ND, true);
4360 ByrefType += " {\n";
4361 ByrefType += " void *__isa;\n";
4362 RewriteByRefString(ByrefType, Name, ND);
4363 ByrefType += " *__forwarding;\n";
4364 ByrefType += " int __flags;\n";
4365 ByrefType += " int __size;\n";
4366 // Add void *__Block_byref_id_object_copy;
4367 // void *__Block_byref_id_object_dispose; if needed.
4368 QualType Ty = ND->getType();
4369 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4370 if (HasCopyAndDispose) {
4371 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4372 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4373 }
4374
4375 QualType T = Ty;
4376 (void)convertBlockPointerToFunctionPointer(T);
4377 T.getAsStringInternal(Name, Context->getPrintingPolicy());
4378
4379 ByrefType += " " + Name + ";\n";
4380 ByrefType += "};\n";
4381 // Insert this type in global scope. It is needed by helper function.
4382 SourceLocation FunLocStart;
4383 if (CurFunctionDef)
4384 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4385 else {
4386 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4387 FunLocStart = CurMethodDef->getLocStart();
4388 }
4389 InsertText(FunLocStart, ByrefType);
4390 if (Ty.isObjCGCWeak()) {
4391 flag |= BLOCK_FIELD_IS_WEAK;
4392 isa = 1;
4393 }
4394
4395 if (HasCopyAndDispose) {
4396 flag = BLOCK_BYREF_CALLER;
4397 QualType Ty = ND->getType();
4398 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4399 if (Ty->isBlockPointerType())
4400 flag |= BLOCK_FIELD_IS_BLOCK;
4401 else
4402 flag |= BLOCK_FIELD_IS_OBJECT;
4403 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
4404 if (!HF.empty())
4405 InsertText(FunLocStart, HF);
4406 }
4407
4408 // struct __Block_byref_ND ND =
4409 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4410 // initializer-if-any};
4411 bool hasInit = (ND->getInit() != 0);
4412 unsigned flags = 0;
4413 if (HasCopyAndDispose)
4414 flags |= BLOCK_HAS_COPY_DISPOSE;
4415 Name = ND->getNameAsString();
4416 ByrefType.clear();
4417 RewriteByRefString(ByrefType, Name, ND);
4418 std::string ForwardingCastType("(");
4419 ForwardingCastType += ByrefType + " *)";
4420 if (!hasInit) {
4421 ByrefType += " " + Name + " = {(void*)";
4422 ByrefType += utostr(isa);
4423 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4424 ByrefType += utostr(flags);
4425 ByrefType += ", ";
4426 ByrefType += "sizeof(";
4427 RewriteByRefString(ByrefType, Name, ND);
4428 ByrefType += ")";
4429 if (HasCopyAndDispose) {
4430 ByrefType += ", __Block_byref_id_object_copy_";
4431 ByrefType += utostr(flag);
4432 ByrefType += ", __Block_byref_id_object_dispose_";
4433 ByrefType += utostr(flag);
4434 }
4435 ByrefType += "};\n";
4436 unsigned nameSize = Name.size();
4437 // for block or function pointer declaration. Name is aleady
4438 // part of the declaration.
4439 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4440 nameSize = 1;
4441 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
4442 }
4443 else {
4444 SourceLocation startLoc;
4445 Expr *E = ND->getInit();
4446 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4447 startLoc = ECE->getLParenLoc();
4448 else
4449 startLoc = E->getLocStart();
4450 startLoc = SM->getExpansionLoc(startLoc);
4451 endBuf = SM->getCharacterData(startLoc);
4452 ByrefType += " " + Name;
4453 ByrefType += " = {(void*)";
4454 ByrefType += utostr(isa);
4455 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4456 ByrefType += utostr(flags);
4457 ByrefType += ", ";
4458 ByrefType += "sizeof(";
4459 RewriteByRefString(ByrefType, Name, ND);
4460 ByrefType += "), ";
4461 if (HasCopyAndDispose) {
4462 ByrefType += "__Block_byref_id_object_copy_";
4463 ByrefType += utostr(flag);
4464 ByrefType += ", __Block_byref_id_object_dispose_";
4465 ByrefType += utostr(flag);
4466 ByrefType += ", ";
4467 }
4468 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
4469
4470 // Complete the newly synthesized compound expression by inserting a right
4471 // curly brace before the end of the declaration.
4472 // FIXME: This approach avoids rewriting the initializer expression. It
4473 // also assumes there is only one declarator. For example, the following
4474 // isn't currently supported by this routine (in general):
4475 //
4476 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4477 //
4478 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4479 const char *semiBuf = strchr(startInitializerBuf, ';');
4480 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4481 SourceLocation semiLoc =
4482 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
4483
4484 InsertText(semiLoc, "}");
4485 }
4486 return;
4487}
4488
4489void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4490 // Add initializers for any closure decl refs.
4491 GetBlockDeclRefExprs(Exp->getBody());
4492 if (BlockDeclRefs.size()) {
4493 // Unique all "by copy" declarations.
4494 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4495 if (!BlockDeclRefs[i]->isByRef()) {
4496 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4497 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4498 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4499 }
4500 }
4501 // Unique all "by ref" declarations.
4502 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4503 if (BlockDeclRefs[i]->isByRef()) {
4504 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4505 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4506 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4507 }
4508 }
4509 // Find any imported blocks...they will need special attention.
4510 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4511 if (BlockDeclRefs[i]->isByRef() ||
4512 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4513 BlockDeclRefs[i]->getType()->isBlockPointerType())
4514 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4515 }
4516}
4517
4518FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
4519 IdentifierInfo *ID = &Context->Idents.get(name);
4520 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
4521 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4522 SourceLocation(), ID, FType, 0, SC_Extern,
4523 SC_None, false, false);
4524}
4525
4526Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
4527 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
4528 const BlockDecl *block = Exp->getBlockDecl();
4529 Blocks.push_back(Exp);
4530
4531 CollectBlockDeclRefInfo(Exp);
4532
4533 // Add inner imported variables now used in current block.
4534 int countOfInnerDecls = 0;
4535 if (!InnerBlockDeclRefs.empty()) {
4536 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
4537 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
4538 ValueDecl *VD = Exp->getDecl();
4539 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4540 // We need to save the copied-in variables in nested
4541 // blocks because it is needed at the end for some of the API generations.
4542 // See SynthesizeBlockLiterals routine.
4543 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4544 BlockDeclRefs.push_back(Exp);
4545 BlockByCopyDeclsPtrSet.insert(VD);
4546 BlockByCopyDecls.push_back(VD);
4547 }
4548 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4549 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4550 BlockDeclRefs.push_back(Exp);
4551 BlockByRefDeclsPtrSet.insert(VD);
4552 BlockByRefDecls.push_back(VD);
4553 }
4554 }
4555 // Find any imported blocks...they will need special attention.
4556 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
4557 if (InnerBlockDeclRefs[i]->isByRef() ||
4558 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4559 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4560 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
4561 }
4562 InnerDeclRefsCount.push_back(countOfInnerDecls);
4563
4564 std::string FuncName;
4565
4566 if (CurFunctionDef)
4567 FuncName = CurFunctionDef->getNameAsString();
4568 else if (CurMethodDef)
4569 BuildUniqueMethodName(FuncName, CurMethodDef);
4570 else if (GlobalVarDecl)
4571 FuncName = std::string(GlobalVarDecl->getNameAsString());
4572
4573 std::string BlockNumber = utostr(Blocks.size()-1);
4574
4575 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4576 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4577
4578 // Get a pointer to the function type so we can cast appropriately.
4579 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4580 QualType FType = Context->getPointerType(BFT);
4581
4582 FunctionDecl *FD;
4583 Expr *NewRep;
4584
4585 // Simulate a contructor call...
4586 FD = SynthBlockInitFunctionDecl(Tag);
4587 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, VK_RValue,
4588 SourceLocation());
4589
4590 SmallVector<Expr*, 4> InitExprs;
4591
4592 // Initialize the block function.
4593 FD = SynthBlockInitFunctionDecl(Func);
4594 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4595 SourceLocation());
4596 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4597 CK_BitCast, Arg);
4598 InitExprs.push_back(castExpr);
4599
4600 // Initialize the block descriptor.
4601 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
4602
4603 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
4604 SourceLocation(), SourceLocation(),
4605 &Context->Idents.get(DescData.c_str()),
4606 Context->VoidPtrTy, 0,
4607 SC_Static, SC_None);
4608 UnaryOperator *DescRefExpr =
4609 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD,
4610 Context->VoidPtrTy,
4611 VK_LValue,
4612 SourceLocation()),
4613 UO_AddrOf,
4614 Context->getPointerType(Context->VoidPtrTy),
4615 VK_RValue, OK_Ordinary,
4616 SourceLocation());
4617 InitExprs.push_back(DescRefExpr);
4618
4619 // Add initializers for any closure decl refs.
4620 if (BlockDeclRefs.size()) {
4621 Expr *Exp;
4622 // Output all "by copy" declarations.
4623 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4624 E = BlockByCopyDecls.end(); I != E; ++I) {
4625 if (isObjCType((*I)->getType())) {
4626 // FIXME: Conform to ABI ([[obj retain] autorelease]).
4627 FD = SynthBlockInitFunctionDecl((*I)->getName());
4628 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4629 SourceLocation());
4630 if (HasLocalVariableExternalStorage(*I)) {
4631 QualType QT = (*I)->getType();
4632 QT = Context->getPointerType(QT);
4633 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4634 OK_Ordinary, SourceLocation());
4635 }
4636 } else if (isTopLevelBlockPointerType((*I)->getType())) {
4637 FD = SynthBlockInitFunctionDecl((*I)->getName());
4638 Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4639 SourceLocation());
4640 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4641 CK_BitCast, Arg);
4642 } else {
4643 FD = SynthBlockInitFunctionDecl((*I)->getName());
4644 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4645 SourceLocation());
4646 if (HasLocalVariableExternalStorage(*I)) {
4647 QualType QT = (*I)->getType();
4648 QT = Context->getPointerType(QT);
4649 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4650 OK_Ordinary, SourceLocation());
4651 }
4652
4653 }
4654 InitExprs.push_back(Exp);
4655 }
4656 // Output all "by ref" declarations.
4657 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4658 E = BlockByRefDecls.end(); I != E; ++I) {
4659 ValueDecl *ND = (*I);
4660 std::string Name(ND->getNameAsString());
4661 std::string RecName;
4662 RewriteByRefString(RecName, Name, ND, true);
4663 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4664 + sizeof("struct"));
4665 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4666 SourceLocation(), SourceLocation(),
4667 II);
4668 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4669 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4670
4671 FD = SynthBlockInitFunctionDecl((*I)->getName());
4672 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4673 SourceLocation());
4674 bool isNestedCapturedVar = false;
4675 if (block)
4676 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
4677 ce = block->capture_end(); ci != ce; ++ci) {
4678 const VarDecl *variable = ci->getVariable();
4679 if (variable == ND && ci->isNested()) {
4680 assert (ci->isByRef() &&
4681 "SynthBlockInitExpr - captured block variable is not byref");
4682 isNestedCapturedVar = true;
4683 break;
4684 }
4685 }
4686 // captured nested byref variable has its address passed. Do not take
4687 // its address again.
4688 if (!isNestedCapturedVar)
4689 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
4690 Context->getPointerType(Exp->getType()),
4691 VK_RValue, OK_Ordinary, SourceLocation());
4692 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
4693 InitExprs.push_back(Exp);
4694 }
4695 }
4696 if (ImportedBlockDecls.size()) {
4697 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4698 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
4699 unsigned IntSize =
4700 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4701 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4702 Context->IntTy, SourceLocation());
4703 InitExprs.push_back(FlagExp);
4704 }
4705 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4706 FType, VK_LValue, SourceLocation());
4707 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
4708 Context->getPointerType(NewRep->getType()),
4709 VK_RValue, OK_Ordinary, SourceLocation());
4710 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
4711 NewRep);
4712 BlockDeclRefs.clear();
4713 BlockByRefDecls.clear();
4714 BlockByRefDeclsPtrSet.clear();
4715 BlockByCopyDecls.clear();
4716 BlockByCopyDeclsPtrSet.clear();
4717 ImportedBlockDecls.clear();
4718 return NewRep;
4719}
4720
4721bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4722 if (const ObjCForCollectionStmt * CS =
4723 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4724 return CS->getElement() == DS;
4725 return false;
4726}
4727
4728//===----------------------------------------------------------------------===//
4729// Function Body / Expression rewriting
4730//===----------------------------------------------------------------------===//
4731
4732Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4733 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4734 isa<DoStmt>(S) || isa<ForStmt>(S))
4735 Stmts.push_back(S);
4736 else if (isa<ObjCForCollectionStmt>(S)) {
4737 Stmts.push_back(S);
4738 ObjCBcLabelNo.push_back(++BcLabelCount);
4739 }
4740
4741 // Pseudo-object operations and ivar references need special
4742 // treatment because we're going to recursively rewrite them.
4743 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4744 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4745 return RewritePropertyOrImplicitSetter(PseudoOp);
4746 } else {
4747 return RewritePropertyOrImplicitGetter(PseudoOp);
4748 }
4749 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4750 return RewriteObjCIvarRefExpr(IvarRefExpr);
4751 }
4752
4753 SourceRange OrigStmtRange = S->getSourceRange();
4754
4755 // Perform a bottom up rewrite of all children.
4756 for (Stmt::child_range CI = S->children(); CI; ++CI)
4757 if (*CI) {
4758 Stmt *childStmt = (*CI);
4759 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
4760 if (newStmt) {
4761 *CI = newStmt;
4762 }
4763 }
4764
4765 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4766 SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
4767 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4768 InnerContexts.insert(BE->getBlockDecl());
4769 ImportedLocalExternalDecls.clear();
4770 GetInnerBlockDeclRefExprs(BE->getBody(),
4771 InnerBlockDeclRefs, InnerContexts);
4772 // Rewrite the block body in place.
4773 Stmt *SaveCurrentBody = CurrentBody;
4774 CurrentBody = BE->getBody();
4775 PropParentMap = 0;
4776 // block literal on rhs of a property-dot-sytax assignment
4777 // must be replaced by its synthesize ast so getRewrittenText
4778 // works as expected. In this case, what actually ends up on RHS
4779 // is the blockTranscribed which is the helper function for the
4780 // block literal; as in: self.c = ^() {[ace ARR];};
4781 bool saveDisableReplaceStmt = DisableReplaceStmt;
4782 DisableReplaceStmt = false;
4783 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4784 DisableReplaceStmt = saveDisableReplaceStmt;
4785 CurrentBody = SaveCurrentBody;
4786 PropParentMap = 0;
4787 ImportedLocalExternalDecls.clear();
4788 // Now we snarf the rewritten text and stash it away for later use.
4789 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
4790 RewrittenBlockExprs[BE] = Str;
4791
4792 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4793
4794 //blockTranscribed->dump();
4795 ReplaceStmt(S, blockTranscribed);
4796 return blockTranscribed;
4797 }
4798 // Handle specific things.
4799 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4800 return RewriteAtEncode(AtEncode);
4801
4802 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4803 return RewriteAtSelector(AtSelector);
4804
4805 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4806 return RewriteObjCStringLiteral(AtString);
4807
4808 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
4809#if 0
4810 // Before we rewrite it, put the original message expression in a comment.
4811 SourceLocation startLoc = MessExpr->getLocStart();
4812 SourceLocation endLoc = MessExpr->getLocEnd();
4813
4814 const char *startBuf = SM->getCharacterData(startLoc);
4815 const char *endBuf = SM->getCharacterData(endLoc);
4816
4817 std::string messString;
4818 messString += "// ";
4819 messString.append(startBuf, endBuf-startBuf+1);
4820 messString += "\n";
4821
4822 // FIXME: Missing definition of
4823 // InsertText(clang::SourceLocation, char const*, unsigned int).
4824 // InsertText(startLoc, messString.c_str(), messString.size());
4825 // Tried this, but it didn't work either...
4826 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
4827#endif
4828 return RewriteMessageExpr(MessExpr);
4829 }
4830
4831 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4832 return RewriteObjCTryStmt(StmtTry);
4833
4834 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4835 return RewriteObjCSynchronizedStmt(StmtTry);
4836
4837 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4838 return RewriteObjCThrowStmt(StmtThrow);
4839
4840 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4841 return RewriteObjCProtocolExpr(ProtocolExp);
4842
4843 if (ObjCForCollectionStmt *StmtForCollection =
4844 dyn_cast<ObjCForCollectionStmt>(S))
4845 return RewriteObjCForCollectionStmt(StmtForCollection,
4846 OrigStmtRange.getEnd());
4847 if (BreakStmt *StmtBreakStmt =
4848 dyn_cast<BreakStmt>(S))
4849 return RewriteBreakStmt(StmtBreakStmt);
4850 if (ContinueStmt *StmtContinueStmt =
4851 dyn_cast<ContinueStmt>(S))
4852 return RewriteContinueStmt(StmtContinueStmt);
4853
4854 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4855 // and cast exprs.
4856 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4857 // FIXME: What we're doing here is modifying the type-specifier that
4858 // precedes the first Decl. In the future the DeclGroup should have
4859 // a separate type-specifier that we can rewrite.
4860 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4861 // the context of an ObjCForCollectionStmt. For example:
4862 // NSArray *someArray;
4863 // for (id <FooProtocol> index in someArray) ;
4864 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4865 // and it depends on the original text locations/positions.
4866 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
4867 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4868
4869 // Blocks rewrite rules.
4870 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4871 DI != DE; ++DI) {
4872 Decl *SD = *DI;
4873 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
4874 if (isTopLevelBlockPointerType(ND->getType()))
4875 RewriteBlockPointerDecl(ND);
4876 else if (ND->getType()->isFunctionPointerType())
4877 CheckFunctionPointerDecl(ND->getType(), ND);
4878 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
4879 if (VD->hasAttr<BlocksAttr>()) {
4880 static unsigned uniqueByrefDeclCount = 0;
4881 assert(!BlockByRefDeclNo.count(ND) &&
4882 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4883 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
4884 RewriteByRefVar(VD);
4885 }
4886 else
4887 RewriteTypeOfDecl(VD);
4888 }
4889 }
4890 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
4891 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4892 RewriteBlockPointerDecl(TD);
4893 else if (TD->getUnderlyingType()->isFunctionPointerType())
4894 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4895 }
4896 }
4897 }
4898
4899 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4900 RewriteObjCQualifiedInterfaceTypes(CE);
4901
4902 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4903 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4904 assert(!Stmts.empty() && "Statement stack is empty");
4905 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4906 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4907 && "Statement stack mismatch");
4908 Stmts.pop_back();
4909 }
4910 // Handle blocks rewriting.
4911 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4912 if (BDRE->isByRef())
4913 return RewriteBlockDeclRefExpr(BDRE);
4914 }
4915 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4916 ValueDecl *VD = DRE->getDecl();
4917 if (VD->hasAttr<BlocksAttr>())
4918 return RewriteBlockDeclRefExpr(DRE);
4919 if (HasLocalVariableExternalStorage(VD))
4920 return RewriteLocalVariableExternalStorage(DRE);
4921 }
4922
4923 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4924 if (CE->getCallee()->getType()->isBlockPointerType()) {
4925 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
4926 ReplaceStmt(S, BlockCall);
4927 return BlockCall;
4928 }
4929 }
4930 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
4931 RewriteCastExpr(CE);
4932 }
4933#if 0
4934 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4935 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4936 ICE->getSubExpr(),
4937 SourceLocation());
4938 // Get the new text.
4939 std::string SStr;
4940 llvm::raw_string_ostream Buf(SStr);
4941 Replacement->printPretty(Buf, *Context);
4942 const std::string &Str = Buf.str();
4943
4944 printf("CAST = %s\n", &Str[0]);
4945 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4946 delete S;
4947 return Replacement;
4948 }
4949#endif
4950 // Return this stmt unmodified.
4951 return S;
4952}
4953
4954void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
4955 for (RecordDecl::field_iterator i = RD->field_begin(),
4956 e = RD->field_end(); i != e; ++i) {
4957 FieldDecl *FD = *i;
4958 if (isTopLevelBlockPointerType(FD->getType()))
4959 RewriteBlockPointerDecl(FD);
4960 if (FD->getType()->isObjCQualifiedIdType() ||
4961 FD->getType()->isObjCQualifiedInterfaceType())
4962 RewriteObjCQualifiedInterfaceTypes(FD);
4963 }
4964}
4965
4966/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4967/// main file of the input.
4968void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
4969 switch (D->getKind()) {
4970 case Decl::Function: {
4971 FunctionDecl *FD = cast<FunctionDecl>(D);
4972 if (FD->isOverloadedOperator())
4973 return;
4974
4975 // Since function prototypes don't have ParmDecl's, we check the function
4976 // prototype. This enables us to rewrite function declarations and
4977 // definitions using the same code.
4978 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
4979
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00004980 if (!FD->isThisDeclarationADefinition())
4981 break;
4982
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004983 // FIXME: If this should support Obj-C++, support CXXTryStmt
4984 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4985 CurFunctionDef = FD;
4986 CurFunctionDeclToDeclareForBlock = FD;
4987 CurrentBody = Body;
4988 Body =
4989 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4990 FD->setBody(Body);
4991 CurrentBody = 0;
4992 if (PropParentMap) {
4993 delete PropParentMap;
4994 PropParentMap = 0;
4995 }
4996 // This synthesizes and inserts the block "impl" struct, invoke function,
4997 // and any copy/dispose helper functions.
4998 InsertBlockLiteralsWithinFunction(FD);
4999 CurFunctionDef = 0;
5000 CurFunctionDeclToDeclareForBlock = 0;
5001 }
5002 break;
5003 }
5004 case Decl::ObjCMethod: {
5005 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5006 if (CompoundStmt *Body = MD->getCompoundBody()) {
5007 CurMethodDef = MD;
5008 CurrentBody = Body;
5009 Body =
5010 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5011 MD->setBody(Body);
5012 CurrentBody = 0;
5013 if (PropParentMap) {
5014 delete PropParentMap;
5015 PropParentMap = 0;
5016 }
5017 InsertBlockLiteralsWithinMethod(MD);
5018 CurMethodDef = 0;
5019 }
5020 break;
5021 }
5022 case Decl::ObjCImplementation: {
5023 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5024 ClassImplementation.push_back(CI);
5025 break;
5026 }
5027 case Decl::ObjCCategoryImpl: {
5028 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5029 CategoryImplementation.push_back(CI);
5030 break;
5031 }
5032 case Decl::Var: {
5033 VarDecl *VD = cast<VarDecl>(D);
5034 RewriteObjCQualifiedInterfaceTypes(VD);
5035 if (isTopLevelBlockPointerType(VD->getType()))
5036 RewriteBlockPointerDecl(VD);
5037 else if (VD->getType()->isFunctionPointerType()) {
5038 CheckFunctionPointerDecl(VD->getType(), VD);
5039 if (VD->getInit()) {
5040 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5041 RewriteCastExpr(CE);
5042 }
5043 }
5044 } else if (VD->getType()->isRecordType()) {
5045 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5046 if (RD->isCompleteDefinition())
5047 RewriteRecordBody(RD);
5048 }
5049 if (VD->getInit()) {
5050 GlobalVarDecl = VD;
5051 CurrentBody = VD->getInit();
5052 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5053 CurrentBody = 0;
5054 if (PropParentMap) {
5055 delete PropParentMap;
5056 PropParentMap = 0;
5057 }
5058 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5059 GlobalVarDecl = 0;
5060
5061 // This is needed for blocks.
5062 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5063 RewriteCastExpr(CE);
5064 }
5065 }
5066 break;
5067 }
5068 case Decl::TypeAlias:
5069 case Decl::Typedef: {
5070 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5071 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5072 RewriteBlockPointerDecl(TD);
5073 else if (TD->getUnderlyingType()->isFunctionPointerType())
5074 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5075 }
5076 break;
5077 }
5078 case Decl::CXXRecord:
5079 case Decl::Record: {
5080 RecordDecl *RD = cast<RecordDecl>(D);
5081 if (RD->isCompleteDefinition())
5082 RewriteRecordBody(RD);
5083 break;
5084 }
5085 default:
5086 break;
5087 }
5088 // Nothing yet.
5089}
5090
5091void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5092 if (Diags.hasErrorOccurred())
5093 return;
5094
5095 RewriteInclude();
5096
5097 // Here's a great place to add any extra declarations that may be needed.
5098 // Write out meta data for each @protocol(<expr>).
5099 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
5100 E = ProtocolExprDecls.end(); I != E; ++I)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005101 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005102
5103 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian57317782012-02-21 23:58:41 +00005104 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5105 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5106 // Write struct declaration for the class matching its ivar declarations.
5107 // Note that for modern abi, this is postponed until the end of TU
5108 // because class extensions and the implementation might declare their own
5109 // private ivars.
5110 RewriteInterfaceDecl(CDecl);
5111 }
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00005112
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005113 if (ClassImplementation.size() || CategoryImplementation.size())
5114 RewriteImplementations();
5115
5116 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5117 // we are done.
5118 if (const RewriteBuffer *RewriteBuf =
5119 Rewrite.getRewriteBufferFor(MainFileID)) {
5120 //printf("Changed:\n");
5121 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5122 } else {
5123 llvm::errs() << "No changes\n";
5124 }
5125
5126 if (ClassImplementation.size() || CategoryImplementation.size() ||
5127 ProtocolExprDecls.size()) {
5128 // Rewrite Objective-c meta data*
5129 std::string ResultStr;
5130 RewriteMetaDataIntoBuffer(ResultStr);
5131 // Emit metadata.
5132 *OutFile << ResultStr;
5133 }
5134 OutFile->flush();
5135}
5136
5137void RewriteModernObjC::Initialize(ASTContext &context) {
5138 InitializeCommon(context);
5139
5140 // declaring objc_selector outside the parameter list removes a silly
5141 // scope related warning...
5142 if (IsHeader)
5143 Preamble = "#pragma once\n";
5144 Preamble += "struct objc_selector; struct objc_class;\n";
5145 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
5146 Preamble += "struct objc_object *superClass; ";
5147 if (LangOpts.MicrosoftExt) {
5148 // Add a constructor for creating temporary objects.
5149 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
5150 ": ";
5151 Preamble += "object(o), superClass(s) {} ";
5152 }
5153 Preamble += "};\n";
5154 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5155 Preamble += "typedef struct objc_object Protocol;\n";
5156 Preamble += "#define _REWRITER_typedef_Protocol\n";
5157 Preamble += "#endif\n";
5158 if (LangOpts.MicrosoftExt) {
5159 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5160 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
5161 } else
5162 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
5163 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
5164 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5165 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
5166 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5167 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
5168 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5169 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
5170 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5171 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
5172 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5173 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5174 Preamble += "(const char *);\n";
5175 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5176 Preamble += "(struct objc_class *);\n";
5177 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5178 Preamble += "(const char *);\n";
5179 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
5180 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
5181 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
5182 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
5183 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
5184 Preamble += "(struct objc_class *, struct objc_object *);\n";
5185 // @synchronized hooks.
5186 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
5187 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
5188 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5189 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5190 Preamble += "struct __objcFastEnumerationState {\n\t";
5191 Preamble += "unsigned long state;\n\t";
5192 Preamble += "void **itemsPtr;\n\t";
5193 Preamble += "unsigned long *mutationsPtr;\n\t";
5194 Preamble += "unsigned long extra[5];\n};\n";
5195 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5196 Preamble += "#define __FASTENUMERATIONSTATE\n";
5197 Preamble += "#endif\n";
5198 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5199 Preamble += "struct __NSConstantStringImpl {\n";
5200 Preamble += " int *isa;\n";
5201 Preamble += " int flags;\n";
5202 Preamble += " char *str;\n";
5203 Preamble += " long length;\n";
5204 Preamble += "};\n";
5205 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5206 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5207 Preamble += "#else\n";
5208 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5209 Preamble += "#endif\n";
5210 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5211 Preamble += "#endif\n";
5212 // Blocks preamble.
5213 Preamble += "#ifndef BLOCK_IMPL\n";
5214 Preamble += "#define BLOCK_IMPL\n";
5215 Preamble += "struct __block_impl {\n";
5216 Preamble += " void *isa;\n";
5217 Preamble += " int Flags;\n";
5218 Preamble += " int Reserved;\n";
5219 Preamble += " void *FuncPtr;\n";
5220 Preamble += "};\n";
5221 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5222 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5223 Preamble += "extern \"C\" __declspec(dllexport) "
5224 "void _Block_object_assign(void *, const void *, const int);\n";
5225 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5226 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5227 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5228 Preamble += "#else\n";
5229 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5230 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5231 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5232 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5233 Preamble += "#endif\n";
5234 Preamble += "#endif\n";
5235 if (LangOpts.MicrosoftExt) {
5236 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5237 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5238 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5239 Preamble += "#define __attribute__(X)\n";
5240 Preamble += "#endif\n";
5241 Preamble += "#define __weak\n";
5242 }
5243 else {
5244 Preamble += "#define __block\n";
5245 Preamble += "#define __weak\n";
5246 }
5247 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5248 // as this avoids warning in any 64bit/32bit compilation model.
5249 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5250}
5251
5252/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5253/// ivar offset.
5254void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5255 std::string &Result) {
5256 if (ivar->isBitField()) {
5257 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5258 // place all bitfields at offset 0.
5259 Result += "0";
5260 } else {
5261 Result += "__OFFSETOFIVAR__(struct ";
5262 Result += ivar->getContainingInterface()->getNameAsString();
5263 if (LangOpts.MicrosoftExt)
5264 Result += "_IMPL";
5265 Result += ", ";
5266 Result += ivar->getNameAsString();
5267 Result += ")";
5268 }
5269}
5270
5271/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
5272/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005273/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005274/// char *attributes;
5275/// }
5276
5277/// struct _prop_list_t {
5278/// uint32_t entsize; // sizeof(struct _prop_t)
5279/// uint32_t count_of_properties;
5280/// struct _prop_t prop_list[count_of_properties];
5281/// }
5282
5283/// struct _protocol_t;
5284
5285/// struct _protocol_list_t {
5286/// long protocol_count; // Note, this is 32/64 bit
5287/// struct _protocol_t * protocol_list[protocol_count];
5288/// }
5289
5290/// struct _objc_method {
5291/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005292/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005293/// char *_imp;
5294/// }
5295
5296/// struct _method_list_t {
5297/// uint32_t entsize; // sizeof(struct _objc_method)
5298/// uint32_t method_count;
5299/// struct _objc_method method_list[method_count];
5300/// }
5301
5302/// struct _protocol_t {
5303/// id isa; // NULL
5304/// const char * const protocol_name;
5305/// const struct _protocol_list_t * protocol_list; // super protocols
5306/// const struct method_list_t * const instance_methods;
5307/// const struct method_list_t * const class_methods;
5308/// const struct method_list_t *optionalInstanceMethods;
5309/// const struct method_list_t *optionalClassMethods;
5310/// const struct _prop_list_t * properties;
5311/// const uint32_t size; // sizeof(struct _protocol_t)
5312/// const uint32_t flags; // = 0
5313/// const char ** extendedMethodTypes;
5314/// }
5315
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005316/// struct _ivar_t {
5317/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00005318/// const char *name;
5319/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005320/// uint32_t alignment;
5321/// uint32_t size;
5322/// }
5323
5324/// struct _ivar_list_t {
5325/// uint32 entsize; // sizeof(struct _ivar_t)
5326/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00005327/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005328/// }
5329
5330/// struct _class_ro_t {
5331/// uint32_t const flags;
5332/// uint32_t const instanceStart;
5333/// uint32_t const instanceSize;
5334/// uint32_t const reserved; // only when building for 64bit targets
5335/// const uint8_t * const ivarLayout;
5336/// const char *const name;
5337/// const struct _method_list_t * const baseMethods;
Fariborz Jahanian0a525342012-02-14 19:31:35 +00005338/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005339/// const struct _ivar_list_t *const ivars;
5340/// const uint8_t * const weakIvarLayout;
5341/// const struct _prop_list_t * const properties;
5342/// }
5343
5344/// struct _class_t {
5345/// struct _class_t *isa;
5346/// struct _class_t * const superclass;
5347/// void *cache;
5348/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005349/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005350/// }
5351
5352/// struct _category_t {
5353/// const char * const name;
5354/// struct _class_t *const cls;
5355/// const struct _method_list_t * const instance_methods;
5356/// const struct _method_list_t * const class_methods;
5357/// const struct _protocol_list_t * const protocols;
5358/// const struct _prop_list_t * const properties;
5359/// }
5360
5361/// MessageRefTy - LLVM for:
5362/// struct _message_ref_t {
5363/// IMP messenger;
5364/// SEL name;
5365/// };
5366
5367/// SuperMessageRefTy - LLVM for:
5368/// struct _super_message_ref_t {
5369/// SUPER_IMP messenger;
5370/// SEL name;
5371/// };
5372
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005373static void WriteModernMetadataDeclarations(std::string &Result) {
5374 static bool meta_data_declared = false;
5375 if (meta_data_declared)
5376 return;
5377
5378 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005379 Result += "\tconst char *name;\n";
5380 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005381 Result += "};\n";
5382
5383 Result += "\nstruct _protocol_t;\n";
5384
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005385 Result += "\nstruct _objc_method {\n";
5386 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005387 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005388 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005389 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005390
5391 Result += "\nstruct _protocol_t {\n";
5392 Result += "\tvoid * isa; // NULL\n";
5393 Result += "\tconst char * const protocol_name;\n";
5394 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
5395 Result += "\tconst struct method_list_t * const instance_methods;\n";
5396 Result += "\tconst struct method_list_t * const class_methods;\n";
5397 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
5398 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
5399 Result += "\tconst struct _prop_list_t * properties;\n";
5400 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
5401 Result += "\tconst unsigned int flags; // = 0\n";
5402 Result += "\tconst char ** extendedMethodTypes;\n";
5403 Result += "};\n";
5404
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005405 Result += "\nstruct _ivar_t {\n";
5406 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005407 Result += "\tconst char *name;\n";
5408 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005409 Result += "\tunsigned int alignment;\n";
5410 Result += "\tunsigned int size;\n";
5411 Result += "};\n";
5412
5413 Result += "\nstruct _class_ro_t {\n";
5414 Result += "\tunsigned int const flags;\n";
5415 Result += "\tunsigned int instanceStart;\n";
5416 Result += "\tunsigned int const instanceSize;\n";
5417 Result += "\tunsigned int const reserved; // only when building for 64bit targets\n";
5418 Result += "\tconst unsigned char * const ivarLayout;\n";
5419 Result += "\tconst char *const name;\n";
5420 Result += "\tconst struct _method_list_t * const baseMethods;\n";
5421 Result += "\tconst struct _objc_protocol_list *const baseProtocols;\n";
5422 Result += "\tconst struct _ivar_list_t *const ivars;\n";
5423 Result += "\tconst unsigned char *const weakIvarLayout;\n";
5424 Result += "\tconst struct _prop_list_t *const properties;\n";
5425 Result += "};\n";
5426
5427 Result += "\nstruct _class_t {\n";
5428 Result += "\tstruct _class_t *isa;\n";
5429 Result += "\tstruct _class_t *const superclass;\n";
5430 Result += "\tvoid *cache;\n";
5431 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005432 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005433 Result += "};\n";
5434
5435 Result += "\nstruct _category_t {\n";
5436 Result += "\tconst char * const name;\n";
5437 Result += "\tstruct _class_t *const cls;\n";
5438 Result += "\tconst struct _method_list_t *const instance_methods;\n";
5439 Result += "\tconst struct _method_list_t *const class_methods;\n";
5440 Result += "\tconst struct _protocol_list_t *const protocols;\n";
5441 Result += "\tconst struct _prop_list_t *const properties;\n";
5442 Result += "};\n";
5443
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005444 Result += "extern void *_objc_empty_cache;\n";
5445 Result += "extern void *_objc_empty_vtable;\n";
5446
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005447 meta_data_declared = true;
5448}
5449
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005450static void Write_protocol_list_t_TypeDecl(std::string &Result,
5451 long super_protocol_count) {
5452 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
5453 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
5454 Result += "\tstruct _protocol_t *super_protocols[";
5455 Result += utostr(super_protocol_count); Result += "];\n";
5456 Result += "}";
5457}
5458
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005459static void Write_method_list_t_TypeDecl(std::string &Result,
5460 unsigned int method_count) {
5461 Result += "struct /*_method_list_t*/"; Result += " {\n";
5462 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
5463 Result += "\tunsigned int method_count;\n";
5464 Result += "\tstruct _objc_method method_list[";
5465 Result += utostr(method_count); Result += "];\n";
5466 Result += "}";
5467}
5468
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005469static void Write__prop_list_t_TypeDecl(std::string &Result,
5470 unsigned int property_count) {
5471 Result += "struct /*_prop_list_t*/"; Result += " {\n";
5472 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5473 Result += "\tunsigned int count_of_properties;\n";
5474 Result += "\tstruct _prop_t prop_list[";
5475 Result += utostr(property_count); Result += "];\n";
5476 Result += "}";
5477}
5478
Fariborz Jahanianae932952012-02-10 20:47:10 +00005479static void Write__ivar_list_t_TypeDecl(std::string &Result,
5480 unsigned int ivar_count) {
5481 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
5482 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5483 Result += "\tunsigned int count;\n";
5484 Result += "\tstruct _ivar_t ivar_list[";
5485 Result += utostr(ivar_count); Result += "];\n";
5486 Result += "}";
5487}
5488
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005489static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
5490 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
5491 StringRef VarName,
5492 StringRef ProtocolName) {
5493 if (SuperProtocols.size() > 0) {
5494 Result += "\nstatic ";
5495 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
5496 Result += " "; Result += VarName;
5497 Result += ProtocolName;
5498 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5499 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
5500 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
5501 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
5502 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
5503 Result += SuperPD->getNameAsString();
5504 if (i == e-1)
5505 Result += "\n};\n";
5506 else
5507 Result += ",\n";
5508 }
5509 }
5510}
5511
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005512static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
5513 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005514 ArrayRef<ObjCMethodDecl *> Methods,
5515 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005516 StringRef TopLevelDeclName,
5517 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005518 if (Methods.size() > 0) {
5519 Result += "\nstatic ";
5520 Write_method_list_t_TypeDecl(Result, Methods.size());
5521 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005522 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005523 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5524 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
5525 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
5526 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
5527 ObjCMethodDecl *MD = Methods[i];
5528 if (i == 0)
5529 Result += "\t{{(struct objc_selector *)\"";
5530 else
5531 Result += "\t{(struct objc_selector *)\"";
5532 Result += (MD)->getSelector().getAsString(); Result += "\"";
5533 Result += ", ";
5534 std::string MethodTypeString;
5535 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
5536 Result += "\""; Result += MethodTypeString; Result += "\"";
5537 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005538 if (!MethodImpl)
5539 Result += "0";
5540 else {
5541 Result += "(void *)";
5542 Result += RewriteObj.MethodInternalNames[MD];
5543 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005544 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005545 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005546 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005547 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005548 }
5549 Result += "};\n";
5550 }
5551}
5552
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005553static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005554 ASTContext *Context, std::string &Result,
5555 ArrayRef<ObjCPropertyDecl *> Properties,
5556 const Decl *Container,
5557 StringRef VarName,
5558 StringRef ProtocolName) {
5559 if (Properties.size() > 0) {
5560 Result += "\nstatic ";
5561 Write__prop_list_t_TypeDecl(Result, Properties.size());
5562 Result += " "; Result += VarName;
5563 Result += ProtocolName;
5564 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5565 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
5566 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
5567 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
5568 ObjCPropertyDecl *PropDecl = Properties[i];
5569 if (i == 0)
5570 Result += "\t{{\"";
5571 else
5572 Result += "\t{\"";
5573 Result += PropDecl->getName(); Result += "\",";
5574 std::string PropertyTypeString, QuotePropertyTypeString;
5575 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
5576 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
5577 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
5578 if (i == e-1)
5579 Result += "}}\n";
5580 else
5581 Result += "},\n";
5582 }
5583 Result += "};\n";
5584 }
5585}
5586
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005587// Metadata flags
5588enum MetaDataDlags {
5589 CLS = 0x0,
5590 CLS_META = 0x1,
5591 CLS_ROOT = 0x2,
5592 OBJC2_CLS_HIDDEN = 0x10,
5593 CLS_EXCEPTION = 0x20,
5594
5595 /// (Obsolete) ARC-specific: this class has a .release_ivars method
5596 CLS_HAS_IVAR_RELEASER = 0x40,
5597 /// class was compiled with -fobjc-arr
5598 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
5599};
5600
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005601static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
5602 unsigned int flags,
5603 const std::string &InstanceStart,
5604 const std::string &InstanceSize,
5605 ArrayRef<ObjCMethodDecl *>baseMethods,
5606 ArrayRef<ObjCProtocolDecl *>baseProtocols,
5607 ArrayRef<ObjCIvarDecl *>ivars,
5608 ArrayRef<ObjCPropertyDecl *>Properties,
5609 StringRef VarName,
5610 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005611 Result += "\nstatic struct _class_ro_t ";
5612 Result += VarName; Result += ClassName;
5613 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5614 Result += "\t";
5615 Result += llvm::utostr(flags); Result += ", ";
5616 Result += InstanceStart; Result += ", ";
5617 Result += InstanceSize; Result += ", \n";
5618 Result += "\t";
5619 // uint32_t const reserved; // only when building for 64bit targets
5620 Result += "(unsigned int)0, \n\t";
5621 // const uint8_t * const ivarLayout;
5622 Result += "0, \n\t";
5623 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005624 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005625 if (baseMethods.size() > 0) {
5626 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005627 if (metaclass)
5628 Result += "_OBJC_$_CLASS_METHODS_";
5629 else
5630 Result += "_OBJC_$_INSTANCE_METHODS_";
5631 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005632 Result += ",\n\t";
5633 }
5634 else
5635 Result += "0, \n\t";
5636
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005637 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005638 Result += "(const struct _objc_protocol_list *)&";
5639 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
5640 Result += ",\n\t";
5641 }
5642 else
5643 Result += "0, \n\t";
5644
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005645 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005646 Result += "(const struct _ivar_list_t *)&";
5647 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
5648 Result += ",\n\t";
5649 }
5650 else
5651 Result += "0, \n\t";
5652
5653 // weakIvarLayout
5654 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005655 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005656 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00005657 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005658 Result += ",\n";
5659 }
5660 else
5661 Result += "0, \n";
5662
5663 Result += "};\n";
5664}
5665
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005666static void Write_class_t(ASTContext *Context, std::string &Result,
5667 StringRef VarName,
5668 const ObjCInterfaceDecl *CDecl, bool metadata) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005669
5670 if (metadata && !CDecl->getSuperClass()) {
5671 // Need to handle a case of use of forward declaration.
5672 Result += "\nextern struct _class_t OBJC_CLASS_$_";
5673 Result += CDecl->getNameAsString();
5674 Result += ";\n";
5675 }
5676 // Also, for possibility of 'super' metadata class not having been defined yet.
5677 if (CDecl->getSuperClass()) {
5678 Result += "\nextern struct _class_t "; Result += VarName;
5679 Result += CDecl->getSuperClass()->getNameAsString();
5680 Result += ";\n";
5681 }
5682
5683 Result += "\nstruct _class_t "; Result += VarName; Result += CDecl->getNameAsString();
5684 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
5685 Result += "\t";
5686 if (metadata) {
5687 if (CDecl->getSuperClass()) {
5688 Result += "&"; Result += VarName;
5689 Result += CDecl->getSuperClass()->getNameAsString();
5690 Result += ",\n\t";
5691 Result += "&"; Result += VarName;
5692 Result += CDecl->getSuperClass()->getNameAsString();
5693 Result += ",\n\t";
5694 }
5695 else {
5696 Result += "&"; Result += VarName;
5697 Result += CDecl->getNameAsString();
5698 Result += ",\n\t";
5699 Result += "&OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
5700 Result += ",\n\t";
5701 }
5702 }
5703 else {
5704 Result += "&OBJC_METACLASS_$_";
5705 Result += CDecl->getNameAsString();
5706 Result += ",\n\t";
5707 if (CDecl->getSuperClass()) {
5708 Result += "&"; Result += VarName;
5709 Result += CDecl->getSuperClass()->getNameAsString();
5710 Result += ",\n\t";
5711 }
5712 else
5713 Result += "0,\n\t";
5714 }
5715 Result += "(void *)&_objc_empty_cache,\n\t";
5716 Result += "(void *)&_objc_empty_vtable,\n\t";
5717 if (metadata)
5718 Result += "&_OBJC_METACLASS_RO_$_";
5719 else
5720 Result += "&_OBJC_CLASS_RO_$_";
5721 Result += CDecl->getNameAsString();
5722 Result += ",\n};\n";
5723}
5724
Fariborz Jahanian61186122012-02-17 18:40:41 +00005725static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
5726 std::string &Result,
5727 StringRef CatName,
5728 StringRef ClassName,
5729 ArrayRef<ObjCMethodDecl *> InstanceMethods,
5730 ArrayRef<ObjCMethodDecl *> ClassMethods,
5731 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
5732 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00005733 // must declare an extern class object in case this class is not implemented
5734 // in this TU.
5735 Result += "\nextern struct _class_t ";
5736 Result += "OBJC_CLASS_$_"; Result += ClassName;
5737 Result += ";\n";
5738
Fariborz Jahanian61186122012-02-17 18:40:41 +00005739 Result += "\nstatic struct _category_t ";
5740 Result += "_OBJC_$_CATEGORY_";
5741 Result += ClassName; Result += "_$_"; Result += CatName;
5742 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
5743 Result += "{\n";
5744 Result += "\t\""; Result += ClassName; Result += "\",\n";
5745 Result += "\t&"; Result += "OBJC_CLASS_$_"; Result += ClassName;
5746 Result += ",\n";
5747 if (InstanceMethods.size() > 0) {
5748 Result += "\t(const struct _method_list_t *)&";
5749 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
5750 Result += ClassName; Result += "_$_"; Result += CatName;
5751 Result += ",\n";
5752 }
5753 else
5754 Result += "\t0,\n";
5755
5756 if (ClassMethods.size() > 0) {
5757 Result += "\t(const struct _method_list_t *)&";
5758 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
5759 Result += ClassName; Result += "_$_"; Result += CatName;
5760 Result += ",\n";
5761 }
5762 else
5763 Result += "\t0,\n";
5764
5765 if (RefedProtocols.size() > 0) {
5766 Result += "\t(const struct _protocol_list_t *)&";
5767 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
5768 Result += ClassName; Result += "_$_"; Result += CatName;
5769 Result += ",\n";
5770 }
5771 else
5772 Result += "\t0,\n";
5773
5774 if (ClassProperties.size() > 0) {
5775 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
5776 Result += ClassName; Result += "_$_"; Result += CatName;
5777 Result += ",\n";
5778 }
5779 else
5780 Result += "\t0,\n";
5781
5782 Result += "};\n";
5783}
5784
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00005785static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
5786 ASTContext *Context, std::string &Result,
5787 ArrayRef<ObjCMethodDecl *> Methods,
5788 StringRef VarName,
5789 StringRef ProtocolName) {
5790 if (Methods.size() == 0)
5791 return;
5792
5793 Result += "\nstatic const char *";
5794 Result += VarName; Result += ProtocolName;
5795 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
5796 Result += "{\n";
5797 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
5798 ObjCMethodDecl *MD = Methods[i];
5799 std::string MethodTypeString, QuoteMethodTypeString;
5800 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
5801 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
5802 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
5803 if (i == e-1)
5804 Result += "\n};\n";
5805 else {
5806 Result += ",\n";
5807 }
5808 }
5809}
5810
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005811static void Write_IvarOffsetVar(std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005812 ArrayRef<ObjCIvarDecl *> Ivars,
5813 StringRef VarName,
5814 StringRef ClassName) {
5815 // FIXME. visibilty of offset symbols may have to be set; for Darwin
5816 // this is what happens:
5817 /**
5818 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
5819 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
5820 Class->getVisibility() == HiddenVisibility)
5821 Visibility shoud be: HiddenVisibility;
5822 else
5823 Visibility shoud be: DefaultVisibility;
5824 */
5825
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005826 Result += "\n";
5827 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
5828 ObjCIvarDecl *IvarDecl = Ivars[i];
5829 Result += "unsigned long int "; Result += VarName;
5830 Result += ClassName; Result += "_";
5831 Result += IvarDecl->getName();
5832 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
5833 Result += " = ";
5834 if (IvarDecl->isBitField()) {
5835 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5836 // place all bitfields at offset 0.
5837 Result += "0;\n";
5838 }
5839 else {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005840 Result += "__OFFSETOFIVAR__(struct ";
5841 Result += ClassName;
5842 Result += "_IMPL, ";
5843 Result += IvarDecl->getName(); Result += ");\n";
5844 }
5845 }
5846}
5847
Fariborz Jahanianae932952012-02-10 20:47:10 +00005848static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
5849 ASTContext *Context, std::string &Result,
5850 ArrayRef<ObjCIvarDecl *> Ivars,
5851 StringRef VarName,
5852 StringRef ClassName) {
5853 if (Ivars.size() > 0) {
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005854 Write_IvarOffsetVar(Result, Ivars, "OBJC_IVAR_$_", ClassName);
5855
Fariborz Jahanianae932952012-02-10 20:47:10 +00005856 Result += "\nstatic ";
5857 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
5858 Result += " "; Result += VarName;
5859 Result += ClassName;
5860 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5861 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
5862 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
5863 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
5864 ObjCIvarDecl *IvarDecl = Ivars[i];
5865 if (i == 0)
5866 Result += "\t{{";
5867 else
5868 Result += "\t {";
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005869
5870 Result += "(unsigned long int *)&OBJC_IVAR_$_";
5871 Result += ClassName; Result += "_"; Result += IvarDecl->getName();
5872 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005873
5874 Result += "\""; Result += IvarDecl->getName(); Result += "\", ";
5875 std::string IvarTypeString, QuoteIvarTypeString;
5876 Context->getObjCEncodingForType(IvarDecl->getType(), IvarTypeString,
5877 IvarDecl);
5878 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
5879 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
5880
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00005881 // FIXME. this alignment represents the host alignment and need be changed to
5882 // represent the target alignment.
5883 unsigned Align = Context->getTypeAlign(IvarDecl->getType())/8;
5884 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00005885 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00005886 CharUnits Size = Context->getTypeSizeInChars(IvarDecl->getType());
5887 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00005888 if (i == e-1)
5889 Result += "}}\n";
5890 else
5891 Result += "},\n";
5892 }
5893 Result += "};\n";
5894 }
5895}
5896
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005897/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005898void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
5899 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005900
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005901 // Do not synthesize the protocol more than once.
5902 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
5903 return;
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005904 WriteModernMetadataDeclarations(Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005905
5906 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
5907 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005908 // Must write out all protocol definitions in current qualifier list,
5909 // and in their nested qualifiers before writing out current definition.
5910 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
5911 E = PDecl->protocol_end(); I != E; ++I)
5912 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005913
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005914 // Construct method lists.
5915 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
5916 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
5917 for (ObjCProtocolDecl::instmeth_iterator
5918 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
5919 I != E; ++I) {
5920 ObjCMethodDecl *MD = *I;
5921 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
5922 OptInstanceMethods.push_back(MD);
5923 } else {
5924 InstanceMethods.push_back(MD);
5925 }
5926 }
5927
5928 for (ObjCProtocolDecl::classmeth_iterator
5929 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
5930 I != E; ++I) {
5931 ObjCMethodDecl *MD = *I;
5932 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
5933 OptClassMethods.push_back(MD);
5934 } else {
5935 ClassMethods.push_back(MD);
5936 }
5937 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00005938 std::vector<ObjCMethodDecl *> AllMethods;
5939 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
5940 AllMethods.push_back(InstanceMethods[i]);
5941 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
5942 AllMethods.push_back(ClassMethods[i]);
5943 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
5944 AllMethods.push_back(OptInstanceMethods[i]);
5945 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
5946 AllMethods.push_back(OptClassMethods[i]);
5947
5948 Write__extendedMethodTypes_initializer(*this, Context, Result,
5949 AllMethods,
5950 "_OBJC_PROTOCOL_METHOD_TYPES_",
5951 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005952 // Protocol's super protocol list
5953 std::vector<ObjCProtocolDecl *> SuperProtocols;
5954 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
5955 E = PDecl->protocol_end(); I != E; ++I)
5956 SuperProtocols.push_back(*I);
5957
5958 Write_protocol_list_initializer(Context, Result, SuperProtocols,
5959 "_OBJC_PROTOCOL_REFS_",
5960 PDecl->getNameAsString());
5961
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005962 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005963 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005964 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005965
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005966 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005967 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005968 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005969
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005970 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005971 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005972 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005973
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005974 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005975 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005976 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005977
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005978 // Protocol's property metadata.
5979 std::vector<ObjCPropertyDecl *> ProtocolProperties;
5980 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
5981 E = PDecl->prop_end(); I != E; ++I)
5982 ProtocolProperties.push_back(*I);
5983
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005984 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005985 /* Container */0,
5986 "_OBJC_PROTOCOL_PROPERTIES_",
5987 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005988
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005989 // Writer out root metadata for current protocol: struct _protocol_t
5990 Result += "\nstatic struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005991 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005992 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
5993 Result += "\t0,\n"; // id is; is null
5994 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005995 if (SuperProtocols.size() > 0) {
5996 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
5997 Result += PDecl->getNameAsString(); Result += ",\n";
5998 }
5999 else
6000 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006001 if (InstanceMethods.size() > 0) {
6002 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
6003 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006004 }
6005 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006006 Result += "\t0,\n";
6007
6008 if (ClassMethods.size() > 0) {
6009 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
6010 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006011 }
6012 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006013 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006014
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006015 if (OptInstanceMethods.size() > 0) {
6016 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
6017 Result += PDecl->getNameAsString(); Result += ",\n";
6018 }
6019 else
6020 Result += "\t0,\n";
6021
6022 if (OptClassMethods.size() > 0) {
6023 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
6024 Result += PDecl->getNameAsString(); Result += ",\n";
6025 }
6026 else
6027 Result += "\t0,\n";
6028
6029 if (ProtocolProperties.size() > 0) {
6030 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
6031 Result += PDecl->getNameAsString(); Result += ",\n";
6032 }
6033 else
6034 Result += "\t0,\n";
6035
6036 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6037 Result += "\t0,\n";
6038
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006039 if (AllMethods.size() > 0) {
6040 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6041 Result += PDecl->getNameAsString();
6042 Result += "\n};\n";
6043 }
6044 else
6045 Result += "\t0\n};\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006046
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006047 // Mark this protocol as having been generated.
6048 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
6049 llvm_unreachable("protocol already synthesized");
6050
6051}
6052
6053void RewriteModernObjC::RewriteObjCProtocolListMetaData(
6054 const ObjCList<ObjCProtocolDecl> &Protocols,
6055 StringRef prefix, StringRef ClassName,
6056 std::string &Result) {
6057 if (Protocols.empty()) return;
6058
6059 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006060 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006061
6062 // Output the top lovel protocol meta-data for the class.
6063 /* struct _objc_protocol_list {
6064 struct _objc_protocol_list *next;
6065 int protocol_count;
6066 struct _objc_protocol *class_protocols[];
6067 }
6068 */
6069 Result += "\nstatic struct {\n";
6070 Result += "\tstruct _objc_protocol_list *next;\n";
6071 Result += "\tint protocol_count;\n";
6072 Result += "\tstruct _objc_protocol *class_protocols[";
6073 Result += utostr(Protocols.size());
6074 Result += "];\n} _OBJC_";
6075 Result += prefix;
6076 Result += "_PROTOCOLS_";
6077 Result += ClassName;
6078 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
6079 "{\n\t0, ";
6080 Result += utostr(Protocols.size());
6081 Result += "\n";
6082
6083 Result += "\t,{&_OBJC_PROTOCOL_";
6084 Result += Protocols[0]->getNameAsString();
6085 Result += " \n";
6086
6087 for (unsigned i = 1; i != Protocols.size(); i++) {
6088 Result += "\t ,&_OBJC_PROTOCOL_";
6089 Result += Protocols[i]->getNameAsString();
6090 Result += "\n";
6091 }
6092 Result += "\t }\n};\n";
6093}
6094
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006095/// hasObjCExceptionAttribute - Return true if this class or any super
6096/// class has the __objc_exception__ attribute.
6097/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
6098static bool hasObjCExceptionAttribute(ASTContext &Context,
6099 const ObjCInterfaceDecl *OID) {
6100 if (OID->hasAttr<ObjCExceptionAttr>())
6101 return true;
6102 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
6103 return hasObjCExceptionAttribute(Context, Super);
6104 return false;
6105}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006106
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006107void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
6108 std::string &Result) {
6109 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6110
6111 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00006112 if (CDecl->isImplicitInterfaceDecl())
6113 assert(false &&
6114 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006115
Fariborz Jahanianae932952012-02-10 20:47:10 +00006116 WriteModernMetadataDeclarations(Result);
6117 SmallVector<ObjCIvarDecl *, 8> IVars;
6118
6119 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6120 IVD; IVD = IVD->getNextIvar()) {
6121 // Ignore unnamed bit-fields.
6122 if (!IVD->getDeclName())
6123 continue;
6124 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006125 }
6126
Fariborz Jahanianae932952012-02-10 20:47:10 +00006127 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006128 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanianae932952012-02-10 20:47:10 +00006129 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006130
6131 // Build _objc_method_list for class's instance methods if needed
6132 SmallVector<ObjCMethodDecl *, 32>
6133 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6134
6135 // If any of our property implementations have associated getters or
6136 // setters, produce metadata for them as well.
6137 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6138 PropEnd = IDecl->propimpl_end();
6139 Prop != PropEnd; ++Prop) {
6140 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6141 continue;
6142 if (!(*Prop)->getPropertyIvarDecl())
6143 continue;
6144 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
6145 if (!PD)
6146 continue;
6147 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
6148 if (!Getter->isDefined())
6149 InstanceMethods.push_back(Getter);
6150 if (PD->isReadOnly())
6151 continue;
6152 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
6153 if (!Setter->isDefined())
6154 InstanceMethods.push_back(Setter);
6155 }
6156
6157 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6158 "_OBJC_$_INSTANCE_METHODS_",
6159 IDecl->getNameAsString(), true);
6160
6161 SmallVector<ObjCMethodDecl *, 32>
6162 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6163
6164 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6165 "_OBJC_$_CLASS_METHODS_",
6166 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00006167
6168 // Protocols referenced in class declaration?
6169 // Protocol's super protocol list
6170 std::vector<ObjCProtocolDecl *> RefedProtocols;
6171 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
6172 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6173 E = Protocols.end();
6174 I != E; ++I) {
6175 RefedProtocols.push_back(*I);
6176 // Must write out all protocol definitions in current qualifier list,
6177 // and in their nested qualifiers before writing out current definition.
6178 RewriteObjCProtocolMetaData(*I, Result);
6179 }
6180
6181 Write_protocol_list_initializer(Context, Result,
6182 RefedProtocols,
6183 "_OBJC_CLASS_PROTOCOLS_$_",
6184 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006185
6186 // Protocol's property metadata.
6187 std::vector<ObjCPropertyDecl *> ClassProperties;
6188 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6189 E = CDecl->prop_end(); I != E; ++I)
6190 ClassProperties.push_back(*I);
6191
6192 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
6193 /* Container */0,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006194 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006195 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006196
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006197
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006198 // Data for initializing _class_ro_t metaclass meta-data
6199 uint32_t flags = CLS_META;
6200 std::string InstanceSize;
6201 std::string InstanceStart;
6202
6203
6204 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
6205 if (classIsHidden)
6206 flags |= OBJC2_CLS_HIDDEN;
6207
6208 if (!CDecl->getSuperClass())
6209 // class is root
6210 flags |= CLS_ROOT;
6211 InstanceSize = "sizeof(struct _class_t)";
6212 InstanceStart = InstanceSize;
6213 Write__class_ro_t_initializer(Context, Result, flags,
6214 InstanceStart, InstanceSize,
6215 ClassMethods,
6216 0,
6217 0,
6218 0,
6219 "_OBJC_METACLASS_RO_$_",
6220 CDecl->getNameAsString());
6221
6222
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006223 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006224 flags = CLS;
6225 if (classIsHidden)
6226 flags |= OBJC2_CLS_HIDDEN;
6227
6228 if (hasObjCExceptionAttribute(*Context, CDecl))
6229 flags |= CLS_EXCEPTION;
6230
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006231 if (!CDecl->getSuperClass())
6232 // class is root
6233 flags |= CLS_ROOT;
6234
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006235 InstanceSize.clear();
6236 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006237 if (!ObjCSynthesizedStructs.count(CDecl)) {
6238 InstanceSize = "0";
6239 InstanceStart = "0";
6240 }
6241 else {
6242 InstanceSize = "sizeof(struct ";
6243 InstanceSize += CDecl->getNameAsString();
6244 InstanceSize += "_IMPL)";
6245
6246 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6247 if (IVD) {
6248 InstanceStart += "__OFFSETOFIVAR__(struct ";
6249 InstanceStart += CDecl->getNameAsString();
6250 InstanceStart += "_IMPL, ";
6251 InstanceStart += IVD->getNameAsString();
6252 InstanceStart += ")";
6253 }
6254 else
6255 InstanceStart = InstanceSize;
6256 }
6257 Write__class_ro_t_initializer(Context, Result, flags,
6258 InstanceStart, InstanceSize,
6259 InstanceMethods,
6260 RefedProtocols,
6261 IVars,
6262 ClassProperties,
6263 "_OBJC_CLASS_RO_$_",
6264 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006265
6266 Write_class_t(Context, Result,
6267 "OBJC_METACLASS_$_",
6268 CDecl, /*metaclass*/true);
6269
6270 Write_class_t(Context, Result,
6271 "OBJC_CLASS_$_",
6272 CDecl, /*metaclass*/false);
6273
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006274}
6275
6276void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
6277 int ClsDefCount = ClassImplementation.size();
6278 int CatDefCount = CategoryImplementation.size();
6279
6280 // For each implemented class, write out all its meta data.
6281 for (int i = 0; i < ClsDefCount; i++)
6282 RewriteObjCClassMetaData(ClassImplementation[i], Result);
6283
6284 // For each implemented category, write out all its meta data.
6285 for (int i = 0; i < CatDefCount; i++)
6286 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
6287
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006288 if (ClsDefCount > 0) {
6289 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
6290 Result += llvm::utostr(ClsDefCount); Result += "]";
6291 Result +=
6292 " __attribute__((used, section (\"__DATA, __objc_classlist,"
6293 "regular,no_dead_strip\")))= {\n";
6294 for (int i = 0; i < ClsDefCount; i++) {
6295 Result += "\t&OBJC_CLASS_$_";
6296 Result += ClassImplementation[i]->getNameAsString();
6297 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006298 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006299 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006300 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00006301
6302 if (CatDefCount > 0) {
6303 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
6304 Result += llvm::utostr(CatDefCount); Result += "]";
6305 Result +=
6306 " __attribute__((used, section (\"__DATA, __objc_catlist,"
6307 "regular,no_dead_strip\")))= {\n";
6308 for (int i = 0; i < CatDefCount; i++) {
6309 Result += "\t&_OBJC_$_CATEGORY_";
6310 Result +=
6311 CategoryImplementation[i]->getClassInterface()->getNameAsString();
6312 Result += "_$_";
6313 Result += CategoryImplementation[i]->getNameAsString();
6314 Result += ",\n";
6315 }
6316 Result += "};\n";
6317 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006318}
6319
6320/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
6321/// implementation.
6322void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
6323 std::string &Result) {
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006324 WriteModernMetadataDeclarations(Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006325 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
6326 // Find category declaration for this implementation.
Fariborz Jahanian61186122012-02-17 18:40:41 +00006327 ObjCCategoryDecl *CDecl=0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006328 for (CDecl = ClassDecl->getCategoryList(); CDecl;
6329 CDecl = CDecl->getNextClassCategory())
6330 if (CDecl->getIdentifier() == IDecl->getIdentifier())
6331 break;
6332
6333 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00006334 FullCategoryName += "_$_";
6335 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006336
6337 // Build _objc_method_list for class's instance methods if needed
6338 SmallVector<ObjCMethodDecl *, 32>
6339 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6340
6341 // If any of our property implementations have associated getters or
6342 // setters, produce metadata for them as well.
6343 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6344 PropEnd = IDecl->propimpl_end();
6345 Prop != PropEnd; ++Prop) {
6346 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6347 continue;
6348 if (!(*Prop)->getPropertyIvarDecl())
6349 continue;
6350 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
6351 if (!PD)
6352 continue;
6353 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
6354 InstanceMethods.push_back(Getter);
6355 if (PD->isReadOnly())
6356 continue;
6357 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
6358 InstanceMethods.push_back(Setter);
6359 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006360
Fariborz Jahanian61186122012-02-17 18:40:41 +00006361 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6362 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
6363 FullCategoryName, true);
6364
6365 SmallVector<ObjCMethodDecl *, 32>
6366 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6367
6368 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6369 "_OBJC_$_CATEGORY_CLASS_METHODS_",
6370 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006371
6372 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00006373 // Protocol's super protocol list
6374 std::vector<ObjCProtocolDecl *> RefedProtocols;
6375 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
6376 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6377 E = Protocols.end();
6378 I != E; ++I) {
6379 RefedProtocols.push_back(*I);
6380 // Must write out all protocol definitions in current qualifier list,
6381 // and in their nested qualifiers before writing out current definition.
6382 RewriteObjCProtocolMetaData(*I, Result);
6383 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006384
Fariborz Jahanian61186122012-02-17 18:40:41 +00006385 Write_protocol_list_initializer(Context, Result,
6386 RefedProtocols,
6387 "_OBJC_CATEGORY_PROTOCOLS_$_",
6388 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006389
Fariborz Jahanian61186122012-02-17 18:40:41 +00006390 // Protocol's property metadata.
6391 std::vector<ObjCPropertyDecl *> ClassProperties;
6392 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6393 E = CDecl->prop_end(); I != E; ++I)
6394 ClassProperties.push_back(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006395
Fariborz Jahanian61186122012-02-17 18:40:41 +00006396 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
6397 /* Container */0,
6398 "_OBJC_$_PROP_LIST_",
6399 FullCategoryName);
6400
6401 Write_category_t(*this, Context, Result,
6402 CDecl->getNameAsString(),
6403 ClassDecl->getNameAsString(),
6404 InstanceMethods,
6405 ClassMethods,
6406 RefedProtocols,
6407 ClassProperties);
6408
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006409}
6410
6411// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
6412/// class methods.
6413template<typename MethodIterator>
6414void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
6415 MethodIterator MethodEnd,
6416 bool IsInstanceMethod,
6417 StringRef prefix,
6418 StringRef ClassName,
6419 std::string &Result) {
6420 if (MethodBegin == MethodEnd) return;
6421
6422 if (!objc_impl_method) {
6423 /* struct _objc_method {
6424 SEL _cmd;
6425 char *method_types;
6426 void *_imp;
6427 }
6428 */
6429 Result += "\nstruct _objc_method {\n";
6430 Result += "\tSEL _cmd;\n";
6431 Result += "\tchar *method_types;\n";
6432 Result += "\tvoid *_imp;\n";
6433 Result += "};\n";
6434
6435 objc_impl_method = true;
6436 }
6437
6438 // Build _objc_method_list for class's methods if needed
6439
6440 /* struct {
6441 struct _objc_method_list *next_method;
6442 int method_count;
6443 struct _objc_method method_list[];
6444 }
6445 */
6446 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
6447 Result += "\nstatic struct {\n";
6448 Result += "\tstruct _objc_method_list *next_method;\n";
6449 Result += "\tint method_count;\n";
6450 Result += "\tstruct _objc_method method_list[";
6451 Result += utostr(NumMethods);
6452 Result += "];\n} _OBJC_";
6453 Result += prefix;
6454 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
6455 Result += "_METHODS_";
6456 Result += ClassName;
6457 Result += " __attribute__ ((used, section (\"__OBJC, __";
6458 Result += IsInstanceMethod ? "inst" : "cls";
6459 Result += "_meth\")))= ";
6460 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
6461
6462 Result += "\t,{{(SEL)\"";
6463 Result += (*MethodBegin)->getSelector().getAsString().c_str();
6464 std::string MethodTypeString;
6465 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
6466 Result += "\", \"";
6467 Result += MethodTypeString;
6468 Result += "\", (void *)";
6469 Result += MethodInternalNames[*MethodBegin];
6470 Result += "}\n";
6471 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
6472 Result += "\t ,{(SEL)\"";
6473 Result += (*MethodBegin)->getSelector().getAsString().c_str();
6474 std::string MethodTypeString;
6475 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
6476 Result += "\", \"";
6477 Result += MethodTypeString;
6478 Result += "\", (void *)";
6479 Result += MethodInternalNames[*MethodBegin];
6480 Result += "}\n";
6481 }
6482 Result += "\t }\n};\n";
6483}
6484
6485Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
6486 SourceRange OldRange = IV->getSourceRange();
6487 Expr *BaseExpr = IV->getBase();
6488
6489 // Rewrite the base, but without actually doing replaces.
6490 {
6491 DisableReplaceStmtScope S(*this);
6492 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
6493 IV->setBase(BaseExpr);
6494 }
6495
6496 ObjCIvarDecl *D = IV->getDecl();
6497
6498 Expr *Replacement = IV;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006499
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006500 if (BaseExpr->getType()->isObjCObjectPointerType()) {
6501 const ObjCInterfaceType *iFaceDecl =
6502 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
6503 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
6504 // lookup which class implements the instance variable.
6505 ObjCInterfaceDecl *clsDeclared = 0;
6506 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
6507 clsDeclared);
6508 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
6509
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006510 // Build name of symbol holding ivar offset.
6511 std::string IvarOffsetName = "OBJC_IVAR_$_";
6512 IvarOffsetName += clsDeclared->getIdentifier()->getName();
6513 IvarOffsetName += "_";
6514 IvarOffsetName += D->getName();
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00006515 ReferencedIvars[clsDeclared].insert(D);
6516
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006517 // cast offset to "char *".
6518 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
6519 Context->getPointerType(Context->CharTy),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006520 CK_BitCast,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006521 BaseExpr);
6522 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
6523 SourceLocation(), &Context->Idents.get(IvarOffsetName),
6524 Context->UnsignedLongTy, 0, SC_Extern, SC_None);
6525 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, Context->UnsignedLongTy, VK_LValue,
6526 SourceLocation());
6527 BinaryOperator *addExpr =
6528 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
6529 Context->getPointerType(Context->CharTy),
6530 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006531 // Don't forget the parens to enforce the proper binding.
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006532 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
6533 SourceLocation(),
6534 addExpr);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00006535 QualType IvarT = D->getType();
6536 convertBlockPointerToFunctionPointer(IvarT);
6537 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006538
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006539 castExpr = NoTypeInfoCStyleCastExpr(Context,
6540 castT,
6541 CK_BitCast,
6542 PE);
6543 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, castT,
6544 VK_LValue, OK_Ordinary,
6545 SourceLocation());
6546 PE = new (Context) ParenExpr(OldRange.getBegin(),
6547 OldRange.getEnd(),
6548 Exp);
6549
6550 Replacement = PE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006551 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006552
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006553 ReplaceStmtWithRange(IV, Replacement, OldRange);
6554 return Replacement;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006555}
6556