blob: c0e5f0e41b9c074e54c62a0ec6d408ac5ee20375 [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();
3135 int NumIvars = CDecl->ivar_size();
3136 SourceLocation LocStart = CDecl->getLocStart();
3137 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
3138
3139 const char *startBuf = SM->getCharacterData(LocStart);
3140 const char *endBuf = SM->getCharacterData(LocEnd);
3141
3142 // If no ivars and no root or if its root, directly or indirectly,
3143 // have no ivars (thus not synthesized) then no need to synthesize this class.
3144 if ((!CDecl->isThisDeclarationADefinition() || NumIvars == 0) &&
3145 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3146 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3147 ReplaceText(LocStart, endBuf-startBuf, Result);
3148 return;
3149 }
3150
3151 // FIXME: This has potential of causing problem. If
3152 // SynthesizeObjCInternalStruct is ever called recursively.
3153 Result += "\nstruct ";
3154 Result += CDecl->getNameAsString();
3155 if (LangOpts.MicrosoftExt)
3156 Result += "_IMPL";
3157
3158 if (NumIvars > 0) {
3159 const char *cursor = strchr(startBuf, '{');
3160 assert((cursor && endBuf)
3161 && "SynthesizeObjCInternalStruct - malformed @interface");
3162 // If the buffer contains preprocessor directives, we do more fine-grained
3163 // rewrites. This is intended to fix code that looks like (which occurs in
3164 // NSURL.h, for example):
3165 //
3166 // #ifdef XYZ
3167 // @interface Foo : NSObject
3168 // #else
3169 // @interface FooBar : NSObject
3170 // #endif
3171 // {
3172 // int i;
3173 // }
3174 // @end
3175 //
3176 // This clause is segregated to avoid breaking the common case.
3177 if (BufferContainsPPDirectives(startBuf, cursor)) {
3178 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
3179 CDecl->getAtStartLoc();
3180 const char *endHeader = SM->getCharacterData(L);
3181 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
3182
3183 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
3184 // advance to the end of the referenced protocols.
3185 while (endHeader < cursor && *endHeader != '>') endHeader++;
3186 endHeader++;
3187 }
3188 // rewrite the original header
3189 ReplaceText(LocStart, endHeader-startBuf, Result);
3190 } else {
3191 // rewrite the original header *without* disturbing the '{'
3192 ReplaceText(LocStart, cursor-startBuf, Result);
3193 }
3194 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
3195 Result = "\n struct ";
3196 Result += RCDecl->getNameAsString();
3197 Result += "_IMPL ";
3198 Result += RCDecl->getNameAsString();
3199 Result += "_IVARS;\n";
3200
3201 // insert the super class structure definition.
3202 SourceLocation OnePastCurly =
3203 LocStart.getLocWithOffset(cursor-startBuf+1);
3204 InsertText(OnePastCurly, Result);
3205 }
3206 cursor++; // past '{'
3207
3208 // Now comment out any visibility specifiers.
3209 while (cursor < endBuf) {
3210 if (*cursor == '@') {
3211 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
3212 // Skip whitespace.
3213 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3214 /*scan*/;
3215
3216 // FIXME: presence of @public, etc. inside comment results in
3217 // this transformation as well, which is still correct c-code.
3218 if (!strncmp(cursor, "public", strlen("public")) ||
3219 !strncmp(cursor, "private", strlen("private")) ||
3220 !strncmp(cursor, "package", strlen("package")) ||
3221 !strncmp(cursor, "protected", strlen("protected")))
3222 InsertText(atLoc, "// ");
3223 }
3224 // FIXME: If there are cases where '<' is used in ivar declaration part
3225 // of user code, then scan the ivar list and use needToScanForQualifiers
3226 // for type checking.
3227 else if (*cursor == '<') {
3228 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
3229 InsertText(atLoc, "/* ");
3230 cursor = strchr(cursor, '>');
3231 cursor++;
3232 atLoc = LocStart.getLocWithOffset(cursor-startBuf);
3233 InsertText(atLoc, " */");
3234 } else if (*cursor == '^') { // rewrite block specifier.
3235 SourceLocation caretLoc = LocStart.getLocWithOffset(cursor-startBuf);
3236 ReplaceText(caretLoc, 1, "*");
3237 }
3238 cursor++;
3239 }
3240 // Don't forget to add a ';'!!
3241 InsertText(LocEnd.getLocWithOffset(1), ";");
3242 } else { // we don't have any instance variables - insert super struct.
3243 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3244 Result += " {\n struct ";
3245 Result += RCDecl->getNameAsString();
3246 Result += "_IMPL ";
3247 Result += RCDecl->getNameAsString();
3248 Result += "_IVARS;\n};\n";
3249 ReplaceText(LocStart, endBuf-startBuf, Result);
3250 }
3251 // Mark this struct as having been generated.
3252 if (!ObjCSynthesizedStructs.insert(CDecl))
3253 llvm_unreachable("struct already synthesize- SynthesizeObjCInternalStruct");
3254}
3255
3256//===----------------------------------------------------------------------===//
3257// Meta Data Emission
3258//===----------------------------------------------------------------------===//
3259
3260
3261/// RewriteImplementations - This routine rewrites all method implementations
3262/// and emits meta-data.
3263
3264void RewriteModernObjC::RewriteImplementations() {
3265 int ClsDefCount = ClassImplementation.size();
3266 int CatDefCount = CategoryImplementation.size();
3267
3268 // Rewrite implemented methods
3269 for (int i = 0; i < ClsDefCount; i++)
3270 RewriteImplementationDecl(ClassImplementation[i]);
3271
3272 for (int i = 0; i < CatDefCount; i++)
3273 RewriteImplementationDecl(CategoryImplementation[i]);
3274}
3275
3276void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
3277 const std::string &Name,
3278 ValueDecl *VD, bool def) {
3279 assert(BlockByRefDeclNo.count(VD) &&
3280 "RewriteByRefString: ByRef decl missing");
3281 if (def)
3282 ResultStr += "struct ";
3283 ResultStr += "__Block_byref_" + Name +
3284 "_" + utostr(BlockByRefDeclNo[VD]) ;
3285}
3286
3287static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3288 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3289 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3290 return false;
3291}
3292
3293std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3294 StringRef funcName,
3295 std::string Tag) {
3296 const FunctionType *AFT = CE->getFunctionType();
3297 QualType RT = AFT->getResultType();
3298 std::string StructRef = "struct " + Tag;
3299 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
3300 funcName.str() + "_" + "block_func_" + utostr(i);
3301
3302 BlockDecl *BD = CE->getBlockDecl();
3303
3304 if (isa<FunctionNoProtoType>(AFT)) {
3305 // No user-supplied arguments. Still need to pass in a pointer to the
3306 // block (to reference imported block decl refs).
3307 S += "(" + StructRef + " *__cself)";
3308 } else if (BD->param_empty()) {
3309 S += "(" + StructRef + " *__cself)";
3310 } else {
3311 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
3312 assert(FT && "SynthesizeBlockFunc: No function proto");
3313 S += '(';
3314 // first add the implicit argument.
3315 S += StructRef + " *__cself, ";
3316 std::string ParamStr;
3317 for (BlockDecl::param_iterator AI = BD->param_begin(),
3318 E = BD->param_end(); AI != E; ++AI) {
3319 if (AI != BD->param_begin()) S += ", ";
3320 ParamStr = (*AI)->getNameAsString();
3321 QualType QT = (*AI)->getType();
3322 if (convertBlockPointerToFunctionPointer(QT))
3323 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
3324 else
3325 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
3326 S += ParamStr;
3327 }
3328 if (FT->isVariadic()) {
3329 if (!BD->param_empty()) S += ", ";
3330 S += "...";
3331 }
3332 S += ')';
3333 }
3334 S += " {\n";
3335
3336 // Create local declarations to avoid rewriting all closure decl ref exprs.
3337 // First, emit a declaration for all "by ref" decls.
3338 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3339 E = BlockByRefDecls.end(); I != E; ++I) {
3340 S += " ";
3341 std::string Name = (*I)->getNameAsString();
3342 std::string TypeString;
3343 RewriteByRefString(TypeString, Name, (*I));
3344 TypeString += " *";
3345 Name = TypeString + Name;
3346 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
3347 }
3348 // Next, emit a declaration for all "by copy" declarations.
3349 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3350 E = BlockByCopyDecls.end(); I != E; ++I) {
3351 S += " ";
3352 // Handle nested closure invocation. For example:
3353 //
3354 // void (^myImportedClosure)(void);
3355 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3356 //
3357 // void (^anotherClosure)(void);
3358 // anotherClosure = ^(void) {
3359 // myImportedClosure(); // import and invoke the closure
3360 // };
3361 //
3362 if (isTopLevelBlockPointerType((*I)->getType())) {
3363 RewriteBlockPointerTypeVariable(S, (*I));
3364 S += " = (";
3365 RewriteBlockPointerType(S, (*I)->getType());
3366 S += ")";
3367 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3368 }
3369 else {
3370 std::string Name = (*I)->getNameAsString();
3371 QualType QT = (*I)->getType();
3372 if (HasLocalVariableExternalStorage(*I))
3373 QT = Context->getPointerType(QT);
3374 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
3375 S += Name + " = __cself->" +
3376 (*I)->getNameAsString() + "; // bound by copy\n";
3377 }
3378 }
3379 std::string RewrittenStr = RewrittenBlockExprs[CE];
3380 const char *cstr = RewrittenStr.c_str();
3381 while (*cstr++ != '{') ;
3382 S += cstr;
3383 S += "\n";
3384 return S;
3385}
3386
3387std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3388 StringRef funcName,
3389 std::string Tag) {
3390 std::string StructRef = "struct " + Tag;
3391 std::string S = "static void __";
3392
3393 S += funcName;
3394 S += "_block_copy_" + utostr(i);
3395 S += "(" + StructRef;
3396 S += "*dst, " + StructRef;
3397 S += "*src) {";
3398 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3399 E = ImportedBlockDecls.end(); I != E; ++I) {
3400 ValueDecl *VD = (*I);
3401 S += "_Block_object_assign((void*)&dst->";
3402 S += (*I)->getNameAsString();
3403 S += ", (void*)src->";
3404 S += (*I)->getNameAsString();
3405 if (BlockByRefDeclsPtrSet.count((*I)))
3406 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3407 else if (VD->getType()->isBlockPointerType())
3408 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3409 else
3410 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3411 }
3412 S += "}\n";
3413
3414 S += "\nstatic void __";
3415 S += funcName;
3416 S += "_block_dispose_" + utostr(i);
3417 S += "(" + StructRef;
3418 S += "*src) {";
3419 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3420 E = ImportedBlockDecls.end(); I != E; ++I) {
3421 ValueDecl *VD = (*I);
3422 S += "_Block_object_dispose((void*)src->";
3423 S += (*I)->getNameAsString();
3424 if (BlockByRefDeclsPtrSet.count((*I)))
3425 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3426 else if (VD->getType()->isBlockPointerType())
3427 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3428 else
3429 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3430 }
3431 S += "}\n";
3432 return S;
3433}
3434
3435std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3436 std::string Desc) {
3437 std::string S = "\nstruct " + Tag;
3438 std::string Constructor = " " + Tag;
3439
3440 S += " {\n struct __block_impl impl;\n";
3441 S += " struct " + Desc;
3442 S += "* Desc;\n";
3443
3444 Constructor += "(void *fp, "; // Invoke function pointer.
3445 Constructor += "struct " + Desc; // Descriptor pointer.
3446 Constructor += " *desc";
3447
3448 if (BlockDeclRefs.size()) {
3449 // Output all "by copy" declarations.
3450 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3451 E = BlockByCopyDecls.end(); I != E; ++I) {
3452 S += " ";
3453 std::string FieldName = (*I)->getNameAsString();
3454 std::string ArgName = "_" + FieldName;
3455 // Handle nested closure invocation. For example:
3456 //
3457 // void (^myImportedBlock)(void);
3458 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3459 //
3460 // void (^anotherBlock)(void);
3461 // anotherBlock = ^(void) {
3462 // myImportedBlock(); // import and invoke the closure
3463 // };
3464 //
3465 if (isTopLevelBlockPointerType((*I)->getType())) {
3466 S += "struct __block_impl *";
3467 Constructor += ", void *" + ArgName;
3468 } else {
3469 QualType QT = (*I)->getType();
3470 if (HasLocalVariableExternalStorage(*I))
3471 QT = Context->getPointerType(QT);
3472 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3473 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
3474 Constructor += ", " + ArgName;
3475 }
3476 S += FieldName + ";\n";
3477 }
3478 // Output all "by ref" declarations.
3479 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3480 E = BlockByRefDecls.end(); I != E; ++I) {
3481 S += " ";
3482 std::string FieldName = (*I)->getNameAsString();
3483 std::string ArgName = "_" + FieldName;
3484 {
3485 std::string TypeString;
3486 RewriteByRefString(TypeString, FieldName, (*I));
3487 TypeString += " *";
3488 FieldName = TypeString + FieldName;
3489 ArgName = TypeString + ArgName;
3490 Constructor += ", " + ArgName;
3491 }
3492 S += FieldName + "; // by ref\n";
3493 }
3494 // Finish writing the constructor.
3495 Constructor += ", int flags=0)";
3496 // Initialize all "by copy" arguments.
3497 bool firsTime = true;
3498 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3499 E = BlockByCopyDecls.end(); I != E; ++I) {
3500 std::string Name = (*I)->getNameAsString();
3501 if (firsTime) {
3502 Constructor += " : ";
3503 firsTime = false;
3504 }
3505 else
3506 Constructor += ", ";
3507 if (isTopLevelBlockPointerType((*I)->getType()))
3508 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3509 else
3510 Constructor += Name + "(_" + Name + ")";
3511 }
3512 // Initialize all "by ref" arguments.
3513 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3514 E = BlockByRefDecls.end(); I != E; ++I) {
3515 std::string Name = (*I)->getNameAsString();
3516 if (firsTime) {
3517 Constructor += " : ";
3518 firsTime = false;
3519 }
3520 else
3521 Constructor += ", ";
3522 Constructor += Name + "(_" + Name + "->__forwarding)";
3523 }
3524
3525 Constructor += " {\n";
3526 if (GlobalVarDecl)
3527 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3528 else
3529 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3530 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3531
3532 Constructor += " Desc = desc;\n";
3533 } else {
3534 // Finish writing the constructor.
3535 Constructor += ", int flags=0) {\n";
3536 if (GlobalVarDecl)
3537 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3538 else
3539 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3540 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3541 Constructor += " Desc = desc;\n";
3542 }
3543 Constructor += " ";
3544 Constructor += "}\n";
3545 S += Constructor;
3546 S += "};\n";
3547 return S;
3548}
3549
3550std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
3551 std::string ImplTag, int i,
3552 StringRef FunName,
3553 unsigned hasCopy) {
3554 std::string S = "\nstatic struct " + DescTag;
3555
3556 S += " {\n unsigned long reserved;\n";
3557 S += " unsigned long Block_size;\n";
3558 if (hasCopy) {
3559 S += " void (*copy)(struct ";
3560 S += ImplTag; S += "*, struct ";
3561 S += ImplTag; S += "*);\n";
3562
3563 S += " void (*dispose)(struct ";
3564 S += ImplTag; S += "*);\n";
3565 }
3566 S += "} ";
3567
3568 S += DescTag + "_DATA = { 0, sizeof(struct ";
3569 S += ImplTag + ")";
3570 if (hasCopy) {
3571 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3572 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
3573 }
3574 S += "};\n";
3575 return S;
3576}
3577
3578void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3579 StringRef FunName) {
3580 // Insert declaration for the function in which block literal is used.
3581 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
3582 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
3583 bool RewriteSC = (GlobalVarDecl &&
3584 !Blocks.empty() &&
3585 GlobalVarDecl->getStorageClass() == SC_Static &&
3586 GlobalVarDecl->getType().getCVRQualifiers());
3587 if (RewriteSC) {
3588 std::string SC(" void __");
3589 SC += GlobalVarDecl->getNameAsString();
3590 SC += "() {}";
3591 InsertText(FunLocStart, SC);
3592 }
3593
3594 // Insert closures that were part of the function.
3595 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3596 CollectBlockDeclRefInfo(Blocks[i]);
3597 // Need to copy-in the inner copied-in variables not actually used in this
3598 // block.
3599 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
3600 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
3601 ValueDecl *VD = Exp->getDecl();
3602 BlockDeclRefs.push_back(Exp);
3603 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
3604 BlockByCopyDeclsPtrSet.insert(VD);
3605 BlockByCopyDecls.push_back(VD);
3606 }
3607 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
3608 BlockByRefDeclsPtrSet.insert(VD);
3609 BlockByRefDecls.push_back(VD);
3610 }
3611 // imported objects in the inner blocks not used in the outer
3612 // blocks must be copied/disposed in the outer block as well.
3613 if (Exp->isByRef() ||
3614 VD->getType()->isObjCObjectPointerType() ||
3615 VD->getType()->isBlockPointerType())
3616 ImportedBlockDecls.insert(VD);
3617 }
3618
3619 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3620 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
3621
3622 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
3623
3624 InsertText(FunLocStart, CI);
3625
3626 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
3627
3628 InsertText(FunLocStart, CF);
3629
3630 if (ImportedBlockDecls.size()) {
3631 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
3632 InsertText(FunLocStart, HF);
3633 }
3634 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3635 ImportedBlockDecls.size() > 0);
3636 InsertText(FunLocStart, BD);
3637
3638 BlockDeclRefs.clear();
3639 BlockByRefDecls.clear();
3640 BlockByRefDeclsPtrSet.clear();
3641 BlockByCopyDecls.clear();
3642 BlockByCopyDeclsPtrSet.clear();
3643 ImportedBlockDecls.clear();
3644 }
3645 if (RewriteSC) {
3646 // Must insert any 'const/volatile/static here. Since it has been
3647 // removed as result of rewriting of block literals.
3648 std::string SC;
3649 if (GlobalVarDecl->getStorageClass() == SC_Static)
3650 SC = "static ";
3651 if (GlobalVarDecl->getType().isConstQualified())
3652 SC += "const ";
3653 if (GlobalVarDecl->getType().isVolatileQualified())
3654 SC += "volatile ";
3655 if (GlobalVarDecl->getType().isRestrictQualified())
3656 SC += "restrict ";
3657 InsertText(FunLocStart, SC);
3658 }
3659
3660 Blocks.clear();
3661 InnerDeclRefsCount.clear();
3662 InnerDeclRefs.clear();
3663 RewrittenBlockExprs.clear();
3664}
3665
3666void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3667 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
3668 StringRef FuncName = FD->getName();
3669
3670 SynthesizeBlockLiterals(FunLocStart, FuncName);
3671}
3672
3673static void BuildUniqueMethodName(std::string &Name,
3674 ObjCMethodDecl *MD) {
3675 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3676 Name = IFace->getName();
3677 Name += "__" + MD->getSelector().getAsString();
3678 // Convert colons to underscores.
3679 std::string::size_type loc = 0;
3680 while ((loc = Name.find(":", loc)) != std::string::npos)
3681 Name.replace(loc, 1, "_");
3682}
3683
3684void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
3685 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3686 //SourceLocation FunLocStart = MD->getLocStart();
3687 SourceLocation FunLocStart = MD->getLocStart();
3688 std::string FuncName;
3689 BuildUniqueMethodName(FuncName, MD);
3690 SynthesizeBlockLiterals(FunLocStart, FuncName);
3691}
3692
3693void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
3694 for (Stmt::child_range CI = S->children(); CI; ++CI)
3695 if (*CI) {
3696 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3697 GetBlockDeclRefExprs(CBE->getBody());
3698 else
3699 GetBlockDeclRefExprs(*CI);
3700 }
3701 // Handle specific things.
3702 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
3703 // FIXME: Handle enums.
3704 if (!isa<FunctionDecl>(CDRE->getDecl()))
3705 BlockDeclRefs.push_back(CDRE);
3706 }
3707 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
3708 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
3709 BlockDeclRefExpr *BDRE =
3710 new (Context)BlockDeclRefExpr(cast<VarDecl>(DRE->getDecl()),
3711 DRE->getType(),
3712 VK_LValue, DRE->getLocation(), false);
3713 BlockDeclRefs.push_back(BDRE);
3714 }
3715
3716 return;
3717}
3718
3719void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
3720 SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
3721 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
3722 for (Stmt::child_range CI = S->children(); CI; ++CI)
3723 if (*CI) {
3724 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
3725 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
3726 GetInnerBlockDeclRefExprs(CBE->getBody(),
3727 InnerBlockDeclRefs,
3728 InnerContexts);
3729 }
3730 else
3731 GetInnerBlockDeclRefExprs(*CI,
3732 InnerBlockDeclRefs,
3733 InnerContexts);
3734
3735 }
3736 // Handle specific things.
3737 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
3738 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
3739 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
3740 InnerBlockDeclRefs.push_back(CDRE);
3741 }
3742 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3743 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
3744 if (Var->isFunctionOrMethodVarDecl())
3745 ImportedLocalExternalDecls.insert(Var);
3746 }
3747
3748 return;
3749}
3750
3751/// convertFunctionTypeOfBlocks - This routine converts a function type
3752/// whose result type may be a block pointer or whose argument type(s)
3753/// might be block pointers to an equivalent function type replacing
3754/// all block pointers to function pointers.
3755QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3756 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3757 // FTP will be null for closures that don't take arguments.
3758 // Generate a funky cast.
3759 SmallVector<QualType, 8> ArgTypes;
3760 QualType Res = FT->getResultType();
3761 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
3762
3763 if (FTP) {
3764 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3765 E = FTP->arg_type_end(); I && (I != E); ++I) {
3766 QualType t = *I;
3767 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3768 if (convertBlockPointerToFunctionPointer(t))
3769 HasBlockType = true;
3770 ArgTypes.push_back(t);
3771 }
3772 }
3773 QualType FuncType;
3774 // FIXME. Does this work if block takes no argument but has a return type
3775 // which is of block type?
3776 if (HasBlockType)
3777 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
3778 else FuncType = QualType(FT, 0);
3779 return FuncType;
3780}
3781
3782Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
3783 // Navigate to relevant type information.
3784 const BlockPointerType *CPT = 0;
3785
3786 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
3787 CPT = DRE->getType()->getAs<BlockPointerType>();
3788 } else if (const BlockDeclRefExpr *CDRE =
3789 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
3790 CPT = CDRE->getType()->getAs<BlockPointerType>();
3791 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
3792 CPT = MExpr->getType()->getAs<BlockPointerType>();
3793 }
3794 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3795 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3796 }
3797 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3798 CPT = IEXPR->getType()->getAs<BlockPointerType>();
3799 else if (const ConditionalOperator *CEXPR =
3800 dyn_cast<ConditionalOperator>(BlockExp)) {
3801 Expr *LHSExp = CEXPR->getLHS();
3802 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3803 Expr *RHSExp = CEXPR->getRHS();
3804 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3805 Expr *CONDExp = CEXPR->getCond();
3806 ConditionalOperator *CondExpr =
3807 new (Context) ConditionalOperator(CONDExp,
3808 SourceLocation(), cast<Expr>(LHSStmt),
3809 SourceLocation(), cast<Expr>(RHSStmt),
3810 Exp->getType(), VK_RValue, OK_Ordinary);
3811 return CondExpr;
3812 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3813 CPT = IRE->getType()->getAs<BlockPointerType>();
3814 } else if (const PseudoObjectExpr *POE
3815 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3816 CPT = POE->getType()->castAs<BlockPointerType>();
3817 } else {
3818 assert(1 && "RewriteBlockClass: Bad type");
3819 }
3820 assert(CPT && "RewriteBlockClass: Bad type");
3821 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
3822 assert(FT && "RewriteBlockClass: Bad type");
3823 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3824 // FTP will be null for closures that don't take arguments.
3825
3826 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3827 SourceLocation(), SourceLocation(),
3828 &Context->Idents.get("__block_impl"));
3829 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
3830
3831 // Generate a funky cast.
3832 SmallVector<QualType, 8> ArgTypes;
3833
3834 // Push the block argument type.
3835 ArgTypes.push_back(PtrBlock);
3836 if (FTP) {
3837 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3838 E = FTP->arg_type_end(); I && (I != E); ++I) {
3839 QualType t = *I;
3840 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3841 if (!convertBlockPointerToFunctionPointer(t))
3842 convertToUnqualifiedObjCType(t);
3843 ArgTypes.push_back(t);
3844 }
3845 }
3846 // Now do the pointer to function cast.
3847 QualType PtrToFuncCastType
3848 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
3849
3850 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
3851
3852 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
3853 CK_BitCast,
3854 const_cast<Expr*>(BlockExp));
3855 // Don't forget the parens to enforce the proper binding.
3856 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3857 BlkCast);
3858 //PE->dump();
3859
3860 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3861 SourceLocation(),
3862 &Context->Idents.get("FuncPtr"),
3863 Context->VoidPtrTy, 0,
3864 /*BitWidth=*/0, /*Mutable=*/true,
3865 /*HasInit=*/false);
3866 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
3867 FD->getType(), VK_LValue,
3868 OK_Ordinary);
3869
3870
3871 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
3872 CK_BitCast, ME);
3873 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3874
3875 SmallVector<Expr*, 8> BlkExprs;
3876 // Add the implicit argument.
3877 BlkExprs.push_back(BlkCast);
3878 // Add the user arguments.
3879 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3880 E = Exp->arg_end(); I != E; ++I) {
3881 BlkExprs.push_back(*I);
3882 }
3883 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
3884 BlkExprs.size(),
3885 Exp->getType(), VK_RValue,
3886 SourceLocation());
3887 return CE;
3888}
3889
3890// We need to return the rewritten expression to handle cases where the
3891// BlockDeclRefExpr is embedded in another expression being rewritten.
3892// For example:
3893//
3894// int main() {
3895// __block Foo *f;
3896// __block int i;
3897//
3898// void (^myblock)() = ^() {
3899// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
3900// i = 77;
3901// };
3902//}
3903Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
3904 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
3905 // for each DeclRefExp where BYREFVAR is name of the variable.
3906 ValueDecl *VD;
3907 bool isArrow = true;
3908 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
3909 VD = BDRE->getDecl();
3910 else {
3911 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
3912 isArrow = false;
3913 }
3914
3915 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3916 SourceLocation(),
3917 &Context->Idents.get("__forwarding"),
3918 Context->VoidPtrTy, 0,
3919 /*BitWidth=*/0, /*Mutable=*/true,
3920 /*HasInit=*/false);
3921 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
3922 FD, SourceLocation(),
3923 FD->getType(), VK_LValue,
3924 OK_Ordinary);
3925
3926 StringRef Name = VD->getName();
3927 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
3928 &Context->Idents.get(Name),
3929 Context->VoidPtrTy, 0,
3930 /*BitWidth=*/0, /*Mutable=*/true,
3931 /*HasInit=*/false);
3932 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
3933 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
3934
3935
3936
3937 // Need parens to enforce precedence.
3938 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
3939 DeclRefExp->getExprLoc(),
3940 ME);
3941 ReplaceStmt(DeclRefExp, PE);
3942 return PE;
3943}
3944
3945// Rewrites the imported local variable V with external storage
3946// (static, extern, etc.) as *V
3947//
3948Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
3949 ValueDecl *VD = DRE->getDecl();
3950 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3951 if (!ImportedLocalExternalDecls.count(Var))
3952 return DRE;
3953 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
3954 VK_LValue, OK_Ordinary,
3955 DRE->getLocation());
3956 // Need parens to enforce precedence.
3957 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3958 Exp);
3959 ReplaceStmt(DRE, PE);
3960 return PE;
3961}
3962
3963void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3964 SourceLocation LocStart = CE->getLParenLoc();
3965 SourceLocation LocEnd = CE->getRParenLoc();
3966
3967 // Need to avoid trying to rewrite synthesized casts.
3968 if (LocStart.isInvalid())
3969 return;
3970 // Need to avoid trying to rewrite casts contained in macros.
3971 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3972 return;
3973
3974 const char *startBuf = SM->getCharacterData(LocStart);
3975 const char *endBuf = SM->getCharacterData(LocEnd);
3976 QualType QT = CE->getType();
3977 const Type* TypePtr = QT->getAs<Type>();
3978 if (isa<TypeOfExprType>(TypePtr)) {
3979 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
3980 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
3981 std::string TypeAsString = "(";
3982 RewriteBlockPointerType(TypeAsString, QT);
3983 TypeAsString += ")";
3984 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
3985 return;
3986 }
3987 // advance the location to startArgList.
3988 const char *argPtr = startBuf;
3989
3990 while (*argPtr++ && (argPtr < endBuf)) {
3991 switch (*argPtr) {
3992 case '^':
3993 // Replace the '^' with '*'.
3994 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
3995 ReplaceText(LocStart, 1, "*");
3996 break;
3997 }
3998 }
3999 return;
4000}
4001
4002void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4003 SourceLocation DeclLoc = FD->getLocation();
4004 unsigned parenCount = 0;
4005
4006 // We have 1 or more arguments that have closure pointers.
4007 const char *startBuf = SM->getCharacterData(DeclLoc);
4008 const char *startArgList = strchr(startBuf, '(');
4009
4010 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4011
4012 parenCount++;
4013 // advance the location to startArgList.
4014 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4015 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4016
4017 const char *argPtr = startArgList;
4018
4019 while (*argPtr++ && parenCount) {
4020 switch (*argPtr) {
4021 case '^':
4022 // Replace the '^' with '*'.
4023 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4024 ReplaceText(DeclLoc, 1, "*");
4025 break;
4026 case '(':
4027 parenCount++;
4028 break;
4029 case ')':
4030 parenCount--;
4031 break;
4032 }
4033 }
4034 return;
4035}
4036
4037bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4038 const FunctionProtoType *FTP;
4039 const PointerType *PT = QT->getAs<PointerType>();
4040 if (PT) {
4041 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4042 } else {
4043 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4044 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4045 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4046 }
4047 if (FTP) {
4048 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4049 E = FTP->arg_type_end(); I != E; ++I)
4050 if (isTopLevelBlockPointerType(*I))
4051 return true;
4052 }
4053 return false;
4054}
4055
4056bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4057 const FunctionProtoType *FTP;
4058 const PointerType *PT = QT->getAs<PointerType>();
4059 if (PT) {
4060 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4061 } else {
4062 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4063 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4064 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4065 }
4066 if (FTP) {
4067 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4068 E = FTP->arg_type_end(); I != E; ++I) {
4069 if ((*I)->isObjCQualifiedIdType())
4070 return true;
4071 if ((*I)->isObjCObjectPointerType() &&
4072 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4073 return true;
4074 }
4075
4076 }
4077 return false;
4078}
4079
4080void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4081 const char *&RParen) {
4082 const char *argPtr = strchr(Name, '(');
4083 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4084
4085 LParen = argPtr; // output the start.
4086 argPtr++; // skip past the left paren.
4087 unsigned parenCount = 1;
4088
4089 while (*argPtr && parenCount) {
4090 switch (*argPtr) {
4091 case '(': parenCount++; break;
4092 case ')': parenCount--; break;
4093 default: break;
4094 }
4095 if (parenCount) argPtr++;
4096 }
4097 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4098 RParen = argPtr; // output the end
4099}
4100
4101void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4102 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4103 RewriteBlockPointerFunctionArgs(FD);
4104 return;
4105 }
4106 // Handle Variables and Typedefs.
4107 SourceLocation DeclLoc = ND->getLocation();
4108 QualType DeclT;
4109 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4110 DeclT = VD->getType();
4111 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4112 DeclT = TDD->getUnderlyingType();
4113 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4114 DeclT = FD->getType();
4115 else
4116 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4117
4118 const char *startBuf = SM->getCharacterData(DeclLoc);
4119 const char *endBuf = startBuf;
4120 // scan backward (from the decl location) for the end of the previous decl.
4121 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4122 startBuf--;
4123 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4124 std::string buf;
4125 unsigned OrigLength=0;
4126 // *startBuf != '^' if we are dealing with a pointer to function that
4127 // may take block argument types (which will be handled below).
4128 if (*startBuf == '^') {
4129 // Replace the '^' with '*', computing a negative offset.
4130 buf = '*';
4131 startBuf++;
4132 OrigLength++;
4133 }
4134 while (*startBuf != ')') {
4135 buf += *startBuf;
4136 startBuf++;
4137 OrigLength++;
4138 }
4139 buf += ')';
4140 OrigLength++;
4141
4142 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4143 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4144 // Replace the '^' with '*' for arguments.
4145 // Replace id<P> with id/*<>*/
4146 DeclLoc = ND->getLocation();
4147 startBuf = SM->getCharacterData(DeclLoc);
4148 const char *argListBegin, *argListEnd;
4149 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4150 while (argListBegin < argListEnd) {
4151 if (*argListBegin == '^')
4152 buf += '*';
4153 else if (*argListBegin == '<') {
4154 buf += "/*";
4155 buf += *argListBegin++;
4156 OrigLength++;;
4157 while (*argListBegin != '>') {
4158 buf += *argListBegin++;
4159 OrigLength++;
4160 }
4161 buf += *argListBegin;
4162 buf += "*/";
4163 }
4164 else
4165 buf += *argListBegin;
4166 argListBegin++;
4167 OrigLength++;
4168 }
4169 buf += ')';
4170 OrigLength++;
4171 }
4172 ReplaceText(Start, OrigLength, buf);
4173
4174 return;
4175}
4176
4177
4178/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4179/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4180/// struct Block_byref_id_object *src) {
4181/// _Block_object_assign (&_dest->object, _src->object,
4182/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4183/// [|BLOCK_FIELD_IS_WEAK]) // object
4184/// _Block_object_assign(&_dest->object, _src->object,
4185/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4186/// [|BLOCK_FIELD_IS_WEAK]) // block
4187/// }
4188/// And:
4189/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4190/// _Block_object_dispose(_src->object,
4191/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4192/// [|BLOCK_FIELD_IS_WEAK]) // object
4193/// _Block_object_dispose(_src->object,
4194/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4195/// [|BLOCK_FIELD_IS_WEAK]) // block
4196/// }
4197
4198std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4199 int flag) {
4200 std::string S;
4201 if (CopyDestroyCache.count(flag))
4202 return S;
4203 CopyDestroyCache.insert(flag);
4204 S = "static void __Block_byref_id_object_copy_";
4205 S += utostr(flag);
4206 S += "(void *dst, void *src) {\n";
4207
4208 // offset into the object pointer is computed as:
4209 // void * + void* + int + int + void* + void *
4210 unsigned IntSize =
4211 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4212 unsigned VoidPtrSize =
4213 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4214
4215 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4216 S += " _Block_object_assign((char*)dst + ";
4217 S += utostr(offset);
4218 S += ", *(void * *) ((char*)src + ";
4219 S += utostr(offset);
4220 S += "), ";
4221 S += utostr(flag);
4222 S += ");\n}\n";
4223
4224 S += "static void __Block_byref_id_object_dispose_";
4225 S += utostr(flag);
4226 S += "(void *src) {\n";
4227 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4228 S += utostr(offset);
4229 S += "), ";
4230 S += utostr(flag);
4231 S += ");\n}\n";
4232 return S;
4233}
4234
4235/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4236/// the declaration into:
4237/// struct __Block_byref_ND {
4238/// void *__isa; // NULL for everything except __weak pointers
4239/// struct __Block_byref_ND *__forwarding;
4240/// int32_t __flags;
4241/// int32_t __size;
4242/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4243/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4244/// typex ND;
4245/// };
4246///
4247/// It then replaces declaration of ND variable with:
4248/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4249/// __size=sizeof(struct __Block_byref_ND),
4250/// ND=initializer-if-any};
4251///
4252///
4253void RewriteModernObjC::RewriteByRefVar(VarDecl *ND) {
4254 // Insert declaration for the function in which block literal is
4255 // used.
4256 if (CurFunctionDeclToDeclareForBlock)
4257 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
4258 int flag = 0;
4259 int isa = 0;
4260 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4261 if (DeclLoc.isInvalid())
4262 // If type location is missing, it is because of missing type (a warning).
4263 // Use variable's location which is good for this case.
4264 DeclLoc = ND->getLocation();
4265 const char *startBuf = SM->getCharacterData(DeclLoc);
4266 SourceLocation X = ND->getLocEnd();
4267 X = SM->getExpansionLoc(X);
4268 const char *endBuf = SM->getCharacterData(X);
4269 std::string Name(ND->getNameAsString());
4270 std::string ByrefType;
4271 RewriteByRefString(ByrefType, Name, ND, true);
4272 ByrefType += " {\n";
4273 ByrefType += " void *__isa;\n";
4274 RewriteByRefString(ByrefType, Name, ND);
4275 ByrefType += " *__forwarding;\n";
4276 ByrefType += " int __flags;\n";
4277 ByrefType += " int __size;\n";
4278 // Add void *__Block_byref_id_object_copy;
4279 // void *__Block_byref_id_object_dispose; if needed.
4280 QualType Ty = ND->getType();
4281 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4282 if (HasCopyAndDispose) {
4283 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4284 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4285 }
4286
4287 QualType T = Ty;
4288 (void)convertBlockPointerToFunctionPointer(T);
4289 T.getAsStringInternal(Name, Context->getPrintingPolicy());
4290
4291 ByrefType += " " + Name + ";\n";
4292 ByrefType += "};\n";
4293 // Insert this type in global scope. It is needed by helper function.
4294 SourceLocation FunLocStart;
4295 if (CurFunctionDef)
4296 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4297 else {
4298 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4299 FunLocStart = CurMethodDef->getLocStart();
4300 }
4301 InsertText(FunLocStart, ByrefType);
4302 if (Ty.isObjCGCWeak()) {
4303 flag |= BLOCK_FIELD_IS_WEAK;
4304 isa = 1;
4305 }
4306
4307 if (HasCopyAndDispose) {
4308 flag = BLOCK_BYREF_CALLER;
4309 QualType Ty = ND->getType();
4310 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4311 if (Ty->isBlockPointerType())
4312 flag |= BLOCK_FIELD_IS_BLOCK;
4313 else
4314 flag |= BLOCK_FIELD_IS_OBJECT;
4315 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
4316 if (!HF.empty())
4317 InsertText(FunLocStart, HF);
4318 }
4319
4320 // struct __Block_byref_ND ND =
4321 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4322 // initializer-if-any};
4323 bool hasInit = (ND->getInit() != 0);
4324 unsigned flags = 0;
4325 if (HasCopyAndDispose)
4326 flags |= BLOCK_HAS_COPY_DISPOSE;
4327 Name = ND->getNameAsString();
4328 ByrefType.clear();
4329 RewriteByRefString(ByrefType, Name, ND);
4330 std::string ForwardingCastType("(");
4331 ForwardingCastType += ByrefType + " *)";
4332 if (!hasInit) {
4333 ByrefType += " " + Name + " = {(void*)";
4334 ByrefType += utostr(isa);
4335 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4336 ByrefType += utostr(flags);
4337 ByrefType += ", ";
4338 ByrefType += "sizeof(";
4339 RewriteByRefString(ByrefType, Name, ND);
4340 ByrefType += ")";
4341 if (HasCopyAndDispose) {
4342 ByrefType += ", __Block_byref_id_object_copy_";
4343 ByrefType += utostr(flag);
4344 ByrefType += ", __Block_byref_id_object_dispose_";
4345 ByrefType += utostr(flag);
4346 }
4347 ByrefType += "};\n";
4348 unsigned nameSize = Name.size();
4349 // for block or function pointer declaration. Name is aleady
4350 // part of the declaration.
4351 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4352 nameSize = 1;
4353 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
4354 }
4355 else {
4356 SourceLocation startLoc;
4357 Expr *E = ND->getInit();
4358 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4359 startLoc = ECE->getLParenLoc();
4360 else
4361 startLoc = E->getLocStart();
4362 startLoc = SM->getExpansionLoc(startLoc);
4363 endBuf = SM->getCharacterData(startLoc);
4364 ByrefType += " " + Name;
4365 ByrefType += " = {(void*)";
4366 ByrefType += utostr(isa);
4367 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4368 ByrefType += utostr(flags);
4369 ByrefType += ", ";
4370 ByrefType += "sizeof(";
4371 RewriteByRefString(ByrefType, Name, ND);
4372 ByrefType += "), ";
4373 if (HasCopyAndDispose) {
4374 ByrefType += "__Block_byref_id_object_copy_";
4375 ByrefType += utostr(flag);
4376 ByrefType += ", __Block_byref_id_object_dispose_";
4377 ByrefType += utostr(flag);
4378 ByrefType += ", ";
4379 }
4380 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
4381
4382 // Complete the newly synthesized compound expression by inserting a right
4383 // curly brace before the end of the declaration.
4384 // FIXME: This approach avoids rewriting the initializer expression. It
4385 // also assumes there is only one declarator. For example, the following
4386 // isn't currently supported by this routine (in general):
4387 //
4388 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4389 //
4390 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4391 const char *semiBuf = strchr(startInitializerBuf, ';');
4392 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4393 SourceLocation semiLoc =
4394 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
4395
4396 InsertText(semiLoc, "}");
4397 }
4398 return;
4399}
4400
4401void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4402 // Add initializers for any closure decl refs.
4403 GetBlockDeclRefExprs(Exp->getBody());
4404 if (BlockDeclRefs.size()) {
4405 // Unique all "by copy" declarations.
4406 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4407 if (!BlockDeclRefs[i]->isByRef()) {
4408 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4409 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4410 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4411 }
4412 }
4413 // Unique all "by ref" declarations.
4414 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4415 if (BlockDeclRefs[i]->isByRef()) {
4416 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4417 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4418 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4419 }
4420 }
4421 // Find any imported blocks...they will need special attention.
4422 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4423 if (BlockDeclRefs[i]->isByRef() ||
4424 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4425 BlockDeclRefs[i]->getType()->isBlockPointerType())
4426 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4427 }
4428}
4429
4430FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
4431 IdentifierInfo *ID = &Context->Idents.get(name);
4432 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
4433 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4434 SourceLocation(), ID, FType, 0, SC_Extern,
4435 SC_None, false, false);
4436}
4437
4438Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
4439 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
4440 const BlockDecl *block = Exp->getBlockDecl();
4441 Blocks.push_back(Exp);
4442
4443 CollectBlockDeclRefInfo(Exp);
4444
4445 // Add inner imported variables now used in current block.
4446 int countOfInnerDecls = 0;
4447 if (!InnerBlockDeclRefs.empty()) {
4448 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
4449 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
4450 ValueDecl *VD = Exp->getDecl();
4451 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4452 // We need to save the copied-in variables in nested
4453 // blocks because it is needed at the end for some of the API generations.
4454 // See SynthesizeBlockLiterals routine.
4455 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4456 BlockDeclRefs.push_back(Exp);
4457 BlockByCopyDeclsPtrSet.insert(VD);
4458 BlockByCopyDecls.push_back(VD);
4459 }
4460 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4461 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4462 BlockDeclRefs.push_back(Exp);
4463 BlockByRefDeclsPtrSet.insert(VD);
4464 BlockByRefDecls.push_back(VD);
4465 }
4466 }
4467 // Find any imported blocks...they will need special attention.
4468 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
4469 if (InnerBlockDeclRefs[i]->isByRef() ||
4470 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4471 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4472 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
4473 }
4474 InnerDeclRefsCount.push_back(countOfInnerDecls);
4475
4476 std::string FuncName;
4477
4478 if (CurFunctionDef)
4479 FuncName = CurFunctionDef->getNameAsString();
4480 else if (CurMethodDef)
4481 BuildUniqueMethodName(FuncName, CurMethodDef);
4482 else if (GlobalVarDecl)
4483 FuncName = std::string(GlobalVarDecl->getNameAsString());
4484
4485 std::string BlockNumber = utostr(Blocks.size()-1);
4486
4487 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4488 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4489
4490 // Get a pointer to the function type so we can cast appropriately.
4491 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4492 QualType FType = Context->getPointerType(BFT);
4493
4494 FunctionDecl *FD;
4495 Expr *NewRep;
4496
4497 // Simulate a contructor call...
4498 FD = SynthBlockInitFunctionDecl(Tag);
4499 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, VK_RValue,
4500 SourceLocation());
4501
4502 SmallVector<Expr*, 4> InitExprs;
4503
4504 // Initialize the block function.
4505 FD = SynthBlockInitFunctionDecl(Func);
4506 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4507 SourceLocation());
4508 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4509 CK_BitCast, Arg);
4510 InitExprs.push_back(castExpr);
4511
4512 // Initialize the block descriptor.
4513 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
4514
4515 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
4516 SourceLocation(), SourceLocation(),
4517 &Context->Idents.get(DescData.c_str()),
4518 Context->VoidPtrTy, 0,
4519 SC_Static, SC_None);
4520 UnaryOperator *DescRefExpr =
4521 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD,
4522 Context->VoidPtrTy,
4523 VK_LValue,
4524 SourceLocation()),
4525 UO_AddrOf,
4526 Context->getPointerType(Context->VoidPtrTy),
4527 VK_RValue, OK_Ordinary,
4528 SourceLocation());
4529 InitExprs.push_back(DescRefExpr);
4530
4531 // Add initializers for any closure decl refs.
4532 if (BlockDeclRefs.size()) {
4533 Expr *Exp;
4534 // Output all "by copy" declarations.
4535 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4536 E = BlockByCopyDecls.end(); I != E; ++I) {
4537 if (isObjCType((*I)->getType())) {
4538 // FIXME: Conform to ABI ([[obj retain] autorelease]).
4539 FD = SynthBlockInitFunctionDecl((*I)->getName());
4540 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4541 SourceLocation());
4542 if (HasLocalVariableExternalStorage(*I)) {
4543 QualType QT = (*I)->getType();
4544 QT = Context->getPointerType(QT);
4545 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4546 OK_Ordinary, SourceLocation());
4547 }
4548 } else if (isTopLevelBlockPointerType((*I)->getType())) {
4549 FD = SynthBlockInitFunctionDecl((*I)->getName());
4550 Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4551 SourceLocation());
4552 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4553 CK_BitCast, Arg);
4554 } else {
4555 FD = SynthBlockInitFunctionDecl((*I)->getName());
4556 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4557 SourceLocation());
4558 if (HasLocalVariableExternalStorage(*I)) {
4559 QualType QT = (*I)->getType();
4560 QT = Context->getPointerType(QT);
4561 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4562 OK_Ordinary, SourceLocation());
4563 }
4564
4565 }
4566 InitExprs.push_back(Exp);
4567 }
4568 // Output all "by ref" declarations.
4569 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4570 E = BlockByRefDecls.end(); I != E; ++I) {
4571 ValueDecl *ND = (*I);
4572 std::string Name(ND->getNameAsString());
4573 std::string RecName;
4574 RewriteByRefString(RecName, Name, ND, true);
4575 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4576 + sizeof("struct"));
4577 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4578 SourceLocation(), SourceLocation(),
4579 II);
4580 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4581 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4582
4583 FD = SynthBlockInitFunctionDecl((*I)->getName());
4584 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4585 SourceLocation());
4586 bool isNestedCapturedVar = false;
4587 if (block)
4588 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
4589 ce = block->capture_end(); ci != ce; ++ci) {
4590 const VarDecl *variable = ci->getVariable();
4591 if (variable == ND && ci->isNested()) {
4592 assert (ci->isByRef() &&
4593 "SynthBlockInitExpr - captured block variable is not byref");
4594 isNestedCapturedVar = true;
4595 break;
4596 }
4597 }
4598 // captured nested byref variable has its address passed. Do not take
4599 // its address again.
4600 if (!isNestedCapturedVar)
4601 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
4602 Context->getPointerType(Exp->getType()),
4603 VK_RValue, OK_Ordinary, SourceLocation());
4604 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
4605 InitExprs.push_back(Exp);
4606 }
4607 }
4608 if (ImportedBlockDecls.size()) {
4609 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4610 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
4611 unsigned IntSize =
4612 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4613 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4614 Context->IntTy, SourceLocation());
4615 InitExprs.push_back(FlagExp);
4616 }
4617 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4618 FType, VK_LValue, SourceLocation());
4619 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
4620 Context->getPointerType(NewRep->getType()),
4621 VK_RValue, OK_Ordinary, SourceLocation());
4622 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
4623 NewRep);
4624 BlockDeclRefs.clear();
4625 BlockByRefDecls.clear();
4626 BlockByRefDeclsPtrSet.clear();
4627 BlockByCopyDecls.clear();
4628 BlockByCopyDeclsPtrSet.clear();
4629 ImportedBlockDecls.clear();
4630 return NewRep;
4631}
4632
4633bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4634 if (const ObjCForCollectionStmt * CS =
4635 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4636 return CS->getElement() == DS;
4637 return false;
4638}
4639
4640//===----------------------------------------------------------------------===//
4641// Function Body / Expression rewriting
4642//===----------------------------------------------------------------------===//
4643
4644Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4645 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4646 isa<DoStmt>(S) || isa<ForStmt>(S))
4647 Stmts.push_back(S);
4648 else if (isa<ObjCForCollectionStmt>(S)) {
4649 Stmts.push_back(S);
4650 ObjCBcLabelNo.push_back(++BcLabelCount);
4651 }
4652
4653 // Pseudo-object operations and ivar references need special
4654 // treatment because we're going to recursively rewrite them.
4655 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4656 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4657 return RewritePropertyOrImplicitSetter(PseudoOp);
4658 } else {
4659 return RewritePropertyOrImplicitGetter(PseudoOp);
4660 }
4661 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4662 return RewriteObjCIvarRefExpr(IvarRefExpr);
4663 }
4664
4665 SourceRange OrigStmtRange = S->getSourceRange();
4666
4667 // Perform a bottom up rewrite of all children.
4668 for (Stmt::child_range CI = S->children(); CI; ++CI)
4669 if (*CI) {
4670 Stmt *childStmt = (*CI);
4671 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
4672 if (newStmt) {
4673 *CI = newStmt;
4674 }
4675 }
4676
4677 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4678 SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
4679 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4680 InnerContexts.insert(BE->getBlockDecl());
4681 ImportedLocalExternalDecls.clear();
4682 GetInnerBlockDeclRefExprs(BE->getBody(),
4683 InnerBlockDeclRefs, InnerContexts);
4684 // Rewrite the block body in place.
4685 Stmt *SaveCurrentBody = CurrentBody;
4686 CurrentBody = BE->getBody();
4687 PropParentMap = 0;
4688 // block literal on rhs of a property-dot-sytax assignment
4689 // must be replaced by its synthesize ast so getRewrittenText
4690 // works as expected. In this case, what actually ends up on RHS
4691 // is the blockTranscribed which is the helper function for the
4692 // block literal; as in: self.c = ^() {[ace ARR];};
4693 bool saveDisableReplaceStmt = DisableReplaceStmt;
4694 DisableReplaceStmt = false;
4695 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4696 DisableReplaceStmt = saveDisableReplaceStmt;
4697 CurrentBody = SaveCurrentBody;
4698 PropParentMap = 0;
4699 ImportedLocalExternalDecls.clear();
4700 // Now we snarf the rewritten text and stash it away for later use.
4701 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
4702 RewrittenBlockExprs[BE] = Str;
4703
4704 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4705
4706 //blockTranscribed->dump();
4707 ReplaceStmt(S, blockTranscribed);
4708 return blockTranscribed;
4709 }
4710 // Handle specific things.
4711 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4712 return RewriteAtEncode(AtEncode);
4713
4714 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4715 return RewriteAtSelector(AtSelector);
4716
4717 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4718 return RewriteObjCStringLiteral(AtString);
4719
4720 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
4721#if 0
4722 // Before we rewrite it, put the original message expression in a comment.
4723 SourceLocation startLoc = MessExpr->getLocStart();
4724 SourceLocation endLoc = MessExpr->getLocEnd();
4725
4726 const char *startBuf = SM->getCharacterData(startLoc);
4727 const char *endBuf = SM->getCharacterData(endLoc);
4728
4729 std::string messString;
4730 messString += "// ";
4731 messString.append(startBuf, endBuf-startBuf+1);
4732 messString += "\n";
4733
4734 // FIXME: Missing definition of
4735 // InsertText(clang::SourceLocation, char const*, unsigned int).
4736 // InsertText(startLoc, messString.c_str(), messString.size());
4737 // Tried this, but it didn't work either...
4738 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
4739#endif
4740 return RewriteMessageExpr(MessExpr);
4741 }
4742
4743 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4744 return RewriteObjCTryStmt(StmtTry);
4745
4746 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4747 return RewriteObjCSynchronizedStmt(StmtTry);
4748
4749 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4750 return RewriteObjCThrowStmt(StmtThrow);
4751
4752 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4753 return RewriteObjCProtocolExpr(ProtocolExp);
4754
4755 if (ObjCForCollectionStmt *StmtForCollection =
4756 dyn_cast<ObjCForCollectionStmt>(S))
4757 return RewriteObjCForCollectionStmt(StmtForCollection,
4758 OrigStmtRange.getEnd());
4759 if (BreakStmt *StmtBreakStmt =
4760 dyn_cast<BreakStmt>(S))
4761 return RewriteBreakStmt(StmtBreakStmt);
4762 if (ContinueStmt *StmtContinueStmt =
4763 dyn_cast<ContinueStmt>(S))
4764 return RewriteContinueStmt(StmtContinueStmt);
4765
4766 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4767 // and cast exprs.
4768 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4769 // FIXME: What we're doing here is modifying the type-specifier that
4770 // precedes the first Decl. In the future the DeclGroup should have
4771 // a separate type-specifier that we can rewrite.
4772 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4773 // the context of an ObjCForCollectionStmt. For example:
4774 // NSArray *someArray;
4775 // for (id <FooProtocol> index in someArray) ;
4776 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4777 // and it depends on the original text locations/positions.
4778 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
4779 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4780
4781 // Blocks rewrite rules.
4782 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4783 DI != DE; ++DI) {
4784 Decl *SD = *DI;
4785 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
4786 if (isTopLevelBlockPointerType(ND->getType()))
4787 RewriteBlockPointerDecl(ND);
4788 else if (ND->getType()->isFunctionPointerType())
4789 CheckFunctionPointerDecl(ND->getType(), ND);
4790 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
4791 if (VD->hasAttr<BlocksAttr>()) {
4792 static unsigned uniqueByrefDeclCount = 0;
4793 assert(!BlockByRefDeclNo.count(ND) &&
4794 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4795 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
4796 RewriteByRefVar(VD);
4797 }
4798 else
4799 RewriteTypeOfDecl(VD);
4800 }
4801 }
4802 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
4803 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4804 RewriteBlockPointerDecl(TD);
4805 else if (TD->getUnderlyingType()->isFunctionPointerType())
4806 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4807 }
4808 }
4809 }
4810
4811 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4812 RewriteObjCQualifiedInterfaceTypes(CE);
4813
4814 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4815 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4816 assert(!Stmts.empty() && "Statement stack is empty");
4817 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4818 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4819 && "Statement stack mismatch");
4820 Stmts.pop_back();
4821 }
4822 // Handle blocks rewriting.
4823 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4824 if (BDRE->isByRef())
4825 return RewriteBlockDeclRefExpr(BDRE);
4826 }
4827 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4828 ValueDecl *VD = DRE->getDecl();
4829 if (VD->hasAttr<BlocksAttr>())
4830 return RewriteBlockDeclRefExpr(DRE);
4831 if (HasLocalVariableExternalStorage(VD))
4832 return RewriteLocalVariableExternalStorage(DRE);
4833 }
4834
4835 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4836 if (CE->getCallee()->getType()->isBlockPointerType()) {
4837 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
4838 ReplaceStmt(S, BlockCall);
4839 return BlockCall;
4840 }
4841 }
4842 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
4843 RewriteCastExpr(CE);
4844 }
4845#if 0
4846 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4847 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4848 ICE->getSubExpr(),
4849 SourceLocation());
4850 // Get the new text.
4851 std::string SStr;
4852 llvm::raw_string_ostream Buf(SStr);
4853 Replacement->printPretty(Buf, *Context);
4854 const std::string &Str = Buf.str();
4855
4856 printf("CAST = %s\n", &Str[0]);
4857 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4858 delete S;
4859 return Replacement;
4860 }
4861#endif
4862 // Return this stmt unmodified.
4863 return S;
4864}
4865
4866void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
4867 for (RecordDecl::field_iterator i = RD->field_begin(),
4868 e = RD->field_end(); i != e; ++i) {
4869 FieldDecl *FD = *i;
4870 if (isTopLevelBlockPointerType(FD->getType()))
4871 RewriteBlockPointerDecl(FD);
4872 if (FD->getType()->isObjCQualifiedIdType() ||
4873 FD->getType()->isObjCQualifiedInterfaceType())
4874 RewriteObjCQualifiedInterfaceTypes(FD);
4875 }
4876}
4877
4878/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4879/// main file of the input.
4880void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
4881 switch (D->getKind()) {
4882 case Decl::Function: {
4883 FunctionDecl *FD = cast<FunctionDecl>(D);
4884 if (FD->isOverloadedOperator())
4885 return;
4886
4887 // Since function prototypes don't have ParmDecl's, we check the function
4888 // prototype. This enables us to rewrite function declarations and
4889 // definitions using the same code.
4890 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
4891
4892 // FIXME: If this should support Obj-C++, support CXXTryStmt
4893 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4894 CurFunctionDef = FD;
4895 CurFunctionDeclToDeclareForBlock = FD;
4896 CurrentBody = Body;
4897 Body =
4898 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4899 FD->setBody(Body);
4900 CurrentBody = 0;
4901 if (PropParentMap) {
4902 delete PropParentMap;
4903 PropParentMap = 0;
4904 }
4905 // This synthesizes and inserts the block "impl" struct, invoke function,
4906 // and any copy/dispose helper functions.
4907 InsertBlockLiteralsWithinFunction(FD);
4908 CurFunctionDef = 0;
4909 CurFunctionDeclToDeclareForBlock = 0;
4910 }
4911 break;
4912 }
4913 case Decl::ObjCMethod: {
4914 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
4915 if (CompoundStmt *Body = MD->getCompoundBody()) {
4916 CurMethodDef = MD;
4917 CurrentBody = Body;
4918 Body =
4919 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4920 MD->setBody(Body);
4921 CurrentBody = 0;
4922 if (PropParentMap) {
4923 delete PropParentMap;
4924 PropParentMap = 0;
4925 }
4926 InsertBlockLiteralsWithinMethod(MD);
4927 CurMethodDef = 0;
4928 }
4929 break;
4930 }
4931 case Decl::ObjCImplementation: {
4932 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
4933 ClassImplementation.push_back(CI);
4934 break;
4935 }
4936 case Decl::ObjCCategoryImpl: {
4937 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
4938 CategoryImplementation.push_back(CI);
4939 break;
4940 }
4941 case Decl::Var: {
4942 VarDecl *VD = cast<VarDecl>(D);
4943 RewriteObjCQualifiedInterfaceTypes(VD);
4944 if (isTopLevelBlockPointerType(VD->getType()))
4945 RewriteBlockPointerDecl(VD);
4946 else if (VD->getType()->isFunctionPointerType()) {
4947 CheckFunctionPointerDecl(VD->getType(), VD);
4948 if (VD->getInit()) {
4949 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4950 RewriteCastExpr(CE);
4951 }
4952 }
4953 } else if (VD->getType()->isRecordType()) {
4954 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4955 if (RD->isCompleteDefinition())
4956 RewriteRecordBody(RD);
4957 }
4958 if (VD->getInit()) {
4959 GlobalVarDecl = VD;
4960 CurrentBody = VD->getInit();
4961 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
4962 CurrentBody = 0;
4963 if (PropParentMap) {
4964 delete PropParentMap;
4965 PropParentMap = 0;
4966 }
4967 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
4968 GlobalVarDecl = 0;
4969
4970 // This is needed for blocks.
4971 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4972 RewriteCastExpr(CE);
4973 }
4974 }
4975 break;
4976 }
4977 case Decl::TypeAlias:
4978 case Decl::Typedef: {
4979 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
4980 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4981 RewriteBlockPointerDecl(TD);
4982 else if (TD->getUnderlyingType()->isFunctionPointerType())
4983 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4984 }
4985 break;
4986 }
4987 case Decl::CXXRecord:
4988 case Decl::Record: {
4989 RecordDecl *RD = cast<RecordDecl>(D);
4990 if (RD->isCompleteDefinition())
4991 RewriteRecordBody(RD);
4992 break;
4993 }
4994 default:
4995 break;
4996 }
4997 // Nothing yet.
4998}
4999
5000void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5001 if (Diags.hasErrorOccurred())
5002 return;
5003
5004 RewriteInclude();
5005
5006 // Here's a great place to add any extra declarations that may be needed.
5007 // Write out meta data for each @protocol(<expr>).
5008 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
5009 E = ProtocolExprDecls.end(); I != E; ++I)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005010 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005011
5012 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
5013 if (ClassImplementation.size() || CategoryImplementation.size())
5014 RewriteImplementations();
5015
5016 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5017 // we are done.
5018 if (const RewriteBuffer *RewriteBuf =
5019 Rewrite.getRewriteBufferFor(MainFileID)) {
5020 //printf("Changed:\n");
5021 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5022 } else {
5023 llvm::errs() << "No changes\n";
5024 }
5025
5026 if (ClassImplementation.size() || CategoryImplementation.size() ||
5027 ProtocolExprDecls.size()) {
5028 // Rewrite Objective-c meta data*
5029 std::string ResultStr;
5030 RewriteMetaDataIntoBuffer(ResultStr);
5031 // Emit metadata.
5032 *OutFile << ResultStr;
5033 }
5034 OutFile->flush();
5035}
5036
5037void RewriteModernObjC::Initialize(ASTContext &context) {
5038 InitializeCommon(context);
5039
5040 // declaring objc_selector outside the parameter list removes a silly
5041 // scope related warning...
5042 if (IsHeader)
5043 Preamble = "#pragma once\n";
5044 Preamble += "struct objc_selector; struct objc_class;\n";
5045 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
5046 Preamble += "struct objc_object *superClass; ";
5047 if (LangOpts.MicrosoftExt) {
5048 // Add a constructor for creating temporary objects.
5049 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
5050 ": ";
5051 Preamble += "object(o), superClass(s) {} ";
5052 }
5053 Preamble += "};\n";
5054 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5055 Preamble += "typedef struct objc_object Protocol;\n";
5056 Preamble += "#define _REWRITER_typedef_Protocol\n";
5057 Preamble += "#endif\n";
5058 if (LangOpts.MicrosoftExt) {
5059 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5060 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
5061 } else
5062 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
5063 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
5064 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5065 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
5066 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5067 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
5068 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5069 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
5070 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5071 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
5072 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5073 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5074 Preamble += "(const char *);\n";
5075 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5076 Preamble += "(struct objc_class *);\n";
5077 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5078 Preamble += "(const char *);\n";
5079 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
5080 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
5081 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
5082 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
5083 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
5084 Preamble += "(struct objc_class *, struct objc_object *);\n";
5085 // @synchronized hooks.
5086 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
5087 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
5088 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5089 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5090 Preamble += "struct __objcFastEnumerationState {\n\t";
5091 Preamble += "unsigned long state;\n\t";
5092 Preamble += "void **itemsPtr;\n\t";
5093 Preamble += "unsigned long *mutationsPtr;\n\t";
5094 Preamble += "unsigned long extra[5];\n};\n";
5095 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5096 Preamble += "#define __FASTENUMERATIONSTATE\n";
5097 Preamble += "#endif\n";
5098 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5099 Preamble += "struct __NSConstantStringImpl {\n";
5100 Preamble += " int *isa;\n";
5101 Preamble += " int flags;\n";
5102 Preamble += " char *str;\n";
5103 Preamble += " long length;\n";
5104 Preamble += "};\n";
5105 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5106 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5107 Preamble += "#else\n";
5108 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5109 Preamble += "#endif\n";
5110 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5111 Preamble += "#endif\n";
5112 // Blocks preamble.
5113 Preamble += "#ifndef BLOCK_IMPL\n";
5114 Preamble += "#define BLOCK_IMPL\n";
5115 Preamble += "struct __block_impl {\n";
5116 Preamble += " void *isa;\n";
5117 Preamble += " int Flags;\n";
5118 Preamble += " int Reserved;\n";
5119 Preamble += " void *FuncPtr;\n";
5120 Preamble += "};\n";
5121 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5122 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5123 Preamble += "extern \"C\" __declspec(dllexport) "
5124 "void _Block_object_assign(void *, const void *, const int);\n";
5125 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5126 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5127 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5128 Preamble += "#else\n";
5129 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5130 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5131 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5132 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5133 Preamble += "#endif\n";
5134 Preamble += "#endif\n";
5135 if (LangOpts.MicrosoftExt) {
5136 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5137 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5138 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5139 Preamble += "#define __attribute__(X)\n";
5140 Preamble += "#endif\n";
5141 Preamble += "#define __weak\n";
5142 }
5143 else {
5144 Preamble += "#define __block\n";
5145 Preamble += "#define __weak\n";
5146 }
5147 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5148 // as this avoids warning in any 64bit/32bit compilation model.
5149 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5150}
5151
5152/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5153/// ivar offset.
5154void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5155 std::string &Result) {
5156 if (ivar->isBitField()) {
5157 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5158 // place all bitfields at offset 0.
5159 Result += "0";
5160 } else {
5161 Result += "__OFFSETOFIVAR__(struct ";
5162 Result += ivar->getContainingInterface()->getNameAsString();
5163 if (LangOpts.MicrosoftExt)
5164 Result += "_IMPL";
5165 Result += ", ";
5166 Result += ivar->getNameAsString();
5167 Result += ")";
5168 }
5169}
5170
5171/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
5172/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005173/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005174/// char *attributes;
5175/// }
5176
5177/// struct _prop_list_t {
5178/// uint32_t entsize; // sizeof(struct _prop_t)
5179/// uint32_t count_of_properties;
5180/// struct _prop_t prop_list[count_of_properties];
5181/// }
5182
5183/// struct _protocol_t;
5184
5185/// struct _protocol_list_t {
5186/// long protocol_count; // Note, this is 32/64 bit
5187/// struct _protocol_t * protocol_list[protocol_count];
5188/// }
5189
5190/// struct _objc_method {
5191/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005192/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005193/// char *_imp;
5194/// }
5195
5196/// struct _method_list_t {
5197/// uint32_t entsize; // sizeof(struct _objc_method)
5198/// uint32_t method_count;
5199/// struct _objc_method method_list[method_count];
5200/// }
5201
5202/// struct _protocol_t {
5203/// id isa; // NULL
5204/// const char * const protocol_name;
5205/// const struct _protocol_list_t * protocol_list; // super protocols
5206/// const struct method_list_t * const instance_methods;
5207/// const struct method_list_t * const class_methods;
5208/// const struct method_list_t *optionalInstanceMethods;
5209/// const struct method_list_t *optionalClassMethods;
5210/// const struct _prop_list_t * properties;
5211/// const uint32_t size; // sizeof(struct _protocol_t)
5212/// const uint32_t flags; // = 0
5213/// const char ** extendedMethodTypes;
5214/// }
5215
5216static void WriteModernMetadataDeclarations(std::string &Result) {
5217 static bool meta_data_declared = false;
5218 if (meta_data_declared)
5219 return;
5220
5221 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005222 Result += "\tconst char *name;\n";
5223 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005224 Result += "};\n";
5225
5226 Result += "\nstruct _protocol_t;\n";
5227
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005228 Result += "\nstruct _objc_method {\n";
5229 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005230 Result += "\tconst char *method_type;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005231 Result += "\tchar *_imp;\n";
5232 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005233
5234 Result += "\nstruct _protocol_t {\n";
5235 Result += "\tvoid * isa; // NULL\n";
5236 Result += "\tconst char * const protocol_name;\n";
5237 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
5238 Result += "\tconst struct method_list_t * const instance_methods;\n";
5239 Result += "\tconst struct method_list_t * const class_methods;\n";
5240 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
5241 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
5242 Result += "\tconst struct _prop_list_t * properties;\n";
5243 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
5244 Result += "\tconst unsigned int flags; // = 0\n";
5245 Result += "\tconst char ** extendedMethodTypes;\n";
5246 Result += "};\n";
5247
5248 meta_data_declared = true;
5249}
5250
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005251static void Write_protocol_list_t_TypeDecl(std::string &Result,
5252 long super_protocol_count) {
5253 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
5254 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
5255 Result += "\tstruct _protocol_t *super_protocols[";
5256 Result += utostr(super_protocol_count); Result += "];\n";
5257 Result += "}";
5258}
5259
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005260static void Write_method_list_t_TypeDecl(std::string &Result,
5261 unsigned int method_count) {
5262 Result += "struct /*_method_list_t*/"; Result += " {\n";
5263 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
5264 Result += "\tunsigned int method_count;\n";
5265 Result += "\tstruct _objc_method method_list[";
5266 Result += utostr(method_count); Result += "];\n";
5267 Result += "}";
5268}
5269
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005270static void Write__prop_list_t_TypeDecl(std::string &Result,
5271 unsigned int property_count) {
5272 Result += "struct /*_prop_list_t*/"; Result += " {\n";
5273 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5274 Result += "\tunsigned int count_of_properties;\n";
5275 Result += "\tstruct _prop_t prop_list[";
5276 Result += utostr(property_count); Result += "];\n";
5277 Result += "}";
5278}
5279
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005280static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
5281 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
5282 StringRef VarName,
5283 StringRef ProtocolName) {
5284 if (SuperProtocols.size() > 0) {
5285 Result += "\nstatic ";
5286 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
5287 Result += " "; Result += VarName;
5288 Result += ProtocolName;
5289 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5290 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
5291 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
5292 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
5293 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
5294 Result += SuperPD->getNameAsString();
5295 if (i == e-1)
5296 Result += "\n};\n";
5297 else
5298 Result += ",\n";
5299 }
5300 }
5301}
5302
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005303static void Write_method_list_t_initializer(ASTContext *Context, std::string &Result,
5304 ArrayRef<ObjCMethodDecl *> Methods,
5305 StringRef VarName,
5306 StringRef ProtocolName) {
5307 if (Methods.size() > 0) {
5308 Result += "\nstatic ";
5309 Write_method_list_t_TypeDecl(Result, Methods.size());
5310 Result += " "; Result += VarName;
5311 Result += ProtocolName;
5312 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5313 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
5314 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
5315 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
5316 ObjCMethodDecl *MD = Methods[i];
5317 if (i == 0)
5318 Result += "\t{{(struct objc_selector *)\"";
5319 else
5320 Result += "\t{(struct objc_selector *)\"";
5321 Result += (MD)->getSelector().getAsString(); Result += "\"";
5322 Result += ", ";
5323 std::string MethodTypeString;
5324 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
5325 Result += "\""; Result += MethodTypeString; Result += "\"";
5326 Result += ", ";
5327 // FIXME is _imp always null here?
5328 if (i == e-1)
5329 Result += "0}}\n";
5330 else
5331 Result += "0},\n";
5332 }
5333 Result += "};\n";
5334 }
5335}
5336
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005337static void Write__prop_list_t_initializer(RewriteModernObjC &RewriteObj,
5338 ASTContext *Context, std::string &Result,
5339 ArrayRef<ObjCPropertyDecl *> Properties,
5340 const Decl *Container,
5341 StringRef VarName,
5342 StringRef ProtocolName) {
5343 if (Properties.size() > 0) {
5344 Result += "\nstatic ";
5345 Write__prop_list_t_TypeDecl(Result, Properties.size());
5346 Result += " "; Result += VarName;
5347 Result += ProtocolName;
5348 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5349 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
5350 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
5351 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
5352 ObjCPropertyDecl *PropDecl = Properties[i];
5353 if (i == 0)
5354 Result += "\t{{\"";
5355 else
5356 Result += "\t{\"";
5357 Result += PropDecl->getName(); Result += "\",";
5358 std::string PropertyTypeString, QuotePropertyTypeString;
5359 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
5360 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
5361 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
5362 if (i == e-1)
5363 Result += "}}\n";
5364 else
5365 Result += "},\n";
5366 }
5367 Result += "};\n";
5368 }
5369}
5370
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00005371static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
5372 ASTContext *Context, std::string &Result,
5373 ArrayRef<ObjCMethodDecl *> Methods,
5374 StringRef VarName,
5375 StringRef ProtocolName) {
5376 if (Methods.size() == 0)
5377 return;
5378
5379 Result += "\nstatic const char *";
5380 Result += VarName; Result += ProtocolName;
5381 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
5382 Result += "{\n";
5383 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
5384 ObjCMethodDecl *MD = Methods[i];
5385 std::string MethodTypeString, QuoteMethodTypeString;
5386 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
5387 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
5388 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
5389 if (i == e-1)
5390 Result += "\n};\n";
5391 else {
5392 Result += ",\n";
5393 }
5394 }
5395}
5396
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005397/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005398void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
5399 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005400
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005401 // Do not synthesize the protocol more than once.
5402 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
5403 return;
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005404 WriteModernMetadataDeclarations(Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005405
5406 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
5407 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005408 // Must write out all protocol definitions in current qualifier list,
5409 // and in their nested qualifiers before writing out current definition.
5410 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
5411 E = PDecl->protocol_end(); I != E; ++I)
5412 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005413
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005414 // Construct method lists.
5415 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
5416 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
5417 for (ObjCProtocolDecl::instmeth_iterator
5418 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
5419 I != E; ++I) {
5420 ObjCMethodDecl *MD = *I;
5421 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
5422 OptInstanceMethods.push_back(MD);
5423 } else {
5424 InstanceMethods.push_back(MD);
5425 }
5426 }
5427
5428 for (ObjCProtocolDecl::classmeth_iterator
5429 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
5430 I != E; ++I) {
5431 ObjCMethodDecl *MD = *I;
5432 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
5433 OptClassMethods.push_back(MD);
5434 } else {
5435 ClassMethods.push_back(MD);
5436 }
5437 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00005438 std::vector<ObjCMethodDecl *> AllMethods;
5439 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
5440 AllMethods.push_back(InstanceMethods[i]);
5441 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
5442 AllMethods.push_back(ClassMethods[i]);
5443 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
5444 AllMethods.push_back(OptInstanceMethods[i]);
5445 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
5446 AllMethods.push_back(OptClassMethods[i]);
5447
5448 Write__extendedMethodTypes_initializer(*this, Context, Result,
5449 AllMethods,
5450 "_OBJC_PROTOCOL_METHOD_TYPES_",
5451 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005452 // Protocol's super protocol list
5453 std::vector<ObjCProtocolDecl *> SuperProtocols;
5454 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
5455 E = PDecl->protocol_end(); I != E; ++I)
5456 SuperProtocols.push_back(*I);
5457
5458 Write_protocol_list_initializer(Context, Result, SuperProtocols,
5459 "_OBJC_PROTOCOL_REFS_",
5460 PDecl->getNameAsString());
5461
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005462 Write_method_list_t_initializer(Context, Result, InstanceMethods,
5463 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
5464 PDecl->getNameAsString());
5465
5466 Write_method_list_t_initializer(Context, Result, ClassMethods,
5467 "_OBJC_PROTOCOL_CLASS_METHODS_",
5468 PDecl->getNameAsString());
5469
5470 Write_method_list_t_initializer(Context, Result, OptInstanceMethods,
5471 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
5472 PDecl->getNameAsString());
5473
5474 Write_method_list_t_initializer(Context, Result, OptClassMethods,
5475 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
5476 PDecl->getNameAsString());
5477
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005478 // Protocol's property metadata.
5479 std::vector<ObjCPropertyDecl *> ProtocolProperties;
5480 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
5481 E = PDecl->prop_end(); I != E; ++I)
5482 ProtocolProperties.push_back(*I);
5483
5484 Write__prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
5485 /* Container */0,
5486 "_OBJC_PROTOCOL_PROPERTIES_",
5487 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005488
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005489 // Writer out root metadata for current protocol: struct _protocol_t
5490 Result += "\nstatic struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005491 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005492 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
5493 Result += "\t0,\n"; // id is; is null
5494 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005495 if (SuperProtocols.size() > 0) {
5496 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
5497 Result += PDecl->getNameAsString(); Result += ",\n";
5498 }
5499 else
5500 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005501 if (InstanceMethods.size() > 0) {
5502 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
5503 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005504 }
5505 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005506 Result += "\t0,\n";
5507
5508 if (ClassMethods.size() > 0) {
5509 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
5510 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005511 }
5512 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005513 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005514
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005515 if (OptInstanceMethods.size() > 0) {
5516 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
5517 Result += PDecl->getNameAsString(); Result += ",\n";
5518 }
5519 else
5520 Result += "\t0,\n";
5521
5522 if (OptClassMethods.size() > 0) {
5523 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
5524 Result += PDecl->getNameAsString(); Result += ",\n";
5525 }
5526 else
5527 Result += "\t0,\n";
5528
5529 if (ProtocolProperties.size() > 0) {
5530 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
5531 Result += PDecl->getNameAsString(); Result += ",\n";
5532 }
5533 else
5534 Result += "\t0,\n";
5535
5536 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
5537 Result += "\t0,\n";
5538
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00005539 if (AllMethods.size() > 0) {
5540 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
5541 Result += PDecl->getNameAsString();
5542 Result += "\n};\n";
5543 }
5544 else
5545 Result += "\t0\n};\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005546
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005547 // Mark this protocol as having been generated.
5548 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
5549 llvm_unreachable("protocol already synthesized");
5550
5551}
5552
5553void RewriteModernObjC::RewriteObjCProtocolListMetaData(
5554 const ObjCList<ObjCProtocolDecl> &Protocols,
5555 StringRef prefix, StringRef ClassName,
5556 std::string &Result) {
5557 if (Protocols.empty()) return;
5558
5559 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005560 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005561
5562 // Output the top lovel protocol meta-data for the class.
5563 /* struct _objc_protocol_list {
5564 struct _objc_protocol_list *next;
5565 int protocol_count;
5566 struct _objc_protocol *class_protocols[];
5567 }
5568 */
5569 Result += "\nstatic struct {\n";
5570 Result += "\tstruct _objc_protocol_list *next;\n";
5571 Result += "\tint protocol_count;\n";
5572 Result += "\tstruct _objc_protocol *class_protocols[";
5573 Result += utostr(Protocols.size());
5574 Result += "];\n} _OBJC_";
5575 Result += prefix;
5576 Result += "_PROTOCOLS_";
5577 Result += ClassName;
5578 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5579 "{\n\t0, ";
5580 Result += utostr(Protocols.size());
5581 Result += "\n";
5582
5583 Result += "\t,{&_OBJC_PROTOCOL_";
5584 Result += Protocols[0]->getNameAsString();
5585 Result += " \n";
5586
5587 for (unsigned i = 1; i != Protocols.size(); i++) {
5588 Result += "\t ,&_OBJC_PROTOCOL_";
5589 Result += Protocols[i]->getNameAsString();
5590 Result += "\n";
5591 }
5592 Result += "\t }\n};\n";
5593}
5594
5595void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
5596 std::string &Result) {
5597 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
5598
5599 // Explicitly declared @interface's are already synthesized.
5600 if (CDecl->isImplicitInterfaceDecl()) {
5601 // FIXME: Implementation of a class with no @interface (legacy) does not
5602 // produce correct synthesis as yet.
5603 RewriteObjCInternalStruct(CDecl, Result);
5604 }
5605
5606 // Build _objc_ivar_list metadata for classes ivars if needed
5607 unsigned NumIvars = !IDecl->ivar_empty()
5608 ? IDecl->ivar_size()
5609 : (CDecl ? CDecl->ivar_size() : 0);
5610 if (NumIvars > 0) {
5611 static bool objc_ivar = false;
5612 if (!objc_ivar) {
5613 /* struct _objc_ivar {
5614 char *ivar_name;
5615 char *ivar_type;
5616 int ivar_offset;
5617 };
5618 */
5619 Result += "\nstruct _objc_ivar {\n";
5620 Result += "\tchar *ivar_name;\n";
5621 Result += "\tchar *ivar_type;\n";
5622 Result += "\tint ivar_offset;\n";
5623 Result += "};\n";
5624
5625 objc_ivar = true;
5626 }
5627
5628 /* struct {
5629 int ivar_count;
5630 struct _objc_ivar ivar_list[nIvars];
5631 };
5632 */
5633 Result += "\nstatic struct {\n";
5634 Result += "\tint ivar_count;\n";
5635 Result += "\tstruct _objc_ivar ivar_list[";
5636 Result += utostr(NumIvars);
5637 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
5638 Result += IDecl->getNameAsString();
5639 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
5640 "{\n\t";
5641 Result += utostr(NumIvars);
5642 Result += "\n";
5643
5644 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
5645 SmallVector<ObjCIvarDecl *, 8> IVars;
5646 if (!IDecl->ivar_empty()) {
5647 for (ObjCInterfaceDecl::ivar_iterator
5648 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
5649 IV != IVEnd; ++IV)
5650 IVars.push_back(*IV);
5651 IVI = IDecl->ivar_begin();
5652 IVE = IDecl->ivar_end();
5653 } else {
5654 IVI = CDecl->ivar_begin();
5655 IVE = CDecl->ivar_end();
5656 }
5657 Result += "\t,{{\"";
5658 Result += (*IVI)->getNameAsString();
5659 Result += "\", \"";
5660 std::string TmpString, StrEncoding;
5661 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
5662 QuoteDoublequotes(TmpString, StrEncoding);
5663 Result += StrEncoding;
5664 Result += "\", ";
5665 RewriteIvarOffsetComputation(*IVI, Result);
5666 Result += "}\n";
5667 for (++IVI; IVI != IVE; ++IVI) {
5668 Result += "\t ,{\"";
5669 Result += (*IVI)->getNameAsString();
5670 Result += "\", \"";
5671 std::string TmpString, StrEncoding;
5672 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
5673 QuoteDoublequotes(TmpString, StrEncoding);
5674 Result += StrEncoding;
5675 Result += "\", ";
5676 RewriteIvarOffsetComputation((*IVI), Result);
5677 Result += "}\n";
5678 }
5679
5680 Result += "\t }\n};\n";
5681 }
5682
5683 // Build _objc_method_list for class's instance methods if needed
5684 SmallVector<ObjCMethodDecl *, 32>
5685 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
5686
5687 // If any of our property implementations have associated getters or
5688 // setters, produce metadata for them as well.
5689 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
5690 PropEnd = IDecl->propimpl_end();
5691 Prop != PropEnd; ++Prop) {
5692 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5693 continue;
5694 if (!(*Prop)->getPropertyIvarDecl())
5695 continue;
5696 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
5697 if (!PD)
5698 continue;
5699 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5700 if (!Getter->isDefined())
5701 InstanceMethods.push_back(Getter);
5702 if (PD->isReadOnly())
5703 continue;
5704 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5705 if (!Setter->isDefined())
5706 InstanceMethods.push_back(Setter);
5707 }
5708 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5709 true, "", IDecl->getName(), Result);
5710
5711 // Build _objc_method_list for class's class methods if needed
5712 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5713 false, "", IDecl->getName(), Result);
5714
5715 // Protocols referenced in class declaration?
5716 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
5717 "CLASS", CDecl->getName(), Result);
5718
5719 // Declaration of class/meta-class metadata
5720 /* struct _objc_class {
5721 struct _objc_class *isa; // or const char *root_class_name when metadata
5722 const char *super_class_name;
5723 char *name;
5724 long version;
5725 long info;
5726 long instance_size;
5727 struct _objc_ivar_list *ivars;
5728 struct _objc_method_list *methods;
5729 struct objc_cache *cache;
5730 struct objc_protocol_list *protocols;
5731 const char *ivar_layout;
5732 struct _objc_class_ext *ext;
5733 };
5734 */
5735 static bool objc_class = false;
5736 if (!objc_class) {
5737 Result += "\nstruct _objc_class {\n";
5738 Result += "\tstruct _objc_class *isa;\n";
5739 Result += "\tconst char *super_class_name;\n";
5740 Result += "\tchar *name;\n";
5741 Result += "\tlong version;\n";
5742 Result += "\tlong info;\n";
5743 Result += "\tlong instance_size;\n";
5744 Result += "\tstruct _objc_ivar_list *ivars;\n";
5745 Result += "\tstruct _objc_method_list *methods;\n";
5746 Result += "\tstruct objc_cache *cache;\n";
5747 Result += "\tstruct _objc_protocol_list *protocols;\n";
5748 Result += "\tconst char *ivar_layout;\n";
5749 Result += "\tstruct _objc_class_ext *ext;\n";
5750 Result += "};\n";
5751 objc_class = true;
5752 }
5753
5754 // Meta-class metadata generation.
5755 ObjCInterfaceDecl *RootClass = 0;
5756 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
5757 while (SuperClass) {
5758 RootClass = SuperClass;
5759 SuperClass = SuperClass->getSuperClass();
5760 }
5761 SuperClass = CDecl->getSuperClass();
5762
5763 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
5764 Result += CDecl->getNameAsString();
5765 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
5766 "{\n\t(struct _objc_class *)\"";
5767 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
5768 Result += "\"";
5769
5770 if (SuperClass) {
5771 Result += ", \"";
5772 Result += SuperClass->getNameAsString();
5773 Result += "\", \"";
5774 Result += CDecl->getNameAsString();
5775 Result += "\"";
5776 }
5777 else {
5778 Result += ", 0, \"";
5779 Result += CDecl->getNameAsString();
5780 Result += "\"";
5781 }
5782 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
5783 // 'info' field is initialized to CLS_META(2) for metaclass
5784 Result += ", 0,2, sizeof(struct _objc_class), 0";
5785 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5786 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
5787 Result += IDecl->getNameAsString();
5788 Result += "\n";
5789 }
5790 else
5791 Result += ", 0\n";
5792 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5793 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
5794 Result += CDecl->getNameAsString();
5795 Result += ",0,0\n";
5796 }
5797 else
5798 Result += "\t,0,0,0,0\n";
5799 Result += "};\n";
5800
5801 // class metadata generation.
5802 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
5803 Result += CDecl->getNameAsString();
5804 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
5805 "{\n\t&_OBJC_METACLASS_";
5806 Result += CDecl->getNameAsString();
5807 if (SuperClass) {
5808 Result += ", \"";
5809 Result += SuperClass->getNameAsString();
5810 Result += "\", \"";
5811 Result += CDecl->getNameAsString();
5812 Result += "\"";
5813 }
5814 else {
5815 Result += ", 0, \"";
5816 Result += CDecl->getNameAsString();
5817 Result += "\"";
5818 }
5819 // 'info' field is initialized to CLS_CLASS(1) for class
5820 Result += ", 0,1";
5821 if (!ObjCSynthesizedStructs.count(CDecl))
5822 Result += ",0";
5823 else {
5824 // class has size. Must synthesize its size.
5825 Result += ",sizeof(struct ";
5826 Result += CDecl->getNameAsString();
5827 if (LangOpts.MicrosoftExt)
5828 Result += "_IMPL";
5829 Result += ")";
5830 }
5831 if (NumIvars > 0) {
5832 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
5833 Result += CDecl->getNameAsString();
5834 Result += "\n\t";
5835 }
5836 else
5837 Result += ",0";
5838 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5839 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
5840 Result += CDecl->getNameAsString();
5841 Result += ", 0\n\t";
5842 }
5843 else
5844 Result += ",0,0";
5845 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5846 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
5847 Result += CDecl->getNameAsString();
5848 Result += ", 0,0\n";
5849 }
5850 else
5851 Result += ",0,0,0\n";
5852 Result += "};\n";
5853}
5854
5855void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
5856 int ClsDefCount = ClassImplementation.size();
5857 int CatDefCount = CategoryImplementation.size();
5858
5859 // For each implemented class, write out all its meta data.
5860 for (int i = 0; i < ClsDefCount; i++)
5861 RewriteObjCClassMetaData(ClassImplementation[i], Result);
5862
5863 // For each implemented category, write out all its meta data.
5864 for (int i = 0; i < CatDefCount; i++)
5865 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
5866
5867 // Write objc_symtab metadata
5868 /*
5869 struct _objc_symtab
5870 {
5871 long sel_ref_cnt;
5872 SEL *refs;
5873 short cls_def_cnt;
5874 short cat_def_cnt;
5875 void *defs[cls_def_cnt + cat_def_cnt];
5876 };
5877 */
5878
5879 Result += "\nstruct _objc_symtab {\n";
5880 Result += "\tlong sel_ref_cnt;\n";
5881 Result += "\tSEL *refs;\n";
5882 Result += "\tshort cls_def_cnt;\n";
5883 Result += "\tshort cat_def_cnt;\n";
5884 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
5885 Result += "};\n\n";
5886
5887 Result += "static struct _objc_symtab "
5888 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
5889 Result += "\t0, 0, " + utostr(ClsDefCount)
5890 + ", " + utostr(CatDefCount) + "\n";
5891 for (int i = 0; i < ClsDefCount; i++) {
5892 Result += "\t,&_OBJC_CLASS_";
5893 Result += ClassImplementation[i]->getNameAsString();
5894 Result += "\n";
5895 }
5896
5897 for (int i = 0; i < CatDefCount; i++) {
5898 Result += "\t,&_OBJC_CATEGORY_";
5899 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
5900 Result += "_";
5901 Result += CategoryImplementation[i]->getNameAsString();
5902 Result += "\n";
5903 }
5904
5905 Result += "};\n\n";
5906
5907 // Write objc_module metadata
5908
5909 /*
5910 struct _objc_module {
5911 long version;
5912 long size;
5913 const char *name;
5914 struct _objc_symtab *symtab;
5915 }
5916 */
5917
5918 Result += "\nstruct _objc_module {\n";
5919 Result += "\tlong version;\n";
5920 Result += "\tlong size;\n";
5921 Result += "\tconst char *name;\n";
5922 Result += "\tstruct _objc_symtab *symtab;\n";
5923 Result += "};\n\n";
5924 Result += "static struct _objc_module "
5925 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
5926 Result += "\t" + utostr(OBJC_ABI_VERSION) +
5927 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
5928 Result += "};\n\n";
5929
5930 if (LangOpts.MicrosoftExt) {
5931 if (ProtocolExprDecls.size()) {
5932 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
5933 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
5934 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
5935 E = ProtocolExprDecls.end(); I != E; ++I) {
5936 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
5937 Result += (*I)->getNameAsString();
5938 Result += " = &_OBJC_PROTOCOL_";
5939 Result += (*I)->getNameAsString();
5940 Result += ";\n";
5941 }
5942 Result += "#pragma data_seg(pop)\n\n";
5943 }
5944 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
5945 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
5946 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
5947 Result += "&_OBJC_MODULES;\n";
5948 Result += "#pragma data_seg(pop)\n\n";
5949 }
5950}
5951
5952/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
5953/// implementation.
5954void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
5955 std::string &Result) {
5956 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
5957 // Find category declaration for this implementation.
5958 ObjCCategoryDecl *CDecl;
5959 for (CDecl = ClassDecl->getCategoryList(); CDecl;
5960 CDecl = CDecl->getNextClassCategory())
5961 if (CDecl->getIdentifier() == IDecl->getIdentifier())
5962 break;
5963
5964 std::string FullCategoryName = ClassDecl->getNameAsString();
5965 FullCategoryName += '_';
5966 FullCategoryName += IDecl->getNameAsString();
5967
5968 // Build _objc_method_list for class's instance methods if needed
5969 SmallVector<ObjCMethodDecl *, 32>
5970 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
5971
5972 // If any of our property implementations have associated getters or
5973 // setters, produce metadata for them as well.
5974 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
5975 PropEnd = IDecl->propimpl_end();
5976 Prop != PropEnd; ++Prop) {
5977 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5978 continue;
5979 if (!(*Prop)->getPropertyIvarDecl())
5980 continue;
5981 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
5982 if (!PD)
5983 continue;
5984 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5985 InstanceMethods.push_back(Getter);
5986 if (PD->isReadOnly())
5987 continue;
5988 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5989 InstanceMethods.push_back(Setter);
5990 }
5991 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5992 true, "CATEGORY_", FullCategoryName.c_str(),
5993 Result);
5994
5995 // Build _objc_method_list for class's class methods if needed
5996 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5997 false, "CATEGORY_", FullCategoryName.c_str(),
5998 Result);
5999
6000 // Protocols referenced in class declaration?
6001 // Null CDecl is case of a category implementation with no category interface
6002 if (CDecl)
6003 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
6004 FullCategoryName, Result);
6005 /* struct _objc_category {
6006 char *category_name;
6007 char *class_name;
6008 struct _objc_method_list *instance_methods;
6009 struct _objc_method_list *class_methods;
6010 struct _objc_protocol_list *protocols;
6011 // Objective-C 1.0 extensions
6012 uint32_t size; // sizeof (struct _objc_category)
6013 struct _objc_property_list *instance_properties; // category's own
6014 // @property decl.
6015 };
6016 */
6017
6018 static bool objc_category = false;
6019 if (!objc_category) {
6020 Result += "\nstruct _objc_category {\n";
6021 Result += "\tchar *category_name;\n";
6022 Result += "\tchar *class_name;\n";
6023 Result += "\tstruct _objc_method_list *instance_methods;\n";
6024 Result += "\tstruct _objc_method_list *class_methods;\n";
6025 Result += "\tstruct _objc_protocol_list *protocols;\n";
6026 Result += "\tunsigned int size;\n";
6027 Result += "\tstruct _objc_property_list *instance_properties;\n";
6028 Result += "};\n";
6029 objc_category = true;
6030 }
6031 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
6032 Result += FullCategoryName;
6033 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
6034 Result += IDecl->getNameAsString();
6035 Result += "\"\n\t, \"";
6036 Result += ClassDecl->getNameAsString();
6037 Result += "\"\n";
6038
6039 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
6040 Result += "\t, (struct _objc_method_list *)"
6041 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
6042 Result += FullCategoryName;
6043 Result += "\n";
6044 }
6045 else
6046 Result += "\t, 0\n";
6047 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
6048 Result += "\t, (struct _objc_method_list *)"
6049 "&_OBJC_CATEGORY_CLASS_METHODS_";
6050 Result += FullCategoryName;
6051 Result += "\n";
6052 }
6053 else
6054 Result += "\t, 0\n";
6055
6056 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
6057 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
6058 Result += FullCategoryName;
6059 Result += "\n";
6060 }
6061 else
6062 Result += "\t, 0\n";
6063 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
6064}
6065
6066// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
6067/// class methods.
6068template<typename MethodIterator>
6069void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
6070 MethodIterator MethodEnd,
6071 bool IsInstanceMethod,
6072 StringRef prefix,
6073 StringRef ClassName,
6074 std::string &Result) {
6075 if (MethodBegin == MethodEnd) return;
6076
6077 if (!objc_impl_method) {
6078 /* struct _objc_method {
6079 SEL _cmd;
6080 char *method_types;
6081 void *_imp;
6082 }
6083 */
6084 Result += "\nstruct _objc_method {\n";
6085 Result += "\tSEL _cmd;\n";
6086 Result += "\tchar *method_types;\n";
6087 Result += "\tvoid *_imp;\n";
6088 Result += "};\n";
6089
6090 objc_impl_method = true;
6091 }
6092
6093 // Build _objc_method_list for class's methods if needed
6094
6095 /* struct {
6096 struct _objc_method_list *next_method;
6097 int method_count;
6098 struct _objc_method method_list[];
6099 }
6100 */
6101 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
6102 Result += "\nstatic struct {\n";
6103 Result += "\tstruct _objc_method_list *next_method;\n";
6104 Result += "\tint method_count;\n";
6105 Result += "\tstruct _objc_method method_list[";
6106 Result += utostr(NumMethods);
6107 Result += "];\n} _OBJC_";
6108 Result += prefix;
6109 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
6110 Result += "_METHODS_";
6111 Result += ClassName;
6112 Result += " __attribute__ ((used, section (\"__OBJC, __";
6113 Result += IsInstanceMethod ? "inst" : "cls";
6114 Result += "_meth\")))= ";
6115 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
6116
6117 Result += "\t,{{(SEL)\"";
6118 Result += (*MethodBegin)->getSelector().getAsString().c_str();
6119 std::string MethodTypeString;
6120 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
6121 Result += "\", \"";
6122 Result += MethodTypeString;
6123 Result += "\", (void *)";
6124 Result += MethodInternalNames[*MethodBegin];
6125 Result += "}\n";
6126 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
6127 Result += "\t ,{(SEL)\"";
6128 Result += (*MethodBegin)->getSelector().getAsString().c_str();
6129 std::string MethodTypeString;
6130 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
6131 Result += "\", \"";
6132 Result += MethodTypeString;
6133 Result += "\", (void *)";
6134 Result += MethodInternalNames[*MethodBegin];
6135 Result += "}\n";
6136 }
6137 Result += "\t }\n};\n";
6138}
6139
6140Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
6141 SourceRange OldRange = IV->getSourceRange();
6142 Expr *BaseExpr = IV->getBase();
6143
6144 // Rewrite the base, but without actually doing replaces.
6145 {
6146 DisableReplaceStmtScope S(*this);
6147 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
6148 IV->setBase(BaseExpr);
6149 }
6150
6151 ObjCIvarDecl *D = IV->getDecl();
6152
6153 Expr *Replacement = IV;
6154 if (CurMethodDef) {
6155 if (BaseExpr->getType()->isObjCObjectPointerType()) {
6156 const ObjCInterfaceType *iFaceDecl =
6157 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
6158 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
6159 // lookup which class implements the instance variable.
6160 ObjCInterfaceDecl *clsDeclared = 0;
6161 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
6162 clsDeclared);
6163 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
6164
6165 // Synthesize an explicit cast to gain access to the ivar.
6166 std::string RecName = clsDeclared->getIdentifier()->getName();
6167 RecName += "_IMPL";
6168 IdentifierInfo *II = &Context->Idents.get(RecName);
6169 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
6170 SourceLocation(), SourceLocation(),
6171 II);
6172 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
6173 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
6174 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
6175 CK_BitCast,
6176 IV->getBase());
6177 // Don't forget the parens to enforce the proper binding.
6178 ParenExpr *PE = new (Context) ParenExpr(OldRange.getBegin(),
6179 OldRange.getEnd(),
6180 castExpr);
6181 if (IV->isFreeIvar() &&
6182 declaresSameEntity(CurMethodDef->getClassInterface(), iFaceDecl->getDecl())) {
6183 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
6184 IV->getLocation(),
6185 D->getType(),
6186 VK_LValue, OK_Ordinary);
6187 Replacement = ME;
6188 } else {
6189 IV->setBase(PE);
6190 }
6191 }
6192 } else { // we are outside a method.
6193 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
6194
6195 // Explicit ivar refs need to have a cast inserted.
6196 // FIXME: consider sharing some of this code with the code above.
6197 if (BaseExpr->getType()->isObjCObjectPointerType()) {
6198 const ObjCInterfaceType *iFaceDecl =
6199 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
6200 // lookup which class implements the instance variable.
6201 ObjCInterfaceDecl *clsDeclared = 0;
6202 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
6203 clsDeclared);
6204 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
6205
6206 // Synthesize an explicit cast to gain access to the ivar.
6207 std::string RecName = clsDeclared->getIdentifier()->getName();
6208 RecName += "_IMPL";
6209 IdentifierInfo *II = &Context->Idents.get(RecName);
6210 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
6211 SourceLocation(), SourceLocation(),
6212 II);
6213 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
6214 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
6215 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
6216 CK_BitCast,
6217 IV->getBase());
6218 // Don't forget the parens to enforce the proper binding.
6219 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
6220 IV->getBase()->getLocEnd(), castExpr);
6221 // Cannot delete IV->getBase(), since PE points to it.
6222 // Replace the old base with the cast. This is important when doing
6223 // embedded rewrites. For example, [newInv->_container addObject:0].
6224 IV->setBase(PE);
6225 }
6226 }
6227
6228 ReplaceStmtWithRange(IV, Replacement, OldRange);
6229 return Replacement;
6230}
6231