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