1 //===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Hacks and fun related to the code rewriter.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Rewrite/Frontend/ASTConsumers.h"
15 #include "clang/AST/AST.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/ParentMap.h"
19 #include "clang/Basic/CharInfo.h"
20 #include "clang/Basic/Diagnostic.h"
21 #include "clang/Basic/IdentifierTable.h"
22 #include "clang/Basic/SourceManager.h"
23 #include "clang/Config/config.h"
24 #include "clang/Lex/Lexer.h"
25 #include "clang/Rewrite/Core/Rewriter.h"
26 #include "llvm/ADT/DenseSet.h"
27 #include "llvm/ADT/SmallPtrSet.h"
28 #include "llvm/ADT/StringExtras.h"
29 #include "llvm/Support/MemoryBuffer.h"
30 #include "llvm/Support/raw_ostream.h"
33 #if CLANG_ENABLE_OBJC_REWRITER
35 using namespace clang;
39 class RewriteObjC : public ASTConsumer {
42 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
44 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
45 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
47 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
49 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
51 BLOCK_BYREF_CURRENT_MAX = 256
55 BLOCK_NEEDS_FREE = (1 << 24),
56 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
57 BLOCK_HAS_CXX_OBJ = (1 << 26),
58 BLOCK_IS_GC = (1 << 27),
59 BLOCK_IS_GLOBAL = (1 << 28),
60 BLOCK_HAS_DESCRIPTOR = (1 << 29)
62 static const int OBJC_ABI_VERSION = 7;
65 DiagnosticsEngine &Diags;
66 const LangOptions &LangOpts;
69 TranslationUnitDecl *TUDecl;
71 const char *MainFileStart, *MainFileEnd;
73 ParentMap *PropParentMap; // created lazily.
74 std::string InFileName;
75 std::unique_ptr<raw_ostream> OutFile;
78 TypeDecl *ProtocolTypeDecl;
79 VarDecl *GlobalVarDecl;
80 unsigned RewriteFailedDiag;
81 // ObjC string constant support.
82 unsigned NumObjCStringLiterals;
83 VarDecl *ConstantStringClassReference;
84 RecordDecl *NSStringRecord;
86 // ObjC foreach break/continue generation support.
89 unsigned TryFinallyContainsReturnDiag;
91 ObjCMethodDecl *CurMethodDef;
92 RecordDecl *SuperStructDecl;
93 RecordDecl *ConstantStringDecl;
95 FunctionDecl *MsgSendFunctionDecl;
96 FunctionDecl *MsgSendSuperFunctionDecl;
97 FunctionDecl *MsgSendStretFunctionDecl;
98 FunctionDecl *MsgSendSuperStretFunctionDecl;
99 FunctionDecl *MsgSendFpretFunctionDecl;
100 FunctionDecl *GetClassFunctionDecl;
101 FunctionDecl *GetMetaClassFunctionDecl;
102 FunctionDecl *GetSuperClassFunctionDecl;
103 FunctionDecl *SelGetUidFunctionDecl;
104 FunctionDecl *CFStringFunctionDecl;
105 FunctionDecl *SuperConstructorFunctionDecl;
106 FunctionDecl *CurFunctionDef;
107 FunctionDecl *CurFunctionDeclToDeclareForBlock;
109 /* Misc. containers needed for meta-data rewrite. */
110 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
111 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
112 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
113 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
114 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
115 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
116 SmallVector<Stmt *, 32> Stmts;
117 SmallVector<int, 8> ObjCBcLabelNo;
118 // Remember all the @protocol(<expr>) expressions.
119 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
121 llvm::DenseSet<uint64_t> CopyDestroyCache;
123 // Block expressions.
124 SmallVector<BlockExpr *, 32> Blocks;
125 SmallVector<int, 32> InnerDeclRefsCount;
126 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
128 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
130 // Block related declarations.
131 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
132 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
133 SmallVector<ValueDecl *, 8> BlockByRefDecls;
134 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
135 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
136 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
137 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
139 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
141 // This maps an original source AST to it's rewritten form. This allows
142 // us to avoid rewriting the same node twice (which is very uncommon).
143 // This is needed to support some of the exotic property rewriting.
144 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
146 // Needed for header files being rewritten
148 bool SilenceRewriteMacroWarning;
149 bool objc_impl_method;
151 bool DisableReplaceStmt;
152 class DisableReplaceStmtScope {
157 DisableReplaceStmtScope(RewriteObjC &R)
158 : R(R), SavedValue(R.DisableReplaceStmt) {
159 R.DisableReplaceStmt = true;
162 ~DisableReplaceStmtScope() {
163 R.DisableReplaceStmt = SavedValue;
167 void InitializeCommon(ASTContext &context);
170 // Top Level Driver code.
171 bool HandleTopLevelDecl(DeclGroupRef D) override {
172 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
173 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
174 if (!Class->isThisDeclarationADefinition()) {
175 RewriteForwardClassDecl(D);
180 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
181 if (!Proto->isThisDeclarationADefinition()) {
182 RewriteForwardProtocolDecl(D);
187 HandleTopLevelSingleDecl(*I);
192 void HandleTopLevelSingleDecl(Decl *D);
193 void HandleDeclInMainFile(Decl *D);
194 RewriteObjC(std::string inFile, std::unique_ptr<raw_ostream> OS,
195 DiagnosticsEngine &D, const LangOptions &LOpts,
196 bool silenceMacroWarn);
198 ~RewriteObjC() override {}
200 void HandleTranslationUnit(ASTContext &C) override;
202 void ReplaceStmt(Stmt *Old, Stmt *New) {
203 ReplaceStmtWithRange(Old, New, Old->getSourceRange());
206 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
207 assert(Old != nullptr && New != nullptr && "Expected non-null Stmt's");
209 Stmt *ReplacingStmt = ReplacedNodes[Old];
211 return; // We can't rewrite the same node twice.
213 if (DisableReplaceStmt)
216 // Measure the old text.
217 int Size = Rewrite.getRangeSize(SrcRange);
219 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
220 << Old->getSourceRange();
225 llvm::raw_string_ostream S(SStr);
226 New->printPretty(S, nullptr, PrintingPolicy(LangOpts));
227 const std::string &Str = S.str();
229 // If replacement succeeded or warning disabled return with no warning.
230 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
231 ReplacedNodes[Old] = New;
234 if (SilenceRewriteMacroWarning)
236 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
237 << Old->getSourceRange();
240 void InsertText(SourceLocation Loc, StringRef Str,
241 bool InsertAfter = true) {
242 // If insertion succeeded or warning disabled return with no warning.
243 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
244 SilenceRewriteMacroWarning)
247 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
250 void ReplaceText(SourceLocation Start, unsigned OrigLength,
252 // If removal succeeded or warning disabled return with no warning.
253 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
254 SilenceRewriteMacroWarning)
257 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
260 // Syntactic Rewriting.
261 void RewriteRecordBody(RecordDecl *RD);
262 void RewriteInclude();
263 void RewriteForwardClassDecl(DeclGroupRef D);
264 void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG);
265 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
266 const std::string &typedefString);
267 void RewriteImplementations();
268 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
269 ObjCImplementationDecl *IMD,
270 ObjCCategoryImplDecl *CID);
271 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
272 void RewriteImplementationDecl(Decl *Dcl);
273 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
274 ObjCMethodDecl *MDecl, std::string &ResultStr);
275 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
276 const FunctionType *&FPRetType);
277 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
278 ValueDecl *VD, bool def=false);
279 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
280 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
281 void RewriteForwardProtocolDecl(DeclGroupRef D);
282 void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG);
283 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
284 void RewriteProperty(ObjCPropertyDecl *prop);
285 void RewriteFunctionDecl(FunctionDecl *FD);
286 void RewriteBlockPointerType(std::string& Str, QualType Type);
287 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
288 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
289 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
290 void RewriteTypeOfDecl(VarDecl *VD);
291 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
293 // Expression Rewriting.
294 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
295 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
296 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
297 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
298 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
299 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
300 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
301 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
302 void RewriteTryReturnStmts(Stmt *S);
303 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
304 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
305 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
306 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
307 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
308 SourceLocation OrigEnd);
309 Stmt *RewriteBreakStmt(BreakStmt *S);
310 Stmt *RewriteContinueStmt(ContinueStmt *S);
311 void RewriteCastExpr(CStyleCastExpr *CE);
314 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
316 // Block specific rewrite rules.
317 void RewriteBlockPointerDecl(NamedDecl *VD);
318 void RewriteByRefVar(VarDecl *VD);
319 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
320 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
321 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
323 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
324 std::string &Result);
326 void Initialize(ASTContext &context) override = 0;
328 // Metadata Rewriting.
329 virtual void RewriteMetaDataIntoBuffer(std::string &Result) = 0;
330 virtual void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
333 std::string &Result) = 0;
334 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
335 std::string &Result) = 0;
336 virtual void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
339 std::string &Result) = 0;
340 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
341 std::string &Result) = 0;
343 // Rewriting ivar access
344 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) = 0;
345 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
346 std::string &Result) = 0;
348 // Misc. AST transformation routines. Sometimes they end up calling
349 // rewriting routines on the new ASTs.
350 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
351 ArrayRef<Expr *> Args,
352 SourceLocation StartLoc=SourceLocation(),
353 SourceLocation EndLoc=SourceLocation());
354 CallExpr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
355 QualType msgSendType,
357 SmallVectorImpl<QualType> &ArgTypes,
358 SmallVectorImpl<Expr*> &MsgExprs,
359 ObjCMethodDecl *Method);
360 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
361 SourceLocation StartLoc=SourceLocation(),
362 SourceLocation EndLoc=SourceLocation());
364 void SynthCountByEnumWithState(std::string &buf);
365 void SynthMsgSendFunctionDecl();
366 void SynthMsgSendSuperFunctionDecl();
367 void SynthMsgSendStretFunctionDecl();
368 void SynthMsgSendFpretFunctionDecl();
369 void SynthMsgSendSuperStretFunctionDecl();
370 void SynthGetClassFunctionDecl();
371 void SynthGetMetaClassFunctionDecl();
372 void SynthGetSuperClassFunctionDecl();
373 void SynthSelGetUidFunctionDecl();
374 void SynthSuperConstructorFunctionDecl();
376 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
377 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
378 StringRef funcName, std::string Tag);
379 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
380 StringRef funcName, std::string Tag);
381 std::string SynthesizeBlockImpl(BlockExpr *CE,
382 std::string Tag, std::string Desc);
383 std::string SynthesizeBlockDescriptor(std::string DescTag,
385 int i, StringRef funcName,
387 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
388 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
390 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
391 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
392 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
394 // Misc. helper routines.
395 QualType getProtocolType();
396 void WarnAboutReturnGotoStmts(Stmt *S);
397 void HasReturnStmts(Stmt *S, bool &hasReturns);
398 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
399 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
400 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
402 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
403 void CollectBlockDeclRefInfo(BlockExpr *Exp);
404 void GetBlockDeclRefExprs(Stmt *S);
405 void GetInnerBlockDeclRefExprs(Stmt *S,
406 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
407 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts);
409 // We avoid calling Type::isBlockPointerType(), since it operates on the
410 // canonical type. We only care if the top-level type is a closure pointer.
411 bool isTopLevelBlockPointerType(QualType T) {
412 return isa<BlockPointerType>(T);
415 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
416 /// to a function pointer type and upon success, returns true; false
418 bool convertBlockPointerToFunctionPointer(QualType &T) {
419 if (isTopLevelBlockPointerType(T)) {
420 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
421 T = Context->getPointerType(BPT->getPointeeType());
427 bool needToScanForQualifiers(QualType T);
428 QualType getSuperStructType();
429 QualType getConstantStringStructType();
430 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
431 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
433 void convertToUnqualifiedObjCType(QualType &T) {
434 if (T->isObjCQualifiedIdType())
435 T = Context->getObjCIdType();
436 else if (T->isObjCQualifiedClassType())
437 T = Context->getObjCClassType();
438 else if (T->isObjCObjectPointerType() &&
439 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
440 if (const ObjCObjectPointerType * OBJPT =
441 T->getAsObjCInterfacePointerType()) {
442 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
443 T = QualType(IFaceT, 0);
444 T = Context->getPointerType(T);
449 // FIXME: This predicate seems like it would be useful to add to ASTContext.
450 bool isObjCType(QualType T) {
451 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
454 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
456 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
457 OCT == Context->getCanonicalType(Context->getObjCClassType()))
460 if (const PointerType *PT = OCT->getAs<PointerType>()) {
461 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
462 PT->getPointeeType()->isObjCQualifiedIdType())
467 bool PointerTypeTakesAnyBlockArguments(QualType QT);
468 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
469 void GetExtentOfArgList(const char *Name, const char *&LParen,
470 const char *&RParen);
472 void QuoteDoublequotes(std::string &From, std::string &To) {
473 for (unsigned i = 0; i < From.length(); i++) {
481 QualType getSimpleFunctionType(QualType result,
482 ArrayRef<QualType> args,
483 bool variadic = false) {
484 if (result == Context->getObjCInstanceType())
485 result = Context->getObjCIdType();
486 FunctionProtoType::ExtProtoInfo fpi;
487 fpi.Variadic = variadic;
488 return Context->getFunctionType(result, args, fpi);
491 // Helper function: create a CStyleCastExpr with trivial type source info.
492 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
493 CastKind Kind, Expr *E) {
494 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
495 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, nullptr,
496 TInfo, SourceLocation(), SourceLocation());
499 StringLiteral *getStringLiteral(StringRef Str) {
500 QualType StrType = Context->getConstantArrayType(
501 Context->CharTy, llvm::APInt(32, Str.size() + 1), ArrayType::Normal,
503 return StringLiteral::Create(*Context, Str, StringLiteral::Ascii,
504 /*Pascal=*/false, StrType, SourceLocation());
508 class RewriteObjCFragileABI : public RewriteObjC {
510 RewriteObjCFragileABI(std::string inFile, std::unique_ptr<raw_ostream> OS,
511 DiagnosticsEngine &D, const LangOptions &LOpts,
512 bool silenceMacroWarn)
513 : RewriteObjC(inFile, std::move(OS), D, LOpts, silenceMacroWarn) {}
515 ~RewriteObjCFragileABI() override {}
516 void Initialize(ASTContext &context) override;
518 // Rewriting metadata
519 template<typename MethodIterator>
520 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
521 MethodIterator MethodEnd,
522 bool IsInstanceMethod,
525 std::string &Result);
526 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
527 StringRef prefix, StringRef ClassName,
528 std::string &Result) override;
529 void RewriteObjCProtocolListMetaData(
530 const ObjCList<ObjCProtocolDecl> &Prots,
531 StringRef prefix, StringRef ClassName, std::string &Result) override;
532 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
533 std::string &Result) override;
534 void RewriteMetaDataIntoBuffer(std::string &Result) override;
535 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
536 std::string &Result) override;
539 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
540 std::string &Result) override;
541 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) override;
543 } // end anonymous namespace
545 void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
547 if (const FunctionProtoType *fproto
548 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
549 for (const auto &I : fproto->param_types())
550 if (isTopLevelBlockPointerType(I)) {
551 // All the args are checked/rewritten. Don't call twice!
552 RewriteBlockPointerDecl(D);
558 void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
559 const PointerType *PT = funcType->getAs<PointerType>();
560 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
561 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
564 static bool IsHeaderFile(const std::string &Filename) {
565 std::string::size_type DotPos = Filename.rfind('.');
567 if (DotPos == std::string::npos) {
572 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
574 // C++ header: .hh or .H;
575 return Ext == "h" || Ext == "hh" || Ext == "H";
578 RewriteObjC::RewriteObjC(std::string inFile, std::unique_ptr<raw_ostream> OS,
579 DiagnosticsEngine &D, const LangOptions &LOpts,
580 bool silenceMacroWarn)
581 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(std::move(OS)),
582 SilenceRewriteMacroWarning(silenceMacroWarn) {
583 IsHeader = IsHeaderFile(inFile);
584 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
585 "rewriting sub-expression within a macro (may not be correct)");
586 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
587 DiagnosticsEngine::Warning,
588 "rewriter doesn't support user-specified control flow semantics "
589 "for @try/@finally (code may not execute properly)");
592 std::unique_ptr<ASTConsumer>
593 clang::CreateObjCRewriter(const std::string &InFile,
594 std::unique_ptr<raw_ostream> OS,
595 DiagnosticsEngine &Diags, const LangOptions &LOpts,
596 bool SilenceRewriteMacroWarning) {
597 return llvm::make_unique<RewriteObjCFragileABI>(
598 InFile, std::move(OS), Diags, LOpts, SilenceRewriteMacroWarning);
601 void RewriteObjC::InitializeCommon(ASTContext &context) {
603 SM = &Context->getSourceManager();
604 TUDecl = Context->getTranslationUnitDecl();
605 MsgSendFunctionDecl = nullptr;
606 MsgSendSuperFunctionDecl = nullptr;
607 MsgSendStretFunctionDecl = nullptr;
608 MsgSendSuperStretFunctionDecl = nullptr;
609 MsgSendFpretFunctionDecl = nullptr;
610 GetClassFunctionDecl = nullptr;
611 GetMetaClassFunctionDecl = nullptr;
612 GetSuperClassFunctionDecl = nullptr;
613 SelGetUidFunctionDecl = nullptr;
614 CFStringFunctionDecl = nullptr;
615 ConstantStringClassReference = nullptr;
616 NSStringRecord = nullptr;
617 CurMethodDef = nullptr;
618 CurFunctionDef = nullptr;
619 CurFunctionDeclToDeclareForBlock = nullptr;
620 GlobalVarDecl = nullptr;
621 SuperStructDecl = nullptr;
622 ProtocolTypeDecl = nullptr;
623 ConstantStringDecl = nullptr;
625 SuperConstructorFunctionDecl = nullptr;
626 NumObjCStringLiterals = 0;
627 PropParentMap = nullptr;
628 CurrentBody = nullptr;
629 DisableReplaceStmt = false;
630 objc_impl_method = false;
632 // Get the ID and start/end of the main file.
633 MainFileID = SM->getMainFileID();
634 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
635 MainFileStart = MainBuf->getBufferStart();
636 MainFileEnd = MainBuf->getBufferEnd();
638 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
641 //===----------------------------------------------------------------------===//
642 // Top Level Driver Code
643 //===----------------------------------------------------------------------===//
645 void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
646 if (Diags.hasErrorOccurred())
649 // Two cases: either the decl could be in the main file, or it could be in a
650 // #included file. If the former, rewrite it now. If the later, check to see
651 // if we rewrote the #include/#import.
652 SourceLocation Loc = D->getLocation();
653 Loc = SM->getExpansionLoc(Loc);
655 // If this is for a builtin, ignore it.
656 if (Loc.isInvalid()) return;
658 // Look for built-in declarations that we need to refer during the rewrite.
659 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
660 RewriteFunctionDecl(FD);
661 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
662 // declared in <Foundation/NSString.h>
663 if (FVD->getName() == "_NSConstantStringClassReference") {
664 ConstantStringClassReference = FVD;
667 } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
668 if (ID->isThisDeclarationADefinition())
669 RewriteInterfaceDecl(ID);
670 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
671 RewriteCategoryDecl(CD);
672 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
673 if (PD->isThisDeclarationADefinition())
674 RewriteProtocolDecl(PD);
675 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
676 // Recurse into linkage specifications
677 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
678 DIEnd = LSD->decls_end();
680 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
681 if (!IFace->isThisDeclarationADefinition()) {
682 SmallVector<Decl *, 8> DG;
683 SourceLocation StartLoc = IFace->getLocStart();
685 if (isa<ObjCInterfaceDecl>(*DI) &&
686 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
687 StartLoc == (*DI)->getLocStart())
693 } while (DI != DIEnd);
694 RewriteForwardClassDecl(DG);
699 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
700 if (!Proto->isThisDeclarationADefinition()) {
701 SmallVector<Decl *, 8> DG;
702 SourceLocation StartLoc = Proto->getLocStart();
704 if (isa<ObjCProtocolDecl>(*DI) &&
705 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
706 StartLoc == (*DI)->getLocStart())
712 } while (DI != DIEnd);
713 RewriteForwardProtocolDecl(DG);
718 HandleTopLevelSingleDecl(*DI);
722 // If we have a decl in the main file, see if we should rewrite it.
723 if (SM->isWrittenInMainFile(Loc))
724 return HandleDeclInMainFile(D);
727 //===----------------------------------------------------------------------===//
728 // Syntactic (non-AST) Rewriting Code
729 //===----------------------------------------------------------------------===//
731 void RewriteObjC::RewriteInclude() {
732 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
733 StringRef MainBuf = SM->getBufferData(MainFileID);
734 const char *MainBufStart = MainBuf.begin();
735 const char *MainBufEnd = MainBuf.end();
736 size_t ImportLen = strlen("import");
738 // Loop over the whole file, looking for includes.
739 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
740 if (*BufPtr == '#') {
741 if (++BufPtr == MainBufEnd)
743 while (*BufPtr == ' ' || *BufPtr == '\t')
744 if (++BufPtr == MainBufEnd)
746 if (!strncmp(BufPtr, "import", ImportLen)) {
747 // replace import with include
748 SourceLocation ImportLoc =
749 LocStart.getLocWithOffset(BufPtr-MainBufStart);
750 ReplaceText(ImportLoc, ImportLen, "include");
757 static std::string getIvarAccessString(ObjCIvarDecl *OID) {
758 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
761 S += ClassDecl->getIdentifier()->getName();
762 S += "_IMPL *)self)->";
767 void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
768 ObjCImplementationDecl *IMD,
769 ObjCCategoryImplDecl *CID) {
770 static bool objcGetPropertyDefined = false;
771 static bool objcSetPropertyDefined = false;
772 SourceLocation startLoc = PID->getLocStart();
773 InsertText(startLoc, "// ");
774 const char *startBuf = SM->getCharacterData(startLoc);
775 assert((*startBuf == '@') && "bogus @synthesize location");
776 const char *semiBuf = strchr(startBuf, ';');
777 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
778 SourceLocation onePastSemiLoc =
779 startLoc.getLocWithOffset(semiBuf-startBuf+1);
781 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
782 return; // FIXME: is this correct?
784 // Generate the 'getter' function.
785 ObjCPropertyDecl *PD = PID->getPropertyDecl();
786 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
790 unsigned Attributes = PD->getPropertyAttributes();
791 if (!PD->getGetterMethodDecl()->isDefined()) {
792 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
793 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
794 ObjCPropertyDecl::OBJC_PR_copy));
796 if (GenGetProperty && !objcGetPropertyDefined) {
797 objcGetPropertyDefined = true;
798 // FIXME. Is this attribute correct in all cases?
799 Getr = "\nextern \"C\" __declspec(dllimport) "
800 "id objc_getProperty(id, SEL, long, bool);\n";
802 RewriteObjCMethodDecl(OID->getContainingInterface(),
803 PD->getGetterMethodDecl(), Getr);
805 // Synthesize an explicit cast to gain access to the ivar.
806 // See objc-act.c:objc_synthesize_new_getter() for details.
807 if (GenGetProperty) {
808 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
810 const FunctionType *FPRetType = nullptr;
811 RewriteTypeIntoString(PD->getGetterMethodDecl()->getReturnType(), Getr,
815 Getr += ")"; // close the precedence "scope" for "*".
817 // Now, emit the argument types (if any).
818 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
820 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
822 std::string ParamStr =
823 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
826 if (FT->isVariadic()) {
827 if (FT->getNumParams())
836 Getr += "return (_TYPE)";
837 Getr += "objc_getProperty(self, _cmd, ";
838 RewriteIvarOffsetComputation(OID, Getr);
842 Getr += "return " + getIvarAccessString(OID);
844 InsertText(onePastSemiLoc, Getr);
847 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
850 // Generate the 'setter' function.
852 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
853 ObjCPropertyDecl::OBJC_PR_copy);
854 if (GenSetProperty && !objcSetPropertyDefined) {
855 objcSetPropertyDefined = true;
856 // FIXME. Is this attribute correct in all cases?
857 Setr = "\nextern \"C\" __declspec(dllimport) "
858 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
861 RewriteObjCMethodDecl(OID->getContainingInterface(),
862 PD->getSetterMethodDecl(), Setr);
864 // Synthesize an explicit cast to initialize the ivar.
865 // See objc-act.c:objc_synthesize_new_setter() for details.
866 if (GenSetProperty) {
867 Setr += "objc_setProperty (self, _cmd, ";
868 RewriteIvarOffsetComputation(OID, Setr);
870 Setr += PD->getName();
872 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
876 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
882 Setr += getIvarAccessString(OID) + " = ";
883 Setr += PD->getName();
886 InsertText(onePastSemiLoc, Setr);
889 static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
890 std::string &typedefString) {
891 typedefString += "#ifndef _REWRITER_typedef_";
892 typedefString += ForwardDecl->getNameAsString();
893 typedefString += "\n";
894 typedefString += "#define _REWRITER_typedef_";
895 typedefString += ForwardDecl->getNameAsString();
896 typedefString += "\n";
897 typedefString += "typedef struct objc_object ";
898 typedefString += ForwardDecl->getNameAsString();
899 typedefString += ";\n#endif\n";
902 void RewriteObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
903 const std::string &typedefString) {
904 SourceLocation startLoc = ClassDecl->getLocStart();
905 const char *startBuf = SM->getCharacterData(startLoc);
906 const char *semiPtr = strchr(startBuf, ';');
907 // Replace the @class with typedefs corresponding to the classes.
908 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
911 void RewriteObjC::RewriteForwardClassDecl(DeclGroupRef D) {
912 std::string typedefString;
913 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
914 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
915 if (I == D.begin()) {
916 // Translate to typedef's that forward reference structs with the same name
917 // as the class. As a convenience, we include the original declaration
919 typedefString += "// @class ";
920 typedefString += ForwardDecl->getNameAsString();
921 typedefString += ";\n";
923 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
925 DeclGroupRef::iterator I = D.begin();
926 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
929 void RewriteObjC::RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &D) {
930 std::string typedefString;
931 for (unsigned i = 0; i < D.size(); i++) {
932 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
934 typedefString += "// @class ";
935 typedefString += ForwardDecl->getNameAsString();
936 typedefString += ";\n";
938 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
940 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
943 void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
944 // When method is a synthesized one, such as a getter/setter there is
945 // nothing to rewrite.
946 if (Method->isImplicit())
948 SourceLocation LocStart = Method->getLocStart();
949 SourceLocation LocEnd = Method->getLocEnd();
951 if (SM->getExpansionLineNumber(LocEnd) >
952 SM->getExpansionLineNumber(LocStart)) {
953 InsertText(LocStart, "#if 0\n");
954 ReplaceText(LocEnd, 1, ";\n#endif\n");
956 InsertText(LocStart, "// ");
960 void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
961 SourceLocation Loc = prop->getAtLoc();
963 ReplaceText(Loc, 0, "// ");
964 // FIXME: handle properties that are declared across multiple lines.
967 void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
968 SourceLocation LocStart = CatDecl->getLocStart();
970 // FIXME: handle category headers that are declared across multiple lines.
971 ReplaceText(LocStart, 0, "// ");
973 for (auto *I : CatDecl->instance_properties())
975 for (auto *I : CatDecl->instance_methods())
976 RewriteMethodDeclaration(I);
977 for (auto *I : CatDecl->class_methods())
978 RewriteMethodDeclaration(I);
980 // Lastly, comment out the @end.
981 ReplaceText(CatDecl->getAtEndRange().getBegin(),
982 strlen("@end"), "/* @end */");
985 void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
986 SourceLocation LocStart = PDecl->getLocStart();
987 assert(PDecl->isThisDeclarationADefinition());
989 // FIXME: handle protocol headers that are declared across multiple lines.
990 ReplaceText(LocStart, 0, "// ");
992 for (auto *I : PDecl->instance_methods())
993 RewriteMethodDeclaration(I);
994 for (auto *I : PDecl->class_methods())
995 RewriteMethodDeclaration(I);
996 for (auto *I : PDecl->instance_properties())
999 // Lastly, comment out the @end.
1000 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1001 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
1003 // Must comment out @optional/@required
1004 const char *startBuf = SM->getCharacterData(LocStart);
1005 const char *endBuf = SM->getCharacterData(LocEnd);
1006 for (const char *p = startBuf; p < endBuf; p++) {
1007 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1008 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1009 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1012 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1013 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1014 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1020 void RewriteObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1021 SourceLocation LocStart = (*D.begin())->getLocStart();
1022 if (LocStart.isInvalid())
1023 llvm_unreachable("Invalid SourceLocation");
1024 // FIXME: handle forward protocol that are declared across multiple lines.
1025 ReplaceText(LocStart, 0, "// ");
1029 RewriteObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
1030 SourceLocation LocStart = DG[0]->getLocStart();
1031 if (LocStart.isInvalid())
1032 llvm_unreachable("Invalid SourceLocation");
1033 // FIXME: handle forward protocol that are declared across multiple lines.
1034 ReplaceText(LocStart, 0, "// ");
1037 void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1038 const FunctionType *&FPRetType) {
1039 if (T->isObjCQualifiedIdType())
1041 else if (T->isFunctionPointerType() ||
1042 T->isBlockPointerType()) {
1043 // needs special handling, since pointer-to-functions have special
1044 // syntax (where a decaration models use).
1045 QualType retType = T;
1047 if (const PointerType* PT = retType->getAs<PointerType>())
1048 PointeeTy = PT->getPointeeType();
1049 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1050 PointeeTy = BPT->getPointeeType();
1051 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1053 FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
1057 ResultStr += T.getAsString(Context->getPrintingPolicy());
1060 void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1061 ObjCMethodDecl *OMD,
1062 std::string &ResultStr) {
1063 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1064 const FunctionType *FPRetType = nullptr;
1065 ResultStr += "\nstatic ";
1066 RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
1069 // Unique method name
1070 std::string NameStr;
1072 if (OMD->isInstanceMethod())
1077 NameStr += IDecl->getNameAsString();
1080 if (ObjCCategoryImplDecl *CID =
1081 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1082 NameStr += CID->getNameAsString();
1085 // Append selector names, replacing ':' with '_'
1087 std::string selString = OMD->getSelector().getAsString();
1088 int len = selString.size();
1089 for (int i = 0; i < len; i++)
1090 if (selString[i] == ':')
1092 NameStr += selString;
1094 // Remember this name for metadata emission
1095 MethodInternalNames[OMD] = NameStr;
1096 ResultStr += NameStr;
1098 // Rewrite arguments
1101 // invisible arguments
1102 if (OMD->isInstanceMethod()) {
1103 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1104 selfTy = Context->getPointerType(selfTy);
1105 if (!LangOpts.MicrosoftExt) {
1106 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1107 ResultStr += "struct ";
1109 // When rewriting for Microsoft, explicitly omit the structure name.
1110 ResultStr += IDecl->getNameAsString();
1114 ResultStr += Context->getObjCClassType().getAsString(
1115 Context->getPrintingPolicy());
1117 ResultStr += " self, ";
1118 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1119 ResultStr += " _cmd";
1121 // Method arguments.
1122 for (const auto *PDecl : OMD->parameters()) {
1124 if (PDecl->getType()->isObjCQualifiedIdType()) {
1126 ResultStr += PDecl->getNameAsString();
1128 std::string Name = PDecl->getNameAsString();
1129 QualType QT = PDecl->getType();
1130 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1131 (void)convertBlockPointerToFunctionPointer(QT);
1132 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
1136 if (OMD->isVariadic())
1137 ResultStr += ", ...";
1141 ResultStr += ")"; // close the precedence "scope" for "*".
1143 // Now, emit the argument types (if any).
1144 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1146 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1147 if (i) ResultStr += ", ";
1148 std::string ParamStr =
1149 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
1150 ResultStr += ParamStr;
1152 if (FT->isVariadic()) {
1153 if (FT->getNumParams())
1164 void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
1165 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1166 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1168 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
1170 for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) {
1171 std::string ResultStr;
1172 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1173 SourceLocation LocStart = OMD->getLocStart();
1174 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1176 const char *startBuf = SM->getCharacterData(LocStart);
1177 const char *endBuf = SM->getCharacterData(LocEnd);
1178 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1181 for (auto *OMD : IMD ? IMD->class_methods() : CID->class_methods()) {
1182 std::string ResultStr;
1183 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1184 SourceLocation LocStart = OMD->getLocStart();
1185 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1187 const char *startBuf = SM->getCharacterData(LocStart);
1188 const char *endBuf = SM->getCharacterData(LocEnd);
1189 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1191 for (auto *I : IMD ? IMD->property_impls() : CID->property_impls())
1192 RewritePropertyImplDecl(I, IMD, CID);
1194 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1197 void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
1198 std::string ResultStr;
1199 if (!ObjCForwardDecls.count(ClassDecl->getCanonicalDecl())) {
1200 // we haven't seen a forward decl - generate a typedef.
1201 ResultStr = "#ifndef _REWRITER_typedef_";
1202 ResultStr += ClassDecl->getNameAsString();
1204 ResultStr += "#define _REWRITER_typedef_";
1205 ResultStr += ClassDecl->getNameAsString();
1207 ResultStr += "typedef struct objc_object ";
1208 ResultStr += ClassDecl->getNameAsString();
1209 ResultStr += ";\n#endif\n";
1210 // Mark this typedef as having been generated.
1211 ObjCForwardDecls.insert(ClassDecl->getCanonicalDecl());
1213 RewriteObjCInternalStruct(ClassDecl, ResultStr);
1215 for (auto *I : ClassDecl->instance_properties())
1217 for (auto *I : ClassDecl->instance_methods())
1218 RewriteMethodDeclaration(I);
1219 for (auto *I : ClassDecl->class_methods())
1220 RewriteMethodDeclaration(I);
1222 // Lastly, comment out the @end.
1223 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1227 Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1228 SourceRange OldRange = PseudoOp->getSourceRange();
1230 // We just magically know some things about the structure of this
1232 ObjCMessageExpr *OldMsg =
1233 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1234 PseudoOp->getNumSemanticExprs() - 1));
1236 // Because the rewriter doesn't allow us to rewrite rewritten code,
1237 // we need to suppress rewriting the sub-statements.
1240 DisableReplaceStmtScope S(*this);
1242 // Rebuild the base expression if we have one.
1244 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1245 Base = OldMsg->getInstanceReceiver();
1246 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1247 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1251 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1252 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1253 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1256 // TODO: avoid this copy.
1257 SmallVector<SourceLocation, 1> SelLocs;
1258 OldMsg->getSelectorLocs(SelLocs);
1260 ObjCMessageExpr *NewMsg = nullptr;
1261 switch (OldMsg->getReceiverKind()) {
1262 case ObjCMessageExpr::Class:
1263 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1264 OldMsg->getValueKind(),
1265 OldMsg->getLeftLoc(),
1266 OldMsg->getClassReceiverTypeInfo(),
1267 OldMsg->getSelector(),
1269 OldMsg->getMethodDecl(),
1271 OldMsg->getRightLoc(),
1272 OldMsg->isImplicit());
1275 case ObjCMessageExpr::Instance:
1276 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1277 OldMsg->getValueKind(),
1278 OldMsg->getLeftLoc(),
1280 OldMsg->getSelector(),
1282 OldMsg->getMethodDecl(),
1284 OldMsg->getRightLoc(),
1285 OldMsg->isImplicit());
1288 case ObjCMessageExpr::SuperClass:
1289 case ObjCMessageExpr::SuperInstance:
1290 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1291 OldMsg->getValueKind(),
1292 OldMsg->getLeftLoc(),
1293 OldMsg->getSuperLoc(),
1294 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1295 OldMsg->getSuperType(),
1296 OldMsg->getSelector(),
1298 OldMsg->getMethodDecl(),
1300 OldMsg->getRightLoc(),
1301 OldMsg->isImplicit());
1305 Stmt *Replacement = SynthMessageExpr(NewMsg);
1306 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1310 Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1311 SourceRange OldRange = PseudoOp->getSourceRange();
1313 // We just magically know some things about the structure of this
1315 ObjCMessageExpr *OldMsg =
1316 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1318 // Because the rewriter doesn't allow us to rewrite rewritten code,
1319 // we need to suppress rewriting the sub-statements.
1320 Expr *Base = nullptr;
1322 DisableReplaceStmtScope S(*this);
1324 // Rebuild the base expression if we have one.
1325 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1326 Base = OldMsg->getInstanceReceiver();
1327 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1328 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1332 // Intentionally empty.
1333 SmallVector<SourceLocation, 1> SelLocs;
1334 SmallVector<Expr*, 1> Args;
1336 ObjCMessageExpr *NewMsg = nullptr;
1337 switch (OldMsg->getReceiverKind()) {
1338 case ObjCMessageExpr::Class:
1339 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1340 OldMsg->getValueKind(),
1341 OldMsg->getLeftLoc(),
1342 OldMsg->getClassReceiverTypeInfo(),
1343 OldMsg->getSelector(),
1345 OldMsg->getMethodDecl(),
1347 OldMsg->getRightLoc(),
1348 OldMsg->isImplicit());
1351 case ObjCMessageExpr::Instance:
1352 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1353 OldMsg->getValueKind(),
1354 OldMsg->getLeftLoc(),
1356 OldMsg->getSelector(),
1358 OldMsg->getMethodDecl(),
1360 OldMsg->getRightLoc(),
1361 OldMsg->isImplicit());
1364 case ObjCMessageExpr::SuperClass:
1365 case ObjCMessageExpr::SuperInstance:
1366 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1367 OldMsg->getValueKind(),
1368 OldMsg->getLeftLoc(),
1369 OldMsg->getSuperLoc(),
1370 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1371 OldMsg->getSuperType(),
1372 OldMsg->getSelector(),
1374 OldMsg->getMethodDecl(),
1376 OldMsg->getRightLoc(),
1377 OldMsg->isImplicit());
1381 Stmt *Replacement = SynthMessageExpr(NewMsg);
1382 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1386 /// SynthCountByEnumWithState - To print:
1387 /// ((unsigned int (*)
1388 /// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1389 /// (void *)objc_msgSend)((id)l_collection,
1390 /// sel_registerName(
1391 /// "countByEnumeratingWithState:objects:count:"),
1393 /// (id *)__rw_items, (unsigned int)16)
1395 void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
1396 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1397 "id *, unsigned int))(void *)objc_msgSend)";
1399 buf += "((id)l_collection,\n\t\t";
1400 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1402 buf += "&enumState, "
1403 "(id *)__rw_items, (unsigned int)16)";
1406 /// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1407 /// statement to exit to its outer synthesized loop.
1409 Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
1410 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1412 // replace break with goto __break_label
1415 SourceLocation startLoc = S->getLocStart();
1416 buf = "goto __break_label_";
1417 buf += utostr(ObjCBcLabelNo.back());
1418 ReplaceText(startLoc, strlen("break"), buf);
1423 /// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1424 /// statement to continue with its inner synthesized loop.
1426 Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
1427 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1429 // replace continue with goto __continue_label
1432 SourceLocation startLoc = S->getLocStart();
1433 buf = "goto __continue_label_";
1434 buf += utostr(ObjCBcLabelNo.back());
1435 ReplaceText(startLoc, strlen("continue"), buf);
1440 /// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1442 /// for ( type elem in collection) { stmts; }
1447 /// struct __objcFastEnumerationState enumState = { 0 };
1448 /// id __rw_items[16];
1449 /// id l_collection = (id)collection;
1450 /// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1451 /// objects:__rw_items count:16];
1453 /// unsigned long startMutations = *enumState.mutationsPtr;
1455 /// unsigned long counter = 0;
1457 /// if (startMutations != *enumState.mutationsPtr)
1458 /// objc_enumerationMutation(l_collection);
1459 /// elem = (type)enumState.itemsPtr[counter++];
1461 /// __continue_label: ;
1462 /// } while (counter < limit);
1463 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1464 /// objects:__rw_items count:16]);
1466 /// __break_label: ;
1472 Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1473 SourceLocation OrigEnd) {
1474 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1475 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1476 "ObjCForCollectionStmt Statement stack mismatch");
1477 assert(!ObjCBcLabelNo.empty() &&
1478 "ObjCForCollectionStmt - Label No stack empty");
1480 SourceLocation startLoc = S->getLocStart();
1481 const char *startBuf = SM->getCharacterData(startLoc);
1482 StringRef elementName;
1483 std::string elementTypeAsString;
1486 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1488 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1489 QualType ElementType = cast<ValueDecl>(D)->getType();
1490 if (ElementType->isObjCQualifiedIdType() ||
1491 ElementType->isObjCQualifiedInterfaceType())
1492 // Simply use 'id' for all qualified types.
1493 elementTypeAsString = "id";
1495 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1496 buf += elementTypeAsString;
1498 elementName = D->getName();
1503 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1504 elementName = DR->getDecl()->getName();
1505 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1506 if (VD->getType()->isObjCQualifiedIdType() ||
1507 VD->getType()->isObjCQualifiedInterfaceType())
1508 // Simply use 'id' for all qualified types.
1509 elementTypeAsString = "id";
1511 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1514 // struct __objcFastEnumerationState enumState = { 0 };
1515 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1516 // id __rw_items[16];
1517 buf += "id __rw_items[16];\n\t";
1518 // id l_collection = (id)
1519 buf += "id l_collection = (id)";
1520 // Find start location of 'collection' the hard way!
1521 const char *startCollectionBuf = startBuf;
1522 startCollectionBuf += 3; // skip 'for'
1523 startCollectionBuf = strchr(startCollectionBuf, '(');
1524 startCollectionBuf++; // skip '('
1525 // find 'in' and skip it.
1526 while (*startCollectionBuf != ' ' ||
1527 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1528 (*(startCollectionBuf+3) != ' ' &&
1529 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1530 startCollectionBuf++;
1531 startCollectionBuf += 3;
1533 // Replace: "for (type element in" with string constructed thus far.
1534 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1535 // Replace ')' in for '(' type elem in collection ')' with ';'
1536 SourceLocation rightParenLoc = S->getRParenLoc();
1537 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1538 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1541 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1542 // objects:__rw_items count:16];
1543 // which is synthesized into:
1544 // unsigned int limit =
1545 // ((unsigned int (*)
1546 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1547 // (void *)objc_msgSend)((id)l_collection,
1548 // sel_registerName(
1549 // "countByEnumeratingWithState:objects:count:"),
1550 // (struct __objcFastEnumerationState *)&state,
1551 // (id *)__rw_items, (unsigned int)16);
1552 buf += "unsigned long limit =\n\t\t";
1553 SynthCountByEnumWithState(buf);
1556 /// unsigned long startMutations = *enumState.mutationsPtr;
1558 /// unsigned long counter = 0;
1560 /// if (startMutations != *enumState.mutationsPtr)
1561 /// objc_enumerationMutation(l_collection);
1562 /// elem = (type)enumState.itemsPtr[counter++];
1563 buf += "if (limit) {\n\t";
1564 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1565 buf += "do {\n\t\t";
1566 buf += "unsigned long counter = 0;\n\t\t";
1567 buf += "do {\n\t\t\t";
1568 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1569 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1572 buf += elementTypeAsString;
1573 buf += ")enumState.itemsPtr[counter++];";
1574 // Replace ')' in for '(' type elem in collection ')' with all of these.
1575 ReplaceText(lparenLoc, 1, buf);
1577 /// __continue_label: ;
1578 /// } while (counter < limit);
1579 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1580 /// objects:__rw_items count:16]);
1582 /// __break_label: ;
1589 buf += "__continue_label_";
1590 buf += utostr(ObjCBcLabelNo.back());
1593 buf += "} while (counter < limit);\n\t";
1594 buf += "} while (limit = ";
1595 SynthCountByEnumWithState(buf);
1599 buf += elementTypeAsString;
1601 buf += "__break_label_";
1602 buf += utostr(ObjCBcLabelNo.back());
1605 buf += "else\n\t\t";
1608 buf += elementTypeAsString;
1612 // Insert all these *after* the statement body.
1613 // FIXME: If this should support Obj-C++, support CXXTryStmt
1614 if (isa<CompoundStmt>(S->getBody())) {
1615 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1616 InsertText(endBodyLoc, buf);
1618 /* Need to treat single statements specially. For example:
1620 * for (A *a in b) if (stuff()) break;
1621 * for (A *a in b) xxxyy;
1623 * The following code simply scans ahead to the semi to find the actual end.
1625 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1626 const char *semiBuf = strchr(stmtBuf, ';');
1627 assert(semiBuf && "Can't find ';'");
1628 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1629 InsertText(endBodyLoc, buf);
1632 ObjCBcLabelNo.pop_back();
1636 /// RewriteObjCSynchronizedStmt -
1637 /// This routine rewrites @synchronized(expr) stmt;
1639 /// objc_sync_enter(expr);
1640 /// @try stmt @finally { objc_sync_exit(expr); }
1642 Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1643 // Get the start location and compute the semi location.
1644 SourceLocation startLoc = S->getLocStart();
1645 const char *startBuf = SM->getCharacterData(startLoc);
1647 assert((*startBuf == '@') && "bogus @synchronized location");
1650 buf = "objc_sync_enter((id)";
1651 const char *lparenBuf = startBuf;
1652 while (*lparenBuf != '(') lparenBuf++;
1653 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
1654 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1655 // the sync expression is typically a message expression that's already
1656 // been rewritten! (which implies the SourceLocation's are invalid).
1657 SourceLocation endLoc = S->getSynchBody()->getLocStart();
1658 const char *endBuf = SM->getCharacterData(endLoc);
1659 while (*endBuf != ')') endBuf--;
1660 SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
1662 // declare a new scope with two variables, _stack and _rethrow.
1663 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1664 buf += "int buf[18/*32-bit i386*/];\n";
1665 buf += "char *pointers[4];} _stack;\n";
1666 buf += "id volatile _rethrow = 0;\n";
1667 buf += "objc_exception_try_enter(&_stack);\n";
1668 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
1669 ReplaceText(rparenLoc, 1, buf);
1670 startLoc = S->getSynchBody()->getLocEnd();
1671 startBuf = SM->getCharacterData(startLoc);
1673 assert((*startBuf == '}') && "bogus @synchronized block");
1674 SourceLocation lastCurlyLoc = startLoc;
1675 buf = "}\nelse {\n";
1676 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1678 buf += "{ /* implicit finally clause */\n";
1679 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1681 std::string syncBuf;
1682 syncBuf += " objc_sync_exit(";
1684 Expr *syncExpr = S->getSynchExpr();
1685 CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1687 syncExpr->getType()->isBlockPointerType()
1688 ? CK_BlockPointerToObjCPointerCast
1689 : CK_CPointerToObjCPointerCast;
1690 syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1692 std::string syncExprBufS;
1693 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
1694 assert(syncExpr != nullptr && "Expected non-null Expr");
1695 syncExpr->printPretty(syncExprBuf, nullptr, PrintingPolicy(LangOpts));
1696 syncBuf += syncExprBuf.str();
1700 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
1704 ReplaceText(lastCurlyLoc, 1, buf);
1706 bool hasReturns = false;
1707 HasReturnStmts(S->getSynchBody(), hasReturns);
1709 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1714 void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1716 // Perform a bottom up traversal of all children.
1717 for (Stmt *SubStmt : S->children())
1719 WarnAboutReturnGotoStmts(SubStmt);
1721 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1722 Diags.Report(Context->getFullLoc(S->getLocStart()),
1723 TryFinallyContainsReturnDiag);
1727 void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1729 // Perform a bottom up traversal of all children.
1730 for (Stmt *SubStmt : S->children())
1732 HasReturnStmts(SubStmt, hasReturns);
1734 if (isa<ReturnStmt>(S))
1738 void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1739 // Perform a bottom up traversal of all children.
1740 for (Stmt *SubStmt : S->children())
1742 RewriteTryReturnStmts(SubStmt);
1744 if (isa<ReturnStmt>(S)) {
1745 SourceLocation startLoc = S->getLocStart();
1746 const char *startBuf = SM->getCharacterData(startLoc);
1747 const char *semiBuf = strchr(startBuf, ';');
1748 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1749 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
1752 buf = "{ objc_exception_try_exit(&_stack); return";
1754 ReplaceText(startLoc, 6, buf);
1755 InsertText(onePastSemiLoc, "}");
1759 void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1760 // Perform a bottom up traversal of all children.
1761 for (Stmt *SubStmt : S->children())
1763 RewriteSyncReturnStmts(SubStmt, syncExitBuf);
1765 if (isa<ReturnStmt>(S)) {
1766 SourceLocation startLoc = S->getLocStart();
1767 const char *startBuf = SM->getCharacterData(startLoc);
1769 const char *semiBuf = strchr(startBuf, ';');
1770 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1771 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
1774 buf = "{ objc_exception_try_exit(&_stack);";
1778 ReplaceText(startLoc, 6, buf);
1779 InsertText(onePastSemiLoc, "}");
1783 Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
1784 // Get the start location and compute the semi location.
1785 SourceLocation startLoc = S->getLocStart();
1786 const char *startBuf = SM->getCharacterData(startLoc);
1788 assert((*startBuf == '@') && "bogus @try location");
1791 // declare a new scope with two variables, _stack and _rethrow.
1792 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1793 buf += "int buf[18/*32-bit i386*/];\n";
1794 buf += "char *pointers[4];} _stack;\n";
1795 buf += "id volatile _rethrow = 0;\n";
1796 buf += "objc_exception_try_enter(&_stack);\n";
1797 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
1799 ReplaceText(startLoc, 4, buf);
1801 startLoc = S->getTryBody()->getLocEnd();
1802 startBuf = SM->getCharacterData(startLoc);
1804 assert((*startBuf == '}') && "bogus @try block");
1806 SourceLocation lastCurlyLoc = startLoc;
1807 if (S->getNumCatchStmts()) {
1808 startLoc = startLoc.getLocWithOffset(1);
1809 buf = " /* @catch begin */ else {\n";
1810 buf += " id _caught = objc_exception_extract(&_stack);\n";
1811 buf += " objc_exception_try_enter (&_stack);\n";
1812 buf += " if (_setjmp(_stack.buf))\n";
1813 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1814 buf += " else { /* @catch continue */";
1816 InsertText(startLoc, buf);
1817 } else { /* no catch list */
1818 buf = "}\nelse {\n";
1819 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1821 ReplaceText(lastCurlyLoc, 1, buf);
1823 Stmt *lastCatchBody = nullptr;
1824 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1825 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
1826 VarDecl *catchDecl = Catch->getCatchParamDecl();
1829 buf = "if ("; // we are generating code for the first catch clause
1832 startLoc = Catch->getLocStart();
1833 startBuf = SM->getCharacterData(startLoc);
1835 assert((*startBuf == '@') && "bogus @catch location");
1837 const char *lParenLoc = strchr(startBuf, '(');
1839 if (Catch->hasEllipsis()) {
1840 // Now rewrite the body...
1841 lastCatchBody = Catch->getCatchBody();
1842 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1843 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1844 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
1845 "bogus @catch paren location");
1846 assert((*bodyBuf == '{') && "bogus @catch body location");
1848 buf += "1) { id _tmp = _caught;";
1849 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
1850 } else if (catchDecl) {
1851 QualType t = catchDecl->getType();
1852 if (t == Context->getObjCIdType()) {
1854 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
1855 } else if (const ObjCObjectPointerType *Ptr =
1856 t->getAs<ObjCObjectPointerType>()) {
1857 // Should be a pointer to a class.
1858 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1860 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
1861 buf += IDecl->getNameAsString();
1862 buf += "\"), (struct objc_object *)_caught)) { ";
1863 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
1866 // Now rewrite the body...
1867 lastCatchBody = Catch->getCatchBody();
1868 SourceLocation rParenLoc = Catch->getRParenLoc();
1869 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1870 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1871 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1872 assert((*rParenBuf == ')') && "bogus @catch paren location");
1873 assert((*bodyBuf == '{') && "bogus @catch body location");
1875 // Here we replace ") {" with "= _caught;" (which initializes and
1876 // declares the @catch parameter).
1877 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
1879 llvm_unreachable("@catch rewrite bug");
1882 // Complete the catch list...
1883 if (lastCatchBody) {
1884 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
1885 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1886 "bogus @catch body location");
1888 // Insert the last (implicit) else clause *before* the right curly brace.
1889 bodyLoc = bodyLoc.getLocWithOffset(-1);
1890 buf = "} /* last catch end */\n";
1892 buf += " _rethrow = _caught;\n";
1893 buf += " objc_exception_try_exit(&_stack);\n";
1894 buf += "} } /* @catch end */\n";
1895 if (!S->getFinallyStmt())
1897 InsertText(bodyLoc, buf);
1900 lastCurlyLoc = lastCatchBody->getLocEnd();
1902 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
1903 startLoc = finalStmt->getLocStart();
1904 startBuf = SM->getCharacterData(startLoc);
1905 assert((*startBuf == '@') && "bogus @finally start");
1907 ReplaceText(startLoc, 8, "/* @finally */");
1909 Stmt *body = finalStmt->getFinallyBody();
1910 SourceLocation startLoc = body->getLocStart();
1911 SourceLocation endLoc = body->getLocEnd();
1912 assert(*SM->getCharacterData(startLoc) == '{' &&
1913 "bogus @finally body location");
1914 assert(*SM->getCharacterData(endLoc) == '}' &&
1915 "bogus @finally body location");
1917 startLoc = startLoc.getLocWithOffset(1);
1918 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
1919 endLoc = endLoc.getLocWithOffset(-1);
1920 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
1923 lastCurlyLoc = body->getLocEnd();
1925 // Now check for any return/continue/go statements within the @try.
1926 WarnAboutReturnGotoStmts(S->getTryBody());
1927 } else { /* no finally clause - make sure we synthesize an implicit one */
1928 buf = "{ /* implicit finally clause */\n";
1929 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1930 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1932 ReplaceText(lastCurlyLoc, 1, buf);
1934 // Now check for any return/continue/go statements within the @try.
1935 // The implicit finally clause won't called if the @try contains any
1937 bool hasReturns = false;
1938 HasReturnStmts(S->getTryBody(), hasReturns);
1940 RewriteTryReturnStmts(S->getTryBody());
1942 // Now emit the final closing curly brace...
1943 lastCurlyLoc = lastCurlyLoc.getLocWithOffset(1);
1944 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
1948 // This can't be done with ReplaceStmt(S, ThrowExpr), since
1949 // the throw expression is typically a message expression that's already
1950 // been rewritten! (which implies the SourceLocation's are invalid).
1951 Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
1952 // Get the start location and compute the semi location.
1953 SourceLocation startLoc = S->getLocStart();
1954 const char *startBuf = SM->getCharacterData(startLoc);
1956 assert((*startBuf == '@') && "bogus @throw location");
1959 /* void objc_exception_throw(id) __attribute__((noreturn)); */
1960 if (S->getThrowExpr())
1961 buf = "objc_exception_throw(";
1962 else // add an implicit argument
1963 buf = "objc_exception_throw(_caught";
1965 // handle "@ throw" correctly.
1966 const char *wBuf = strchr(startBuf, 'w');
1967 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1968 ReplaceText(startLoc, wBuf-startBuf+1, buf);
1970 const char *semiBuf = strchr(startBuf, ';');
1971 assert((*semiBuf == ';') && "@throw: can't find ';'");
1972 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
1973 ReplaceText(semiLoc, 1, ");");
1977 Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
1978 // Create a new string expression.
1979 std::string StrEncoding;
1980 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
1981 Expr *Replacement = getStringLiteral(StrEncoding);
1982 ReplaceStmt(Exp, Replacement);
1984 // Replace this subexpr in the parent.
1985 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1989 Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1990 if (!SelGetUidFunctionDecl)
1991 SynthSelGetUidFunctionDecl();
1992 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1993 // Create a call to sel_registerName("selName").
1994 SmallVector<Expr*, 8> SelExprs;
1995 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
1996 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1998 ReplaceStmt(Exp, SelExp);
1999 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2004 RewriteObjC::SynthesizeCallToFunctionDecl(FunctionDecl *FD,
2005 ArrayRef<Expr *> Args,
2006 SourceLocation StartLoc,
2007 SourceLocation EndLoc) {
2008 // Get the type, we will need to reference it in a couple spots.
2009 QualType msgSendType = FD->getType();
2011 // Create a reference to the objc_msgSend() declaration.
2012 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, msgSendType,
2013 VK_LValue, SourceLocation());
2015 // Now, we cast the reference to a pointer to the objc_msgSend type.
2016 QualType pToFunc = Context->getPointerType(msgSendType);
2017 ImplicitCastExpr *ICE =
2018 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2019 DRE, nullptr, VK_RValue);
2021 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2023 CallExpr *Exp = new (Context) CallExpr(*Context, ICE, Args,
2024 FT->getCallResultType(*Context),
2029 static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2030 const char *&startRef, const char *&endRef) {
2031 while (startBuf < endBuf) {
2032 if (*startBuf == '<')
2033 startRef = startBuf; // mark the start.
2034 if (*startBuf == '>') {
2035 if (startRef && *startRef == '<') {
2036 endRef = startBuf; // mark the end.
2046 static void scanToNextArgument(const char *&argRef) {
2048 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2051 else if (*argRef == '>')
2055 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2058 bool RewriteObjC::needToScanForQualifiers(QualType T) {
2059 if (T->isObjCQualifiedIdType())
2061 if (const PointerType *PT = T->getAs<PointerType>()) {
2062 if (PT->getPointeeType()->isObjCQualifiedIdType())
2065 if (T->isObjCObjectPointerType()) {
2066 T = T->getPointeeType();
2067 return T->isObjCQualifiedInterfaceType();
2069 if (T->isArrayType()) {
2070 QualType ElemTy = Context->getBaseElementType(T);
2071 return needToScanForQualifiers(ElemTy);
2076 void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2077 QualType Type = E->getType();
2078 if (needToScanForQualifiers(Type)) {
2079 SourceLocation Loc, EndLoc;
2081 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2082 Loc = ECE->getLParenLoc();
2083 EndLoc = ECE->getRParenLoc();
2085 Loc = E->getLocStart();
2086 EndLoc = E->getLocEnd();
2088 // This will defend against trying to rewrite synthesized expressions.
2089 if (Loc.isInvalid() || EndLoc.isInvalid())
2092 const char *startBuf = SM->getCharacterData(Loc);
2093 const char *endBuf = SM->getCharacterData(EndLoc);
2094 const char *startRef = nullptr, *endRef = nullptr;
2095 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2096 // Get the locations of the startRef, endRef.
2097 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2098 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2099 // Comment out the protocol references.
2100 InsertText(LessLoc, "/*");
2101 InsertText(GreaterLoc, "*/");
2106 void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2109 const FunctionProtoType *proto = nullptr;
2110 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2111 Loc = VD->getLocation();
2112 Type = VD->getType();
2114 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2115 Loc = FD->getLocation();
2116 // Check for ObjC 'id' and class types that have been adorned with protocol
2117 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2118 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2119 assert(funcType && "missing function type");
2120 proto = dyn_cast<FunctionProtoType>(funcType);
2123 Type = proto->getReturnType();
2125 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2126 Loc = FD->getLocation();
2127 Type = FD->getType();
2132 if (needToScanForQualifiers(Type)) {
2133 // Since types are unique, we need to scan the buffer.
2135 const char *endBuf = SM->getCharacterData(Loc);
2136 const char *startBuf = endBuf;
2137 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2138 startBuf--; // scan backward (from the decl location) for return type.
2139 const char *startRef = nullptr, *endRef = nullptr;
2140 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2141 // Get the locations of the startRef, endRef.
2142 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2143 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2144 // Comment out the protocol references.
2145 InsertText(LessLoc, "/*");
2146 InsertText(GreaterLoc, "*/");
2150 return; // most likely, was a variable
2151 // Now check arguments.
2152 const char *startBuf = SM->getCharacterData(Loc);
2153 const char *startFuncBuf = startBuf;
2154 for (unsigned i = 0; i < proto->getNumParams(); i++) {
2155 if (needToScanForQualifiers(proto->getParamType(i))) {
2156 // Since types are unique, we need to scan the buffer.
2158 const char *endBuf = startBuf;
2159 // scan forward (from the decl location) for argument types.
2160 scanToNextArgument(endBuf);
2161 const char *startRef = nullptr, *endRef = nullptr;
2162 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2163 // Get the locations of the startRef, endRef.
2164 SourceLocation LessLoc =
2165 Loc.getLocWithOffset(startRef-startFuncBuf);
2166 SourceLocation GreaterLoc =
2167 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2168 // Comment out the protocol references.
2169 InsertText(LessLoc, "/*");
2170 InsertText(GreaterLoc, "*/");
2172 startBuf = ++endBuf;
2175 // If the function name is derived from a macro expansion, then the
2176 // argument buffer will not follow the name. Need to speak with Chris.
2177 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2178 startBuf++; // scan forward (from the decl location) for argument types.
2184 void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2185 QualType QT = ND->getType();
2186 const Type* TypePtr = QT->getAs<Type>();
2187 if (!isa<TypeOfExprType>(TypePtr))
2189 while (isa<TypeOfExprType>(TypePtr)) {
2190 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2191 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2192 TypePtr = QT->getAs<Type>();
2194 // FIXME. This will not work for multiple declarators; as in:
2195 // __typeof__(a) b,c,d;
2196 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2197 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2198 const char *startBuf = SM->getCharacterData(DeclLoc);
2199 if (ND->getInit()) {
2200 std::string Name(ND->getNameAsString());
2201 TypeAsString += " " + Name + " = ";
2202 Expr *E = ND->getInit();
2203 SourceLocation startLoc;
2204 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2205 startLoc = ECE->getLParenLoc();
2207 startLoc = E->getLocStart();
2208 startLoc = SM->getExpansionLoc(startLoc);
2209 const char *endBuf = SM->getCharacterData(startLoc);
2210 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2213 SourceLocation X = ND->getLocEnd();
2214 X = SM->getExpansionLoc(X);
2215 const char *endBuf = SM->getCharacterData(X);
2216 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2220 // SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2221 void RewriteObjC::SynthSelGetUidFunctionDecl() {
2222 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2223 SmallVector<QualType, 16> ArgTys;
2224 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2225 QualType getFuncType =
2226 getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
2227 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2230 SelGetUidIdent, getFuncType,
2231 nullptr, SC_Extern);
2234 void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2235 // declared in <objc/objc.h>
2236 if (FD->getIdentifier() &&
2237 FD->getName() == "sel_registerName") {
2238 SelGetUidFunctionDecl = FD;
2241 RewriteObjCQualifiedInterfaceTypes(FD);
2244 void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2245 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2246 const char *argPtr = TypeString.c_str();
2247 if (!strchr(argPtr, '^')) {
2252 Str += (*argPtr == '^' ? '*' : *argPtr);
2257 // FIXME. Consolidate this routine with RewriteBlockPointerType.
2258 void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2260 QualType Type = VD->getType();
2261 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2262 const char *argPtr = TypeString.c_str();
2277 Str += VD->getNameAsString();
2287 void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2288 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2289 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2290 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2293 QualType Type = proto->getReturnType();
2294 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2296 FdStr += FD->getName();
2298 unsigned numArgs = proto->getNumParams();
2299 for (unsigned i = 0; i < numArgs; i++) {
2300 QualType ArgType = proto->getParamType(i);
2301 RewriteBlockPointerType(FdStr, ArgType);
2306 InsertText(FunLocStart, FdStr);
2307 CurFunctionDeclToDeclareForBlock = nullptr;
2310 // SynthSuperConstructorFunctionDecl - id objc_super(id obj, id super);
2311 void RewriteObjC::SynthSuperConstructorFunctionDecl() {
2312 if (SuperConstructorFunctionDecl)
2314 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2315 SmallVector<QualType, 16> ArgTys;
2316 QualType argT = Context->getObjCIdType();
2317 assert(!argT.isNull() && "Can't find 'id' type");
2318 ArgTys.push_back(argT);
2319 ArgTys.push_back(argT);
2320 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2322 SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2325 msgSendIdent, msgSendType,
2326 nullptr, SC_Extern);
2329 // SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2330 void RewriteObjC::SynthMsgSendFunctionDecl() {
2331 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2332 SmallVector<QualType, 16> ArgTys;
2333 QualType argT = Context->getObjCIdType();
2334 assert(!argT.isNull() && "Can't find 'id' type");
2335 ArgTys.push_back(argT);
2336 argT = Context->getObjCSelType();
2337 assert(!argT.isNull() && "Can't find 'SEL' type");
2338 ArgTys.push_back(argT);
2339 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2340 ArgTys, /*isVariadic=*/true);
2341 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2344 msgSendIdent, msgSendType,
2345 nullptr, SC_Extern);
2348 // SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
2349 void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
2350 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2351 SmallVector<QualType, 16> ArgTys;
2352 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2353 SourceLocation(), SourceLocation(),
2354 &Context->Idents.get("objc_super"));
2355 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2356 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2357 ArgTys.push_back(argT);
2358 argT = Context->getObjCSelType();
2359 assert(!argT.isNull() && "Can't find 'SEL' type");
2360 ArgTys.push_back(argT);
2361 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2362 ArgTys, /*isVariadic=*/true);
2363 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2366 msgSendIdent, msgSendType,
2367 nullptr, SC_Extern);
2370 // SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2371 void RewriteObjC::SynthMsgSendStretFunctionDecl() {
2372 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2373 SmallVector<QualType, 16> ArgTys;
2374 QualType argT = Context->getObjCIdType();
2375 assert(!argT.isNull() && "Can't find 'id' type");
2376 ArgTys.push_back(argT);
2377 argT = Context->getObjCSelType();
2378 assert(!argT.isNull() && "Can't find 'SEL' type");
2379 ArgTys.push_back(argT);
2380 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2381 ArgTys, /*isVariadic=*/true);
2382 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2385 msgSendIdent, msgSendType,
2386 nullptr, SC_Extern);
2389 // SynthMsgSendSuperStretFunctionDecl -
2390 // id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
2391 void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
2392 IdentifierInfo *msgSendIdent =
2393 &Context->Idents.get("objc_msgSendSuper_stret");
2394 SmallVector<QualType, 16> ArgTys;
2395 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2396 SourceLocation(), SourceLocation(),
2397 &Context->Idents.get("objc_super"));
2398 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2399 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2400 ArgTys.push_back(argT);
2401 argT = Context->getObjCSelType();
2402 assert(!argT.isNull() && "Can't find 'SEL' type");
2403 ArgTys.push_back(argT);
2404 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2405 ArgTys, /*isVariadic=*/true);
2406 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2410 msgSendType, nullptr,
2414 // SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2415 void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
2416 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2417 SmallVector<QualType, 16> ArgTys;
2418 QualType argT = Context->getObjCIdType();
2419 assert(!argT.isNull() && "Can't find 'id' type");
2420 ArgTys.push_back(argT);
2421 argT = Context->getObjCSelType();
2422 assert(!argT.isNull() && "Can't find 'SEL' type");
2423 ArgTys.push_back(argT);
2424 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2425 ArgTys, /*isVariadic=*/true);
2426 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2429 msgSendIdent, msgSendType,
2430 nullptr, SC_Extern);
2433 // SynthGetClassFunctionDecl - id objc_getClass(const char *name);
2434 void RewriteObjC::SynthGetClassFunctionDecl() {
2435 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2436 SmallVector<QualType, 16> ArgTys;
2437 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2438 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2440 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2443 getClassIdent, getClassType,
2444 nullptr, SC_Extern);
2447 // SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2448 void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2449 IdentifierInfo *getSuperClassIdent =
2450 &Context->Idents.get("class_getSuperclass");
2451 SmallVector<QualType, 16> ArgTys;
2452 ArgTys.push_back(Context->getObjCClassType());
2453 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2455 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2459 getClassType, nullptr,
2463 // SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
2464 void RewriteObjC::SynthGetMetaClassFunctionDecl() {
2465 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2466 SmallVector<QualType, 16> ArgTys;
2467 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2468 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2470 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2473 getClassIdent, getClassType,
2474 nullptr, SC_Extern);
2477 Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2478 assert(Exp != nullptr && "Expected non-null ObjCStringLiteral");
2479 QualType strType = getConstantStringStructType();
2481 std::string S = "__NSConstantStringImpl_";
2483 std::string tmpName = InFileName;
2485 for (i=0; i < tmpName.length(); i++) {
2486 char c = tmpName.at(i);
2487 // replace any non-alphanumeric characters with '_'.
2488 if (!isAlphanumeric(c))
2493 S += utostr(NumObjCStringLiterals++);
2495 Preamble += "static __NSConstantStringImpl " + S;
2496 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2497 Preamble += "0x000007c8,"; // utf8_str
2498 // The pretty printer for StringLiteral handles escape characters properly.
2499 std::string prettyBufS;
2500 llvm::raw_string_ostream prettyBuf(prettyBufS);
2501 Exp->getString()->printPretty(prettyBuf, nullptr, PrintingPolicy(LangOpts));
2502 Preamble += prettyBuf.str();
2504 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2506 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2507 SourceLocation(), &Context->Idents.get(S),
2508 strType, nullptr, SC_Static);
2509 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
2511 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2512 Context->getPointerType(DRE->getType()),
2513 VK_RValue, OK_Ordinary,
2515 // cast to NSConstantString *
2516 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2517 CK_CPointerToObjCPointerCast, Unop);
2518 ReplaceStmt(Exp, cast);
2519 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2523 // struct objc_super { struct objc_object *receiver; struct objc_class *super; };
2524 QualType RewriteObjC::getSuperStructType() {
2525 if (!SuperStructDecl) {
2526 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2527 SourceLocation(), SourceLocation(),
2528 &Context->Idents.get("objc_super"));
2529 QualType FieldTypes[2];
2531 // struct objc_object *receiver;
2532 FieldTypes[0] = Context->getObjCIdType();
2533 // struct objc_class *super;
2534 FieldTypes[1] = Context->getObjCClassType();
2537 for (unsigned i = 0; i < 2; ++i) {
2538 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2540 SourceLocation(), nullptr,
2541 FieldTypes[i], nullptr,
2542 /*BitWidth=*/nullptr,
2547 SuperStructDecl->completeDefinition();
2549 return Context->getTagDeclType(SuperStructDecl);
2552 QualType RewriteObjC::getConstantStringStructType() {
2553 if (!ConstantStringDecl) {
2554 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2555 SourceLocation(), SourceLocation(),
2556 &Context->Idents.get("__NSConstantStringImpl"));
2557 QualType FieldTypes[4];
2559 // struct objc_object *receiver;
2560 FieldTypes[0] = Context->getObjCIdType();
2562 FieldTypes[1] = Context->IntTy;
2564 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2566 FieldTypes[3] = Context->LongTy;
2569 for (unsigned i = 0; i < 4; ++i) {
2570 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2573 SourceLocation(), nullptr,
2574 FieldTypes[i], nullptr,
2575 /*BitWidth=*/nullptr,
2580 ConstantStringDecl->completeDefinition();
2582 return Context->getTagDeclType(ConstantStringDecl);
2585 CallExpr *RewriteObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
2586 QualType msgSendType,
2587 QualType returnType,
2588 SmallVectorImpl<QualType> &ArgTypes,
2589 SmallVectorImpl<Expr*> &MsgExprs,
2590 ObjCMethodDecl *Method) {
2591 // Create a reference to the objc_msgSend_stret() declaration.
2592 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
2594 VK_LValue, SourceLocation());
2595 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2596 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2597 Context->getPointerType(Context->VoidTy),
2599 // Now do the "normal" pointer to function cast.
2600 QualType castType = getSimpleFunctionType(returnType, ArgTypes,
2601 Method ? Method->isVariadic()
2603 castType = Context->getPointerType(castType);
2604 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2607 // Don't forget the parens to enforce the proper binding.
2608 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
2610 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2611 CallExpr *STCE = new (Context) CallExpr(
2612 *Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, SourceLocation());
2616 Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2617 SourceLocation StartLoc,
2618 SourceLocation EndLoc) {
2619 if (!SelGetUidFunctionDecl)
2620 SynthSelGetUidFunctionDecl();
2621 if (!MsgSendFunctionDecl)
2622 SynthMsgSendFunctionDecl();
2623 if (!MsgSendSuperFunctionDecl)
2624 SynthMsgSendSuperFunctionDecl();
2625 if (!MsgSendStretFunctionDecl)
2626 SynthMsgSendStretFunctionDecl();
2627 if (!MsgSendSuperStretFunctionDecl)
2628 SynthMsgSendSuperStretFunctionDecl();
2629 if (!MsgSendFpretFunctionDecl)
2630 SynthMsgSendFpretFunctionDecl();
2631 if (!GetClassFunctionDecl)
2632 SynthGetClassFunctionDecl();
2633 if (!GetSuperClassFunctionDecl)
2634 SynthGetSuperClassFunctionDecl();
2635 if (!GetMetaClassFunctionDecl)
2636 SynthGetMetaClassFunctionDecl();
2638 // default to objc_msgSend().
2639 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2640 // May need to use objc_msgSend_stret() as well.
2641 FunctionDecl *MsgSendStretFlavor = nullptr;
2642 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2643 QualType resultType = mDecl->getReturnType();
2644 if (resultType->isRecordType())
2645 MsgSendStretFlavor = MsgSendStretFunctionDecl;
2646 else if (resultType->isRealFloatingType())
2647 MsgSendFlavor = MsgSendFpretFunctionDecl;
2650 // Synthesize a call to objc_msgSend().
2651 SmallVector<Expr*, 8> MsgExprs;
2652 switch (Exp->getReceiverKind()) {
2653 case ObjCMessageExpr::SuperClass: {
2654 MsgSendFlavor = MsgSendSuperFunctionDecl;
2655 if (MsgSendStretFlavor)
2656 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2657 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2659 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2661 SmallVector<Expr*, 4> InitExprs;
2663 // set the receiver to self, the first argument to all methods.
2664 InitExprs.push_back(
2665 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2667 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2669 Context->getObjCIdType(),
2672 ); // set the 'receiver'.
2674 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2675 SmallVector<Expr*, 8> ClsExprs;
2676 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
2677 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2678 ClsExprs, StartLoc, EndLoc);
2679 // (Class)objc_getClass("CurrentClass")
2680 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2681 Context->getObjCClassType(),
2684 ClsExprs.push_back(ArgExpr);
2685 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
2687 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2688 // To turn off a warning, type-cast to 'id'
2689 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2690 NoTypeInfoCStyleCastExpr(Context,
2691 Context->getObjCIdType(),
2693 // struct objc_super
2694 QualType superType = getSuperStructType();
2697 if (LangOpts.MicrosoftExt) {
2698 SynthSuperConstructorFunctionDecl();
2699 // Simulate a constructor call...
2700 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
2701 false, superType, VK_LValue,
2703 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
2704 superType, VK_LValue,
2706 // The code for super is a little tricky to prevent collision with
2707 // the structure definition in the header. The rewriter has it's own
2708 // internal definition (__rw_objc_super) that is uses. This is why
2709 // we need the cast below. For example:
2710 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2712 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2713 Context->getPointerType(SuperRep->getType()),
2714 VK_RValue, OK_Ordinary,
2716 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2717 Context->getPointerType(superType),
2718 CK_BitCast, SuperRep);
2720 // (struct objc_super) { <exprs from above> }
2722 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
2724 TypeSourceInfo *superTInfo
2725 = Context->getTrivialTypeSourceInfo(superType);
2726 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2727 superType, VK_LValue,
2729 // struct objc_super *
2730 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2731 Context->getPointerType(SuperRep->getType()),
2732 VK_RValue, OK_Ordinary,
2735 MsgExprs.push_back(SuperRep);
2739 case ObjCMessageExpr::Class: {
2740 SmallVector<Expr*, 8> ClsExprs;
2741 ObjCInterfaceDecl *Class
2742 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
2743 IdentifierInfo *clsName = Class->getIdentifier();
2744 ClsExprs.push_back(getStringLiteral(clsName->getName()));
2745 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
2747 MsgExprs.push_back(Cls);
2751 case ObjCMessageExpr::SuperInstance:{
2752 MsgSendFlavor = MsgSendSuperFunctionDecl;
2753 if (MsgSendStretFlavor)
2754 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2755 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2756 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2757 SmallVector<Expr*, 4> InitExprs;
2759 InitExprs.push_back(
2760 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2762 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2764 Context->getObjCIdType(),
2765 VK_RValue, SourceLocation()))
2766 ); // set the 'receiver'.
2768 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2769 SmallVector<Expr*, 8> ClsExprs;
2770 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
2771 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
2773 // (Class)objc_getClass("CurrentClass")
2774 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2775 Context->getObjCClassType(),
2778 ClsExprs.push_back(ArgExpr);
2779 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
2782 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2783 // To turn off a warning, type-cast to 'id'
2784 InitExprs.push_back(
2785 // set 'super class', using class_getSuperclass().
2786 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2788 // struct objc_super
2789 QualType superType = getSuperStructType();
2792 if (LangOpts.MicrosoftExt) {
2793 SynthSuperConstructorFunctionDecl();
2794 // Simulate a constructor call...
2795 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
2796 false, superType, VK_LValue,
2798 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
2799 superType, VK_LValue, SourceLocation());
2800 // The code for super is a little tricky to prevent collision with
2801 // the structure definition in the header. The rewriter has it's own
2802 // internal definition (__rw_objc_super) that is uses. This is why
2803 // we need the cast below. For example:
2804 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2806 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2807 Context->getPointerType(SuperRep->getType()),
2808 VK_RValue, OK_Ordinary,
2810 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2811 Context->getPointerType(superType),
2812 CK_BitCast, SuperRep);
2814 // (struct objc_super) { <exprs from above> }
2816 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
2818 TypeSourceInfo *superTInfo
2819 = Context->getTrivialTypeSourceInfo(superType);
2820 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2821 superType, VK_RValue, ILE,
2824 MsgExprs.push_back(SuperRep);
2828 case ObjCMessageExpr::Instance: {
2829 // Remove all type-casts because it may contain objc-style types; e.g.
2831 Expr *recExpr = Exp->getInstanceReceiver();
2832 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2833 recExpr = CE->getSubExpr();
2834 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
2835 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
2836 ? CK_BlockPointerToObjCPointerCast
2837 : CK_CPointerToObjCPointerCast;
2839 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2841 MsgExprs.push_back(recExpr);
2846 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
2847 SmallVector<Expr*, 8> SelExprs;
2848 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
2849 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2850 SelExprs, StartLoc, EndLoc);
2851 MsgExprs.push_back(SelExp);
2853 // Now push any user supplied arguments.
2854 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
2855 Expr *userExpr = Exp->getArg(i);
2856 // Make all implicit casts explicit...ICE comes in handy:-)
2857 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2858 // Reuse the ICE type, it is exactly what the doctor ordered.
2859 QualType type = ICE->getType();
2860 if (needToScanForQualifiers(type))
2861 type = Context->getObjCIdType();
2862 // Make sure we convert "type (^)(...)" to "type (*)(...)".
2863 (void)convertBlockPointerToFunctionPointer(type);
2864 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2866 if (SubExpr->getType()->isIntegralType(*Context) &&
2867 type->isBooleanType()) {
2868 CK = CK_IntegralToBoolean;
2869 } else if (type->isObjCObjectPointerType()) {
2870 if (SubExpr->getType()->isBlockPointerType()) {
2871 CK = CK_BlockPointerToObjCPointerCast;
2872 } else if (SubExpr->getType()->isPointerType()) {
2873 CK = CK_CPointerToObjCPointerCast;
2881 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
2883 // Make id<P...> cast into an 'id' cast.
2884 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
2885 if (CE->getType()->isObjCQualifiedIdType()) {
2886 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
2887 userExpr = CE->getSubExpr();
2889 if (userExpr->getType()->isIntegralType(*Context)) {
2890 CK = CK_IntegralToPointer;
2891 } else if (userExpr->getType()->isBlockPointerType()) {
2892 CK = CK_BlockPointerToObjCPointerCast;
2893 } else if (userExpr->getType()->isPointerType()) {
2894 CK = CK_CPointerToObjCPointerCast;
2898 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2902 MsgExprs.push_back(userExpr);
2903 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2904 // out the argument in the original expression (since we aren't deleting
2905 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
2906 //Exp->setArg(i, 0);
2908 // Generate the funky cast.
2910 SmallVector<QualType, 8> ArgTypes;
2911 QualType returnType;
2913 // Push 'id' and 'SEL', the 2 implicit arguments.
2914 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2915 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2917 ArgTypes.push_back(Context->getObjCIdType());
2918 ArgTypes.push_back(Context->getObjCSelType());
2919 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
2920 // Push any user argument types.
2921 for (const auto *PI : OMD->parameters()) {
2922 QualType t = PI->getType()->isObjCQualifiedIdType()
2923 ? Context->getObjCIdType()
2925 // Make sure we convert "t (^)(...)" to "t (*)(...)".
2926 (void)convertBlockPointerToFunctionPointer(t);
2927 ArgTypes.push_back(t);
2929 returnType = Exp->getType();
2930 convertToUnqualifiedObjCType(returnType);
2931 (void)convertBlockPointerToFunctionPointer(returnType);
2933 returnType = Context->getObjCIdType();
2935 // Get the type, we will need to reference it in a couple spots.
2936 QualType msgSendType = MsgSendFlavor->getType();
2938 // Create a reference to the objc_msgSend() declaration.
2939 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2940 VK_LValue, SourceLocation());
2942 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2943 // If we don't do this cast, we get the following bizarre warning/note:
2944 // xx.m:13: warning: function called through a non-compatible type
2945 // xx.m:13: note: if this code is reached, the program will abort
2946 cast = NoTypeInfoCStyleCastExpr(Context,
2947 Context->getPointerType(Context->VoidTy),
2950 // Now do the "normal" pointer to function cast.
2951 // If we don't have a method decl, force a variadic cast.
2952 const ObjCMethodDecl *MD = Exp->getMethodDecl();
2954 getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
2955 castType = Context->getPointerType(castType);
2956 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2959 // Don't forget the parens to enforce the proper binding.
2960 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2962 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2963 CallExpr *CE = new (Context)
2964 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
2965 Stmt *ReplacingStmt = CE;
2966 if (MsgSendStretFlavor) {
2967 // We have the method which returns a struct/union. Must also generate
2968 // call to objc_msgSend_stret and hang both varieties on a conditional
2969 // expression which dictate which one to envoke depending on size of
2970 // method's return type.
2972 CallExpr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
2973 msgSendType, returnType,
2975 Exp->getMethodDecl());
2977 // Build sizeof(returnType)
2978 UnaryExprOrTypeTraitExpr *sizeofExpr =
2979 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
2980 Context->getTrivialTypeSourceInfo(returnType),
2981 Context->getSizeType(), SourceLocation(),
2983 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2984 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2985 // For X86 it is more complicated and some kind of target specific routine
2986 // is needed to decide what to do.
2988 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2989 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
2990 llvm::APInt(IntSize, 8),
2993 BinaryOperator *lessThanExpr =
2994 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
2995 VK_RValue, OK_Ordinary, SourceLocation(),
2997 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2998 ConditionalOperator *CondExpr =
2999 new (Context) ConditionalOperator(lessThanExpr,
3000 SourceLocation(), CE,
3001 SourceLocation(), STCE,
3002 returnType, VK_RValue, OK_Ordinary);
3003 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3006 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3007 return ReplacingStmt;
3010 Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3011 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3014 // Now do the actual rewrite.
3015 ReplaceStmt(Exp, ReplacingStmt);
3017 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3018 return ReplacingStmt;
3021 // typedef struct objc_object Protocol;
3022 QualType RewriteObjC::getProtocolType() {
3023 if (!ProtocolTypeDecl) {
3024 TypeSourceInfo *TInfo
3025 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3026 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3027 SourceLocation(), SourceLocation(),
3028 &Context->Idents.get("Protocol"),
3031 return Context->getTypeDeclType(ProtocolTypeDecl);
3034 /// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3035 /// a synthesized/forward data reference (to the protocol's metadata).
3036 /// The forward references (and metadata) are generated in
3037 /// RewriteObjC::HandleTranslationUnit().
3038 Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
3039 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3040 IdentifierInfo *ID = &Context->Idents.get(Name);
3041 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3042 SourceLocation(), ID, getProtocolType(),
3043 nullptr, SC_Extern);
3044 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3045 VK_LValue, SourceLocation());
3046 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3047 Context->getPointerType(DRE->getType()),
3048 VK_RValue, OK_Ordinary, SourceLocation());
3049 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3052 ReplaceStmt(Exp, castExpr);
3053 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3054 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3058 bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
3059 const char *endBuf) {
3060 while (startBuf < endBuf) {
3061 if (*startBuf == '#') {
3063 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3065 if (!strncmp(startBuf, "if", strlen("if")) ||
3066 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3067 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3068 !strncmp(startBuf, "define", strlen("define")) ||
3069 !strncmp(startBuf, "undef", strlen("undef")) ||
3070 !strncmp(startBuf, "else", strlen("else")) ||
3071 !strncmp(startBuf, "elif", strlen("elif")) ||
3072 !strncmp(startBuf, "endif", strlen("endif")) ||
3073 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3074 !strncmp(startBuf, "include", strlen("include")) ||
3075 !strncmp(startBuf, "import", strlen("import")) ||
3076 !strncmp(startBuf, "include_next", strlen("include_next")))
3084 /// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3085 /// an objective-c class with ivars.
3086 void RewriteObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3087 std::string &Result) {
3088 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3089 assert(CDecl->getName() != "" &&
3090 "Name missing in SynthesizeObjCInternalStruct");
3091 // Do not synthesize more than once.
3092 if (ObjCSynthesizedStructs.count(CDecl))
3094 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
3095 int NumIvars = CDecl->ivar_size();
3096 SourceLocation LocStart = CDecl->getLocStart();
3097 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
3099 const char *startBuf = SM->getCharacterData(LocStart);
3100 const char *endBuf = SM->getCharacterData(LocEnd);
3102 // If no ivars and no root or if its root, directly or indirectly,
3103 // have no ivars (thus not synthesized) then no need to synthesize this class.
3104 if ((!CDecl->isThisDeclarationADefinition() || NumIvars == 0) &&
3105 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3106 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3107 ReplaceText(LocStart, endBuf-startBuf, Result);
3111 // FIXME: This has potential of causing problem. If
3112 // SynthesizeObjCInternalStruct is ever called recursively.
3113 Result += "\nstruct ";
3114 Result += CDecl->getNameAsString();
3115 if (LangOpts.MicrosoftExt)
3119 const char *cursor = strchr(startBuf, '{');
3120 assert((cursor && endBuf)
3121 && "SynthesizeObjCInternalStruct - malformed @interface");
3122 // If the buffer contains preprocessor directives, we do more fine-grained
3123 // rewrites. This is intended to fix code that looks like (which occurs in
3124 // NSURL.h, for example):
3127 // @interface Foo : NSObject
3129 // @interface FooBar : NSObject
3136 // This clause is segregated to avoid breaking the common case.
3137 if (BufferContainsPPDirectives(startBuf, cursor)) {
3138 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
3139 CDecl->getAtStartLoc();
3140 const char *endHeader = SM->getCharacterData(L);
3141 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
3143 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
3144 // advance to the end of the referenced protocols.
3145 while (endHeader < cursor && *endHeader != '>') endHeader++;
3148 // rewrite the original header
3149 ReplaceText(LocStart, endHeader-startBuf, Result);
3151 // rewrite the original header *without* disturbing the '{'
3152 ReplaceText(LocStart, cursor-startBuf, Result);
3154 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
3155 Result = "\n struct ";
3156 Result += RCDecl->getNameAsString();
3158 Result += RCDecl->getNameAsString();
3159 Result += "_IVARS;\n";
3161 // insert the super class structure definition.
3162 SourceLocation OnePastCurly =
3163 LocStart.getLocWithOffset(cursor-startBuf+1);
3164 InsertText(OnePastCurly, Result);
3166 cursor++; // past '{'
3168 // Now comment out any visibility specifiers.
3169 while (cursor < endBuf) {
3170 if (*cursor == '@') {
3171 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
3173 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3176 // FIXME: presence of @public, etc. inside comment results in
3177 // this transformation as well, which is still correct c-code.
3178 if (!strncmp(cursor, "public", strlen("public")) ||
3179 !strncmp(cursor, "private", strlen("private")) ||
3180 !strncmp(cursor, "package", strlen("package")) ||
3181 !strncmp(cursor, "protected", strlen("protected")))
3182 InsertText(atLoc, "// ");
3184 // FIXME: If there are cases where '<' is used in ivar declaration part
3185 // of user code, then scan the ivar list and use needToScanForQualifiers
3186 // for type checking.
3187 else if (*cursor == '<') {
3188 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
3189 InsertText(atLoc, "/* ");
3190 cursor = strchr(cursor, '>');
3192 atLoc = LocStart.getLocWithOffset(cursor-startBuf);
3193 InsertText(atLoc, " */");
3194 } else if (*cursor == '^') { // rewrite block specifier.
3195 SourceLocation caretLoc = LocStart.getLocWithOffset(cursor-startBuf);
3196 ReplaceText(caretLoc, 1, "*");
3200 // Don't forget to add a ';'!!
3201 InsertText(LocEnd.getLocWithOffset(1), ";");
3202 } else { // we don't have any instance variables - insert super struct.
3203 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3204 Result += " {\n struct ";
3205 Result += RCDecl->getNameAsString();
3207 Result += RCDecl->getNameAsString();
3208 Result += "_IVARS;\n};\n";
3209 ReplaceText(LocStart, endBuf-startBuf, Result);
3211 // Mark this struct as having been generated.
3212 if (!ObjCSynthesizedStructs.insert(CDecl).second)
3213 llvm_unreachable("struct already synthesize- SynthesizeObjCInternalStruct");
3216 //===----------------------------------------------------------------------===//
3217 // Meta Data Emission
3218 //===----------------------------------------------------------------------===//
3220 /// RewriteImplementations - This routine rewrites all method implementations
3221 /// and emits meta-data.
3223 void RewriteObjC::RewriteImplementations() {
3224 int ClsDefCount = ClassImplementation.size();
3225 int CatDefCount = CategoryImplementation.size();
3227 // Rewrite implemented methods
3228 for (int i = 0; i < ClsDefCount; i++)
3229 RewriteImplementationDecl(ClassImplementation[i]);
3231 for (int i = 0; i < CatDefCount; i++)
3232 RewriteImplementationDecl(CategoryImplementation[i]);
3235 void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3236 const std::string &Name,
3237 ValueDecl *VD, bool def) {
3238 assert(BlockByRefDeclNo.count(VD) &&
3239 "RewriteByRefString: ByRef decl missing");
3241 ResultStr += "struct ";
3242 ResultStr += "__Block_byref_" + Name +
3243 "_" + utostr(BlockByRefDeclNo[VD]) ;
3246 static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3247 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3248 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3252 std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3255 const FunctionType *AFT = CE->getFunctionType();
3256 QualType RT = AFT->getReturnType();
3257 std::string StructRef = "struct " + Tag;
3258 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
3259 funcName.str() + "_" + "block_func_" + utostr(i);
3261 BlockDecl *BD = CE->getBlockDecl();
3263 if (isa<FunctionNoProtoType>(AFT)) {
3264 // No user-supplied arguments. Still need to pass in a pointer to the
3265 // block (to reference imported block decl refs).
3266 S += "(" + StructRef + " *__cself)";
3267 } else if (BD->param_empty()) {
3268 S += "(" + StructRef + " *__cself)";
3270 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
3271 assert(FT && "SynthesizeBlockFunc: No function proto");
3273 // first add the implicit argument.
3274 S += StructRef + " *__cself, ";
3275 std::string ParamStr;
3276 for (BlockDecl::param_iterator AI = BD->param_begin(),
3277 E = BD->param_end(); AI != E; ++AI) {
3278 if (AI != BD->param_begin()) S += ", ";
3279 ParamStr = (*AI)->getNameAsString();
3280 QualType QT = (*AI)->getType();
3281 (void)convertBlockPointerToFunctionPointer(QT);
3282 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
3285 if (FT->isVariadic()) {
3286 if (!BD->param_empty()) S += ", ";
3293 // Create local declarations to avoid rewriting all closure decl ref exprs.
3294 // First, emit a declaration for all "by ref" decls.
3295 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
3296 E = BlockByRefDecls.end(); I != E; ++I) {
3298 std::string Name = (*I)->getNameAsString();
3299 std::string TypeString;
3300 RewriteByRefString(TypeString, Name, (*I));
3302 Name = TypeString + Name;
3303 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
3305 // Next, emit a declaration for all "by copy" declarations.
3306 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
3307 E = BlockByCopyDecls.end(); I != E; ++I) {
3309 // Handle nested closure invocation. For example:
3311 // void (^myImportedClosure)(void);
3312 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3314 // void (^anotherClosure)(void);
3315 // anotherClosure = ^(void) {
3316 // myImportedClosure(); // import and invoke the closure
3319 if (isTopLevelBlockPointerType((*I)->getType())) {
3320 RewriteBlockPointerTypeVariable(S, (*I));
3322 RewriteBlockPointerType(S, (*I)->getType());
3324 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3327 std::string Name = (*I)->getNameAsString();
3328 QualType QT = (*I)->getType();
3329 if (HasLocalVariableExternalStorage(*I))
3330 QT = Context->getPointerType(QT);
3331 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
3332 S += Name + " = __cself->" +
3333 (*I)->getNameAsString() + "; // bound by copy\n";
3336 std::string RewrittenStr = RewrittenBlockExprs[CE];
3337 const char *cstr = RewrittenStr.c_str();
3338 while (*cstr++ != '{') ;
3344 std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3347 std::string StructRef = "struct " + Tag;
3348 std::string S = "static void __";
3351 S += "_block_copy_" + utostr(i);
3352 S += "(" + StructRef;
3353 S += "*dst, " + StructRef;
3355 for (ValueDecl *VD : ImportedBlockDecls) {
3356 S += "_Block_object_assign((void*)&dst->";
3357 S += VD->getNameAsString();
3358 S += ", (void*)src->";
3359 S += VD->getNameAsString();
3360 if (BlockByRefDeclsPtrSet.count(VD))
3361 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3362 else if (VD->getType()->isBlockPointerType())
3363 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3365 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3369 S += "\nstatic void __";
3371 S += "_block_dispose_" + utostr(i);
3372 S += "(" + StructRef;
3374 for (ValueDecl *VD : ImportedBlockDecls) {
3375 S += "_Block_object_dispose((void*)src->";
3376 S += VD->getNameAsString();
3377 if (BlockByRefDeclsPtrSet.count(VD))
3378 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3379 else if (VD->getType()->isBlockPointerType())
3380 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3382 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3388 std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3390 std::string S = "\nstruct " + Tag;
3391 std::string Constructor = " " + Tag;
3393 S += " {\n struct __block_impl impl;\n";
3394 S += " struct " + Desc;
3397 Constructor += "(void *fp, "; // Invoke function pointer.
3398 Constructor += "struct " + Desc; // Descriptor pointer.
3399 Constructor += " *desc";
3401 if (BlockDeclRefs.size()) {
3402 // Output all "by copy" declarations.
3403 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
3404 E = BlockByCopyDecls.end(); I != E; ++I) {
3406 std::string FieldName = (*I)->getNameAsString();
3407 std::string ArgName = "_" + FieldName;
3408 // Handle nested closure invocation. For example:
3410 // void (^myImportedBlock)(void);
3411 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3413 // void (^anotherBlock)(void);
3414 // anotherBlock = ^(void) {
3415 // myImportedBlock(); // import and invoke the closure
3418 if (isTopLevelBlockPointerType((*I)->getType())) {
3419 S += "struct __block_impl *";
3420 Constructor += ", void *" + ArgName;
3422 QualType QT = (*I)->getType();
3423 if (HasLocalVariableExternalStorage(*I))
3424 QT = Context->getPointerType(QT);
3425 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3426 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
3427 Constructor += ", " + ArgName;
3429 S += FieldName + ";\n";
3431 // Output all "by ref" declarations.
3432 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
3433 E = BlockByRefDecls.end(); I != E; ++I) {
3435 std::string FieldName = (*I)->getNameAsString();
3436 std::string ArgName = "_" + FieldName;
3438 std::string TypeString;
3439 RewriteByRefString(TypeString, FieldName, (*I));
3441 FieldName = TypeString + FieldName;
3442 ArgName = TypeString + ArgName;
3443 Constructor += ", " + ArgName;
3445 S += FieldName + "; // by ref\n";
3447 // Finish writing the constructor.
3448 Constructor += ", int flags=0)";
3449 // Initialize all "by copy" arguments.
3450 bool firsTime = true;
3451 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
3452 E = BlockByCopyDecls.end(); I != E; ++I) {
3453 std::string Name = (*I)->getNameAsString();
3455 Constructor += " : ";
3459 Constructor += ", ";
3460 if (isTopLevelBlockPointerType((*I)->getType()))
3461 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3463 Constructor += Name + "(_" + Name + ")";
3465 // Initialize all "by ref" arguments.
3466 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
3467 E = BlockByRefDecls.end(); I != E; ++I) {
3468 std::string Name = (*I)->getNameAsString();
3470 Constructor += " : ";
3474 Constructor += ", ";
3475 Constructor += Name + "(_" + Name + "->__forwarding)";
3478 Constructor += " {\n";
3480 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3482 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3483 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3485 Constructor += " Desc = desc;\n";
3487 // Finish writing the constructor.
3488 Constructor += ", int flags=0) {\n";
3490 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3492 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3493 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3494 Constructor += " Desc = desc;\n";
3497 Constructor += "}\n";
3503 std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
3504 std::string ImplTag, int i,
3507 std::string S = "\nstatic struct " + DescTag;
3509 S += " {\n unsigned long reserved;\n";
3510 S += " unsigned long Block_size;\n";
3512 S += " void (*copy)(struct ";
3513 S += ImplTag; S += "*, struct ";
3514 S += ImplTag; S += "*);\n";
3516 S += " void (*dispose)(struct ";
3517 S += ImplTag; S += "*);\n";
3521 S += DescTag + "_DATA = { 0, sizeof(struct ";
3524 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3525 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
3531 void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3532 StringRef FunName) {
3533 // Insert declaration for the function in which block literal is used.
3534 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
3535 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
3536 bool RewriteSC = (GlobalVarDecl &&
3538 GlobalVarDecl->getStorageClass() == SC_Static &&
3539 GlobalVarDecl->getType().getCVRQualifiers());
3541 std::string SC(" void __");
3542 SC += GlobalVarDecl->getNameAsString();
3544 InsertText(FunLocStart, SC);
3547 // Insert closures that were part of the function.
3548 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3549 CollectBlockDeclRefInfo(Blocks[i]);
3550 // Need to copy-in the inner copied-in variables not actually used in this
3552 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
3553 DeclRefExpr *Exp = InnerDeclRefs[count++];
3554 ValueDecl *VD = Exp->getDecl();
3555 BlockDeclRefs.push_back(Exp);
3556 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
3557 BlockByCopyDeclsPtrSet.insert(VD);
3558 BlockByCopyDecls.push_back(VD);
3560 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
3561 BlockByRefDeclsPtrSet.insert(VD);
3562 BlockByRefDecls.push_back(VD);
3564 // imported objects in the inner blocks not used in the outer
3565 // blocks must be copied/disposed in the outer block as well.
3566 if (VD->hasAttr<BlocksAttr>() ||
3567 VD->getType()->isObjCObjectPointerType() ||
3568 VD->getType()->isBlockPointerType())
3569 ImportedBlockDecls.insert(VD);
3572 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3573 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
3575 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
3577 InsertText(FunLocStart, CI);
3579 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
3581 InsertText(FunLocStart, CF);
3583 if (ImportedBlockDecls.size()) {
3584 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
3585 InsertText(FunLocStart, HF);
3587 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3588 ImportedBlockDecls.size() > 0);
3589 InsertText(FunLocStart, BD);
3591 BlockDeclRefs.clear();
3592 BlockByRefDecls.clear();
3593 BlockByRefDeclsPtrSet.clear();
3594 BlockByCopyDecls.clear();
3595 BlockByCopyDeclsPtrSet.clear();
3596 ImportedBlockDecls.clear();
3599 // Must insert any 'const/volatile/static here. Since it has been
3600 // removed as result of rewriting of block literals.
3602 if (GlobalVarDecl->getStorageClass() == SC_Static)
3604 if (GlobalVarDecl->getType().isConstQualified())
3606 if (GlobalVarDecl->getType().isVolatileQualified())
3608 if (GlobalVarDecl->getType().isRestrictQualified())
3610 InsertText(FunLocStart, SC);
3614 InnerDeclRefsCount.clear();
3615 InnerDeclRefs.clear();
3616 RewrittenBlockExprs.clear();
3619 void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3620 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
3621 StringRef FuncName = FD->getName();
3623 SynthesizeBlockLiterals(FunLocStart, FuncName);
3626 static void BuildUniqueMethodName(std::string &Name,
3627 ObjCMethodDecl *MD) {
3628 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3629 Name = IFace->getName();
3630 Name += "__" + MD->getSelector().getAsString();
3631 // Convert colons to underscores.
3632 std::string::size_type loc = 0;
3633 while ((loc = Name.find(':', loc)) != std::string::npos)
3634 Name.replace(loc, 1, "_");
3637 void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
3638 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3639 //SourceLocation FunLocStart = MD->getLocStart();
3640 SourceLocation FunLocStart = MD->getLocStart();
3641 std::string FuncName;
3642 BuildUniqueMethodName(FuncName, MD);
3643 SynthesizeBlockLiterals(FunLocStart, FuncName);
3646 void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3647 for (Stmt *SubStmt : S->children())
3649 if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt))
3650 GetBlockDeclRefExprs(CBE->getBody());
3652 GetBlockDeclRefExprs(SubStmt);
3654 // Handle specific things.
3655 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
3656 if (DRE->refersToEnclosingVariableOrCapture() ||
3657 HasLocalVariableExternalStorage(DRE->getDecl()))
3658 // FIXME: Handle enums.
3659 BlockDeclRefs.push_back(DRE);
3662 void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
3663 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
3664 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts) {
3665 for (Stmt *SubStmt : S->children())
3667 if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt)) {
3668 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
3669 GetInnerBlockDeclRefExprs(CBE->getBody(),
3674 GetInnerBlockDeclRefExprs(SubStmt, InnerBlockDeclRefs, InnerContexts);
3676 // Handle specific things.
3677 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3678 if (DRE->refersToEnclosingVariableOrCapture() ||
3679 HasLocalVariableExternalStorage(DRE->getDecl())) {
3680 if (!InnerContexts.count(DRE->getDecl()->getDeclContext()))
3681 InnerBlockDeclRefs.push_back(DRE);
3682 if (VarDecl *Var = cast<VarDecl>(DRE->getDecl()))
3683 if (Var->isFunctionOrMethodVarDecl())
3684 ImportedLocalExternalDecls.insert(Var);
3689 /// convertFunctionTypeOfBlocks - This routine converts a function type
3690 /// whose result type may be a block pointer or whose argument type(s)
3691 /// might be block pointers to an equivalent function type replacing
3692 /// all block pointers to function pointers.
3693 QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3694 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3695 // FTP will be null for closures that don't take arguments.
3696 // Generate a funky cast.
3697 SmallVector<QualType, 8> ArgTypes;
3698 QualType Res = FT->getReturnType();
3699 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
3702 for (auto &I : FTP->param_types()) {
3704 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3705 if (convertBlockPointerToFunctionPointer(t))
3706 HasBlockType = true;
3707 ArgTypes.push_back(t);
3711 // FIXME. Does this work if block takes no argument but has a return type
3712 // which is of block type?
3714 FuncType = getSimpleFunctionType(Res, ArgTypes);
3715 else FuncType = QualType(FT, 0);
3719 Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
3720 // Navigate to relevant type information.
3721 const BlockPointerType *CPT = nullptr;
3723 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
3724 CPT = DRE->getType()->getAs<BlockPointerType>();
3725 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
3726 CPT = MExpr->getType()->getAs<BlockPointerType>();
3728 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3729 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3731 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3732 CPT = IEXPR->getType()->getAs<BlockPointerType>();
3733 else if (const ConditionalOperator *CEXPR =
3734 dyn_cast<ConditionalOperator>(BlockExp)) {
3735 Expr *LHSExp = CEXPR->getLHS();
3736 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3737 Expr *RHSExp = CEXPR->getRHS();
3738 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3739 Expr *CONDExp = CEXPR->getCond();
3740 ConditionalOperator *CondExpr =
3741 new (Context) ConditionalOperator(CONDExp,
3742 SourceLocation(), cast<Expr>(LHSStmt),
3743 SourceLocation(), cast<Expr>(RHSStmt),
3744 Exp->getType(), VK_RValue, OK_Ordinary);
3746 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3747 CPT = IRE->getType()->getAs<BlockPointerType>();
3748 } else if (const PseudoObjectExpr *POE
3749 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3750 CPT = POE->getType()->castAs<BlockPointerType>();
3752 assert(false && "RewriteBlockClass: Bad type");
3754 assert(CPT && "RewriteBlockClass: Bad type");
3755 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
3756 assert(FT && "RewriteBlockClass: Bad type");
3757 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3758 // FTP will be null for closures that don't take arguments.
3760 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3761 SourceLocation(), SourceLocation(),
3762 &Context->Idents.get("__block_impl"));
3763 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
3765 // Generate a funky cast.
3766 SmallVector<QualType, 8> ArgTypes;
3768 // Push the block argument type.
3769 ArgTypes.push_back(PtrBlock);
3771 for (auto &I : FTP->param_types()) {
3773 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3774 if (!convertBlockPointerToFunctionPointer(t))
3775 convertToUnqualifiedObjCType(t);
3776 ArgTypes.push_back(t);
3779 // Now do the pointer to function cast.
3780 QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
3782 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
3784 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
3786 const_cast<Expr*>(BlockExp));
3787 // Don't forget the parens to enforce the proper binding.
3788 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3792 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
3794 &Context->Idents.get("FuncPtr"),
3795 Context->VoidPtrTy, nullptr,
3796 /*BitWidth=*/nullptr, /*Mutable=*/true,
3799 new (Context) MemberExpr(PE, true, SourceLocation(), FD, SourceLocation(),
3800 FD->getType(), VK_LValue, OK_Ordinary);
3802 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
3804 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3806 SmallVector<Expr*, 8> BlkExprs;
3807 // Add the implicit argument.
3808 BlkExprs.push_back(BlkCast);
3809 // Add the user arguments.
3810 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3811 E = Exp->arg_end(); I != E; ++I) {
3812 BlkExprs.push_back(*I);
3814 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
3815 Exp->getType(), VK_RValue,
3820 // We need to return the rewritten expression to handle cases where the
3821 // BlockDeclRefExpr is embedded in another expression being rewritten.
3828 // void (^myblock)() = ^() {
3829 // [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
3833 Stmt *RewriteObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
3834 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
3835 // for each DeclRefExp where BYREFVAR is name of the variable.
3836 ValueDecl *VD = DeclRefExp->getDecl();
3837 bool isArrow = DeclRefExp->refersToEnclosingVariableOrCapture() ||
3838 HasLocalVariableExternalStorage(DeclRefExp->getDecl());
3840 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
3842 &Context->Idents.get("__forwarding"),
3843 Context->VoidPtrTy, nullptr,
3844 /*BitWidth=*/nullptr, /*Mutable=*/true,
3846 MemberExpr *ME = new (Context)
3847 MemberExpr(DeclRefExp, isArrow, SourceLocation(), FD, SourceLocation(),
3848 FD->getType(), VK_LValue, OK_Ordinary);
3850 StringRef Name = VD->getName();
3851 FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(),
3852 &Context->Idents.get(Name),
3853 Context->VoidPtrTy, nullptr,
3854 /*BitWidth=*/nullptr, /*Mutable=*/true,
3857 new (Context) MemberExpr(ME, true, SourceLocation(), FD, SourceLocation(),
3858 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
3860 // Need parens to enforce precedence.
3861 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
3862 DeclRefExp->getExprLoc(),
3864 ReplaceStmt(DeclRefExp, PE);
3868 // Rewrites the imported local variable V with external storage
3869 // (static, extern, etc.) as *V
3871 Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
3872 ValueDecl *VD = DRE->getDecl();
3873 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3874 if (!ImportedLocalExternalDecls.count(Var))
3876 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
3877 VK_LValue, OK_Ordinary,
3878 DRE->getLocation());
3879 // Need parens to enforce precedence.
3880 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3882 ReplaceStmt(DRE, PE);
3886 void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3887 SourceLocation LocStart = CE->getLParenLoc();
3888 SourceLocation LocEnd = CE->getRParenLoc();
3890 // Need to avoid trying to rewrite synthesized casts.
3891 if (LocStart.isInvalid())
3893 // Need to avoid trying to rewrite casts contained in macros.
3894 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3897 const char *startBuf = SM->getCharacterData(LocStart);
3898 const char *endBuf = SM->getCharacterData(LocEnd);
3899 QualType QT = CE->getType();
3900 const Type* TypePtr = QT->getAs<Type>();
3901 if (isa<TypeOfExprType>(TypePtr)) {
3902 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
3903 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
3904 std::string TypeAsString = "(";
3905 RewriteBlockPointerType(TypeAsString, QT);
3906 TypeAsString += ")";
3907 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
3910 // advance the location to startArgList.
3911 const char *argPtr = startBuf;
3913 while (*argPtr++ && (argPtr < endBuf)) {
3916 // Replace the '^' with '*'.
3917 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
3918 ReplaceText(LocStart, 1, "*");
3924 void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3925 SourceLocation DeclLoc = FD->getLocation();
3926 unsigned parenCount = 0;
3928 // We have 1 or more arguments that have closure pointers.
3929 const char *startBuf = SM->getCharacterData(DeclLoc);
3930 const char *startArgList = strchr(startBuf, '(');
3932 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3935 // advance the location to startArgList.
3936 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
3937 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3939 const char *argPtr = startArgList;
3941 while (*argPtr++ && parenCount) {
3944 // Replace the '^' with '*'.
3945 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
3946 ReplaceText(DeclLoc, 1, "*");
3958 bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
3959 const FunctionProtoType *FTP;
3960 const PointerType *PT = QT->getAs<PointerType>();
3962 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
3964 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
3965 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3966 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
3969 for (const auto &I : FTP->param_types())
3970 if (isTopLevelBlockPointerType(I))
3976 bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
3977 const FunctionProtoType *FTP;
3978 const PointerType *PT = QT->getAs<PointerType>();
3980 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
3982 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
3983 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3984 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
3987 for (const auto &I : FTP->param_types()) {
3988 if (I->isObjCQualifiedIdType())
3990 if (I->isObjCObjectPointerType() &&
3991 I->getPointeeType()->isObjCQualifiedInterfaceType())
3999 void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4000 const char *&RParen) {
4001 const char *argPtr = strchr(Name, '(');
4002 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4004 LParen = argPtr; // output the start.
4005 argPtr++; // skip past the left paren.
4006 unsigned parenCount = 1;
4008 while (*argPtr && parenCount) {
4010 case '(': parenCount++; break;
4011 case ')': parenCount--; break;
4014 if (parenCount) argPtr++;
4016 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4017 RParen = argPtr; // output the end
4020 void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4021 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4022 RewriteBlockPointerFunctionArgs(FD);
4025 // Handle Variables and Typedefs.
4026 SourceLocation DeclLoc = ND->getLocation();
4028 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4029 DeclT = VD->getType();
4030 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4031 DeclT = TDD->getUnderlyingType();
4032 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4033 DeclT = FD->getType();
4035 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4037 const char *startBuf = SM->getCharacterData(DeclLoc);
4038 const char *endBuf = startBuf;
4039 // scan backward (from the decl location) for the end of the previous decl.
4040 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4042 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4044 unsigned OrigLength=0;
4045 // *startBuf != '^' if we are dealing with a pointer to function that
4046 // may take block argument types (which will be handled below).
4047 if (*startBuf == '^') {
4048 // Replace the '^' with '*', computing a negative offset.
4053 while (*startBuf != ')') {
4061 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4062 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4063 // Replace the '^' with '*' for arguments.
4064 // Replace id<P> with id/*<>*/
4065 DeclLoc = ND->getLocation();
4066 startBuf = SM->getCharacterData(DeclLoc);
4067 const char *argListBegin, *argListEnd;
4068 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4069 while (argListBegin < argListEnd) {
4070 if (*argListBegin == '^')
4072 else if (*argListBegin == '<') {
4074 buf += *argListBegin++;
4076 while (*argListBegin != '>') {
4077 buf += *argListBegin++;
4080 buf += *argListBegin;
4084 buf += *argListBegin;
4091 ReplaceText(Start, OrigLength, buf);
4094 /// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4095 /// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4096 /// struct Block_byref_id_object *src) {
4097 /// _Block_object_assign (&_dest->object, _src->object,
4098 /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4099 /// [|BLOCK_FIELD_IS_WEAK]) // object
4100 /// _Block_object_assign(&_dest->object, _src->object,
4101 /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4102 /// [|BLOCK_FIELD_IS_WEAK]) // block
4105 /// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4106 /// _Block_object_dispose(_src->object,
4107 /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4108 /// [|BLOCK_FIELD_IS_WEAK]) // object
4109 /// _Block_object_dispose(_src->object,
4110 /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4111 /// [|BLOCK_FIELD_IS_WEAK]) // block
4114 std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4117 if (CopyDestroyCache.count(flag))
4119 CopyDestroyCache.insert(flag);
4120 S = "static void __Block_byref_id_object_copy_";
4122 S += "(void *dst, void *src) {\n";
4124 // offset into the object pointer is computed as:
4125 // void * + void* + int + int + void* + void *
4127 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4128 unsigned VoidPtrSize =
4129 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4131 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4132 S += " _Block_object_assign((char*)dst + ";
4133 S += utostr(offset);
4134 S += ", *(void * *) ((char*)src + ";
4135 S += utostr(offset);
4140 S += "static void __Block_byref_id_object_dispose_";
4142 S += "(void *src) {\n";
4143 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4144 S += utostr(offset);
4151 /// RewriteByRefVar - For each __block typex ND variable this routine transforms
4152 /// the declaration into:
4153 /// struct __Block_byref_ND {
4154 /// void *__isa; // NULL for everything except __weak pointers
4155 /// struct __Block_byref_ND *__forwarding;
4156 /// int32_t __flags;
4158 /// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4159 /// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4163 /// It then replaces declaration of ND variable with:
4164 /// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4165 /// __size=sizeof(struct __Block_byref_ND),
4166 /// ND=initializer-if-any};
4169 void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
4170 // Insert declaration for the function in which block literal is
4172 if (CurFunctionDeclToDeclareForBlock)
4173 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
4176 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4177 if (DeclLoc.isInvalid())
4178 // If type location is missing, it is because of missing type (a warning).
4179 // Use variable's location which is good for this case.
4180 DeclLoc = ND->getLocation();
4181 const char *startBuf = SM->getCharacterData(DeclLoc);
4182 SourceLocation X = ND->getLocEnd();
4183 X = SM->getExpansionLoc(X);
4184 const char *endBuf = SM->getCharacterData(X);
4185 std::string Name(ND->getNameAsString());
4186 std::string ByrefType;
4187 RewriteByRefString(ByrefType, Name, ND, true);
4188 ByrefType += " {\n";
4189 ByrefType += " void *__isa;\n";
4190 RewriteByRefString(ByrefType, Name, ND);
4191 ByrefType += " *__forwarding;\n";
4192 ByrefType += " int __flags;\n";
4193 ByrefType += " int __size;\n";
4194 // Add void *__Block_byref_id_object_copy;
4195 // void *__Block_byref_id_object_dispose; if needed.
4196 QualType Ty = ND->getType();
4197 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
4198 if (HasCopyAndDispose) {
4199 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4200 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4204 (void)convertBlockPointerToFunctionPointer(T);
4205 T.getAsStringInternal(Name, Context->getPrintingPolicy());
4207 ByrefType += " " + Name + ";\n";
4208 ByrefType += "};\n";
4209 // Insert this type in global scope. It is needed by helper function.
4210 SourceLocation FunLocStart;
4212 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4214 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4215 FunLocStart = CurMethodDef->getLocStart();
4217 InsertText(FunLocStart, ByrefType);
4218 if (Ty.isObjCGCWeak()) {
4219 flag |= BLOCK_FIELD_IS_WEAK;
4223 if (HasCopyAndDispose) {
4224 flag = BLOCK_BYREF_CALLER;
4225 QualType Ty = ND->getType();
4226 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4227 if (Ty->isBlockPointerType())
4228 flag |= BLOCK_FIELD_IS_BLOCK;
4230 flag |= BLOCK_FIELD_IS_OBJECT;
4231 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
4233 InsertText(FunLocStart, HF);
4236 // struct __Block_byref_ND ND =
4237 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4238 // initializer-if-any};
4239 bool hasInit = (ND->getInit() != nullptr);
4241 if (HasCopyAndDispose)
4242 flags |= BLOCK_HAS_COPY_DISPOSE;
4243 Name = ND->getNameAsString();
4245 RewriteByRefString(ByrefType, Name, ND);
4246 std::string ForwardingCastType("(");
4247 ForwardingCastType += ByrefType + " *)";
4249 ByrefType += " " + Name + " = {(void*)";
4250 ByrefType += utostr(isa);
4251 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4252 ByrefType += utostr(flags);
4254 ByrefType += "sizeof(";
4255 RewriteByRefString(ByrefType, Name, ND);
4257 if (HasCopyAndDispose) {
4258 ByrefType += ", __Block_byref_id_object_copy_";
4259 ByrefType += utostr(flag);
4260 ByrefType += ", __Block_byref_id_object_dispose_";
4261 ByrefType += utostr(flag);
4263 ByrefType += "};\n";
4264 unsigned nameSize = Name.size();
4265 // for block or function pointer declaration. Name is already
4266 // part of the declaration.
4267 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4269 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
4272 SourceLocation startLoc;
4273 Expr *E = ND->getInit();
4274 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4275 startLoc = ECE->getLParenLoc();
4277 startLoc = E->getLocStart();
4278 startLoc = SM->getExpansionLoc(startLoc);
4279 endBuf = SM->getCharacterData(startLoc);
4280 ByrefType += " " + Name;
4281 ByrefType += " = {(void*)";
4282 ByrefType += utostr(isa);
4283 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4284 ByrefType += utostr(flags);
4286 ByrefType += "sizeof(";
4287 RewriteByRefString(ByrefType, Name, ND);
4289 if (HasCopyAndDispose) {
4290 ByrefType += "__Block_byref_id_object_copy_";
4291 ByrefType += utostr(flag);
4292 ByrefType += ", __Block_byref_id_object_dispose_";
4293 ByrefType += utostr(flag);
4296 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
4298 // Complete the newly synthesized compound expression by inserting a right
4299 // curly brace before the end of the declaration.
4300 // FIXME: This approach avoids rewriting the initializer expression. It
4301 // also assumes there is only one declarator. For example, the following
4302 // isn't currently supported by this routine (in general):
4304 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4306 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4307 const char *semiBuf = strchr(startInitializerBuf, ';');
4308 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4309 SourceLocation semiLoc =
4310 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
4312 InsertText(semiLoc, "}");
4316 void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4317 // Add initializers for any closure decl refs.
4318 GetBlockDeclRefExprs(Exp->getBody());
4319 if (BlockDeclRefs.size()) {
4320 // Unique all "by copy" declarations.
4321 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4322 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
4323 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4324 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4325 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4328 // Unique all "by ref" declarations.
4329 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4330 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
4331 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4332 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4333 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4336 // Find any imported blocks...they will need special attention.
4337 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4338 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
4339 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4340 BlockDeclRefs[i]->getType()->isBlockPointerType())
4341 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4345 FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
4346 IdentifierInfo *ID = &Context->Idents.get(name);
4347 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
4348 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4349 SourceLocation(), ID, FType, nullptr, SC_Extern,
4353 Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
4354 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
4355 const BlockDecl *block = Exp->getBlockDecl();
4356 Blocks.push_back(Exp);
4358 CollectBlockDeclRefInfo(Exp);
4360 // Add inner imported variables now used in current block.
4361 int countOfInnerDecls = 0;
4362 if (!InnerBlockDeclRefs.empty()) {
4363 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
4364 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
4365 ValueDecl *VD = Exp->getDecl();
4366 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
4367 // We need to save the copied-in variables in nested
4368 // blocks because it is needed at the end for some of the API generations.
4369 // See SynthesizeBlockLiterals routine.
4370 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4371 BlockDeclRefs.push_back(Exp);
4372 BlockByCopyDeclsPtrSet.insert(VD);
4373 BlockByCopyDecls.push_back(VD);
4375 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
4376 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4377 BlockDeclRefs.push_back(Exp);
4378 BlockByRefDeclsPtrSet.insert(VD);
4379 BlockByRefDecls.push_back(VD);
4382 // Find any imported blocks...they will need special attention.
4383 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
4384 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
4385 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4386 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4387 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
4389 InnerDeclRefsCount.push_back(countOfInnerDecls);
4391 std::string FuncName;
4394 FuncName = CurFunctionDef->getNameAsString();
4395 else if (CurMethodDef)
4396 BuildUniqueMethodName(FuncName, CurMethodDef);
4397 else if (GlobalVarDecl)
4398 FuncName = std::string(GlobalVarDecl->getNameAsString());
4400 std::string BlockNumber = utostr(Blocks.size()-1);
4402 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4403 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4405 // Get a pointer to the function type so we can cast appropriately.
4406 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4407 QualType FType = Context->getPointerType(BFT);
4412 // Simulate a constructor call...
4413 FD = SynthBlockInitFunctionDecl(Tag);
4414 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
4417 SmallVector<Expr*, 4> InitExprs;
4419 // Initialize the block function.
4420 FD = SynthBlockInitFunctionDecl(Func);
4421 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4422 VK_LValue, SourceLocation());
4423 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4425 InitExprs.push_back(castExpr);
4427 // Initialize the block descriptor.
4428 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
4430 VarDecl *NewVD = VarDecl::Create(
4431 *Context, TUDecl, SourceLocation(), SourceLocation(),
4432 &Context->Idents.get(DescData), Context->VoidPtrTy, nullptr, SC_Static);
4433 UnaryOperator *DescRefExpr =
4434 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
4439 Context->getPointerType(Context->VoidPtrTy),
4440 VK_RValue, OK_Ordinary,
4442 InitExprs.push_back(DescRefExpr);
4444 // Add initializers for any closure decl refs.
4445 if (BlockDeclRefs.size()) {
4447 // Output all "by copy" declarations.
4448 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
4449 E = BlockByCopyDecls.end(); I != E; ++I) {
4450 if (isObjCType((*I)->getType())) {
4451 // FIXME: Conform to ABI ([[obj retain] autorelease]).
4452 FD = SynthBlockInitFunctionDecl((*I)->getName());
4453 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
4455 if (HasLocalVariableExternalStorage(*I)) {
4456 QualType QT = (*I)->getType();
4457 QT = Context->getPointerType(QT);
4458 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4459 OK_Ordinary, SourceLocation());
4461 } else if (isTopLevelBlockPointerType((*I)->getType())) {
4462 FD = SynthBlockInitFunctionDecl((*I)->getName());
4463 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
4465 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4468 FD = SynthBlockInitFunctionDecl((*I)->getName());
4469 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
4471 if (HasLocalVariableExternalStorage(*I)) {
4472 QualType QT = (*I)->getType();
4473 QT = Context->getPointerType(QT);
4474 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4475 OK_Ordinary, SourceLocation());
4478 InitExprs.push_back(Exp);
4480 // Output all "by ref" declarations.
4481 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
4482 E = BlockByRefDecls.end(); I != E; ++I) {
4483 ValueDecl *ND = (*I);
4484 std::string Name(ND->getNameAsString());
4485 std::string RecName;
4486 RewriteByRefString(RecName, Name, ND, true);
4487 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4488 + sizeof("struct"));
4489 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4490 SourceLocation(), SourceLocation(),
4492 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4493 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4495 FD = SynthBlockInitFunctionDecl((*I)->getName());
4496 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
4498 bool isNestedCapturedVar = false;
4500 for (const auto &CI : block->captures()) {
4501 const VarDecl *variable = CI.getVariable();
4502 if (variable == ND && CI.isNested()) {
4503 assert (CI.isByRef() &&
4504 "SynthBlockInitExpr - captured block variable is not byref");
4505 isNestedCapturedVar = true;
4509 // captured nested byref variable has its address passed. Do not take
4510 // its address again.
4511 if (!isNestedCapturedVar)
4512 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
4513 Context->getPointerType(Exp->getType()),
4514 VK_RValue, OK_Ordinary, SourceLocation());
4515 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
4516 InitExprs.push_back(Exp);
4519 if (ImportedBlockDecls.size()) {
4520 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4521 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
4523 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4524 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4525 Context->IntTy, SourceLocation());
4526 InitExprs.push_back(FlagExp);
4528 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
4529 FType, VK_LValue, SourceLocation());
4530 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
4531 Context->getPointerType(NewRep->getType()),
4532 VK_RValue, OK_Ordinary, SourceLocation());
4533 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
4535 BlockDeclRefs.clear();
4536 BlockByRefDecls.clear();
4537 BlockByRefDeclsPtrSet.clear();
4538 BlockByCopyDecls.clear();
4539 BlockByCopyDeclsPtrSet.clear();
4540 ImportedBlockDecls.clear();
4544 bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4545 if (const ObjCForCollectionStmt * CS =
4546 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4547 return CS->getElement() == DS;
4551 //===----------------------------------------------------------------------===//
4552 // Function Body / Expression rewriting
4553 //===----------------------------------------------------------------------===//
4555 Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4556 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4557 isa<DoStmt>(S) || isa<ForStmt>(S))
4559 else if (isa<ObjCForCollectionStmt>(S)) {
4561 ObjCBcLabelNo.push_back(++BcLabelCount);
4564 // Pseudo-object operations and ivar references need special
4565 // treatment because we're going to recursively rewrite them.
4566 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4567 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4568 return RewritePropertyOrImplicitSetter(PseudoOp);
4570 return RewritePropertyOrImplicitGetter(PseudoOp);
4572 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4573 return RewriteObjCIvarRefExpr(IvarRefExpr);
4576 SourceRange OrigStmtRange = S->getSourceRange();
4578 // Perform a bottom up rewrite of all children.
4579 for (Stmt *&childStmt : S->children())
4581 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
4583 childStmt = newStmt;
4587 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4588 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
4589 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4590 InnerContexts.insert(BE->getBlockDecl());
4591 ImportedLocalExternalDecls.clear();
4592 GetInnerBlockDeclRefExprs(BE->getBody(),
4593 InnerBlockDeclRefs, InnerContexts);
4594 // Rewrite the block body in place.
4595 Stmt *SaveCurrentBody = CurrentBody;
4596 CurrentBody = BE->getBody();
4597 PropParentMap = nullptr;
4598 // block literal on rhs of a property-dot-sytax assignment
4599 // must be replaced by its synthesize ast so getRewrittenText
4600 // works as expected. In this case, what actually ends up on RHS
4601 // is the blockTranscribed which is the helper function for the
4602 // block literal; as in: self.c = ^() {[ace ARR];};
4603 bool saveDisableReplaceStmt = DisableReplaceStmt;
4604 DisableReplaceStmt = false;
4605 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4606 DisableReplaceStmt = saveDisableReplaceStmt;
4607 CurrentBody = SaveCurrentBody;
4608 PropParentMap = nullptr;
4609 ImportedLocalExternalDecls.clear();
4610 // Now we snarf the rewritten text and stash it away for later use.
4611 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
4612 RewrittenBlockExprs[BE] = Str;
4614 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4616 //blockTranscribed->dump();
4617 ReplaceStmt(S, blockTranscribed);
4618 return blockTranscribed;
4620 // Handle specific things.
4621 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4622 return RewriteAtEncode(AtEncode);
4624 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4625 return RewriteAtSelector(AtSelector);
4627 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4628 return RewriteObjCStringLiteral(AtString);
4630 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
4632 // Before we rewrite it, put the original message expression in a comment.
4633 SourceLocation startLoc = MessExpr->getLocStart();
4634 SourceLocation endLoc = MessExpr->getLocEnd();
4636 const char *startBuf = SM->getCharacterData(startLoc);
4637 const char *endBuf = SM->getCharacterData(endLoc);
4639 std::string messString;
4640 messString += "// ";
4641 messString.append(startBuf, endBuf-startBuf+1);
4644 // FIXME: Missing definition of
4645 // InsertText(clang::SourceLocation, char const*, unsigned int).
4646 // InsertText(startLoc, messString);
4647 // Tried this, but it didn't work either...
4648 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
4650 return RewriteMessageExpr(MessExpr);
4653 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4654 return RewriteObjCTryStmt(StmtTry);
4656 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4657 return RewriteObjCSynchronizedStmt(StmtTry);
4659 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4660 return RewriteObjCThrowStmt(StmtThrow);
4662 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4663 return RewriteObjCProtocolExpr(ProtocolExp);
4665 if (ObjCForCollectionStmt *StmtForCollection =
4666 dyn_cast<ObjCForCollectionStmt>(S))
4667 return RewriteObjCForCollectionStmt(StmtForCollection,
4668 OrigStmtRange.getEnd());
4669 if (BreakStmt *StmtBreakStmt =
4670 dyn_cast<BreakStmt>(S))
4671 return RewriteBreakStmt(StmtBreakStmt);
4672 if (ContinueStmt *StmtContinueStmt =
4673 dyn_cast<ContinueStmt>(S))
4674 return RewriteContinueStmt(StmtContinueStmt);
4676 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4678 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4679 // FIXME: What we're doing here is modifying the type-specifier that
4680 // precedes the first Decl. In the future the DeclGroup should have
4681 // a separate type-specifier that we can rewrite.
4682 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4683 // the context of an ObjCForCollectionStmt. For example:
4684 // NSArray *someArray;
4685 // for (id <FooProtocol> index in someArray) ;
4686 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4687 // and it depends on the original text locations/positions.
4688 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
4689 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4691 // Blocks rewrite rules.
4692 for (auto *SD : DS->decls()) {
4693 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
4694 if (isTopLevelBlockPointerType(ND->getType()))
4695 RewriteBlockPointerDecl(ND);
4696 else if (ND->getType()->isFunctionPointerType())
4697 CheckFunctionPointerDecl(ND->getType(), ND);
4698 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
4699 if (VD->hasAttr<BlocksAttr>()) {
4700 static unsigned uniqueByrefDeclCount = 0;
4701 assert(!BlockByRefDeclNo.count(ND) &&
4702 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4703 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
4704 RewriteByRefVar(VD);
4707 RewriteTypeOfDecl(VD);
4710 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
4711 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4712 RewriteBlockPointerDecl(TD);
4713 else if (TD->getUnderlyingType()->isFunctionPointerType())
4714 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4719 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4720 RewriteObjCQualifiedInterfaceTypes(CE);
4722 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4723 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4724 assert(!Stmts.empty() && "Statement stack is empty");
4725 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4726 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4727 && "Statement stack mismatch");
4730 // Handle blocks rewriting.
4731 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4732 ValueDecl *VD = DRE->getDecl();
4733 if (VD->hasAttr<BlocksAttr>())
4734 return RewriteBlockDeclRefExpr(DRE);
4735 if (HasLocalVariableExternalStorage(VD))
4736 return RewriteLocalVariableExternalStorage(DRE);
4739 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4740 if (CE->getCallee()->getType()->isBlockPointerType()) {
4741 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
4742 ReplaceStmt(S, BlockCall);
4746 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
4747 RewriteCastExpr(CE);
4750 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4751 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4754 // Get the new text.
4756 llvm::raw_string_ostream Buf(SStr);
4757 Replacement->printPretty(Buf);
4758 const std::string &Str = Buf.str();
4760 printf("CAST = %s\n", &Str[0]);
4761 InsertText(ICE->getSubExpr()->getLocStart(), Str);
4766 // Return this stmt unmodified.
4770 void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
4771 for (auto *FD : RD->fields()) {
4772 if (isTopLevelBlockPointerType(FD->getType()))
4773 RewriteBlockPointerDecl(FD);
4774 if (FD->getType()->isObjCQualifiedIdType() ||
4775 FD->getType()->isObjCQualifiedInterfaceType())
4776 RewriteObjCQualifiedInterfaceTypes(FD);
4780 /// HandleDeclInMainFile - This is called for each top-level decl defined in the
4781 /// main file of the input.
4782 void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4783 switch (D->getKind()) {
4784 case Decl::Function: {
4785 FunctionDecl *FD = cast<FunctionDecl>(D);
4786 if (FD->isOverloadedOperator())
4789 // Since function prototypes don't have ParmDecl's, we check the function
4790 // prototype. This enables us to rewrite function declarations and
4791 // definitions using the same code.
4792 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
4794 if (!FD->isThisDeclarationADefinition())
4797 // FIXME: If this should support Obj-C++, support CXXTryStmt
4798 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4799 CurFunctionDef = FD;
4800 CurFunctionDeclToDeclareForBlock = FD;
4803 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4805 CurrentBody = nullptr;
4806 if (PropParentMap) {
4807 delete PropParentMap;
4808 PropParentMap = nullptr;
4810 // This synthesizes and inserts the block "impl" struct, invoke function,
4811 // and any copy/dispose helper functions.
4812 InsertBlockLiteralsWithinFunction(FD);
4813 CurFunctionDef = nullptr;
4814 CurFunctionDeclToDeclareForBlock = nullptr;
4818 case Decl::ObjCMethod: {
4819 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
4820 if (CompoundStmt *Body = MD->getCompoundBody()) {
4824 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4826 CurrentBody = nullptr;
4827 if (PropParentMap) {
4828 delete PropParentMap;
4829 PropParentMap = nullptr;
4831 InsertBlockLiteralsWithinMethod(MD);
4832 CurMethodDef = nullptr;
4836 case Decl::ObjCImplementation: {
4837 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
4838 ClassImplementation.push_back(CI);
4841 case Decl::ObjCCategoryImpl: {
4842 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
4843 CategoryImplementation.push_back(CI);
4847 VarDecl *VD = cast<VarDecl>(D);
4848 RewriteObjCQualifiedInterfaceTypes(VD);
4849 if (isTopLevelBlockPointerType(VD->getType()))
4850 RewriteBlockPointerDecl(VD);
4851 else if (VD->getType()->isFunctionPointerType()) {
4852 CheckFunctionPointerDecl(VD->getType(), VD);
4853 if (VD->getInit()) {
4854 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4855 RewriteCastExpr(CE);
4858 } else if (VD->getType()->isRecordType()) {
4859 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4860 if (RD->isCompleteDefinition())
4861 RewriteRecordBody(RD);
4863 if (VD->getInit()) {
4865 CurrentBody = VD->getInit();
4866 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
4867 CurrentBody = nullptr;
4868 if (PropParentMap) {
4869 delete PropParentMap;
4870 PropParentMap = nullptr;
4872 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
4873 GlobalVarDecl = nullptr;
4875 // This is needed for blocks.
4876 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4877 RewriteCastExpr(CE);
4882 case Decl::TypeAlias:
4883 case Decl::Typedef: {
4884 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
4885 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4886 RewriteBlockPointerDecl(TD);
4887 else if (TD->getUnderlyingType()->isFunctionPointerType())
4888 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4892 case Decl::CXXRecord:
4893 case Decl::Record: {
4894 RecordDecl *RD = cast<RecordDecl>(D);
4895 if (RD->isCompleteDefinition())
4896 RewriteRecordBody(RD);
4905 void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
4906 if (Diags.hasErrorOccurred())
4911 // Here's a great place to add any extra declarations that may be needed.
4912 // Write out meta data for each @protocol(<expr>).
4913 for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls)
4914 RewriteObjCProtocolMetaData(ProtDecl, "", "", Preamble);
4916 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
4917 if (ClassImplementation.size() || CategoryImplementation.size())
4918 RewriteImplementations();
4920 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4922 if (const RewriteBuffer *RewriteBuf =
4923 Rewrite.getRewriteBufferFor(MainFileID)) {
4924 //printf("Changed:\n");
4925 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4927 llvm::errs() << "No changes\n";
4930 if (ClassImplementation.size() || CategoryImplementation.size() ||
4931 ProtocolExprDecls.size()) {
4932 // Rewrite Objective-c meta data*
4933 std::string ResultStr;
4934 RewriteMetaDataIntoBuffer(ResultStr);
4936 *OutFile << ResultStr;
4941 void RewriteObjCFragileABI::Initialize(ASTContext &context) {
4942 InitializeCommon(context);
4944 // declaring objc_selector outside the parameter list removes a silly
4945 // scope related warning...
4947 Preamble = "#pragma once\n";
4948 Preamble += "struct objc_selector; struct objc_class;\n";
4949 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
4950 Preamble += "struct objc_object *superClass; ";
4951 if (LangOpts.MicrosoftExt) {
4952 // Add a constructor for creating temporary objects.
4953 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
4955 Preamble += "object(o), superClass(s) {} ";
4958 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
4959 Preamble += "typedef struct objc_object Protocol;\n";
4960 Preamble += "#define _REWRITER_typedef_Protocol\n";
4961 Preamble += "#endif\n";
4962 if (LangOpts.MicrosoftExt) {
4963 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
4964 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
4966 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
4967 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
4968 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
4969 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
4970 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
4971 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
4972 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
4973 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
4974 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
4975 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
4976 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
4977 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
4978 Preamble += "(const char *);\n";
4979 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
4980 Preamble += "(struct objc_class *);\n";
4981 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
4982 Preamble += "(const char *);\n";
4983 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
4984 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
4985 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
4986 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
4987 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
4988 Preamble += "(struct objc_class *, struct objc_object *);\n";
4989 // @synchronized hooks.
4990 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter(struct objc_object *);\n";
4991 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit(struct objc_object *);\n";
4992 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
4993 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
4994 Preamble += "struct __objcFastEnumerationState {\n\t";
4995 Preamble += "unsigned long state;\n\t";
4996 Preamble += "void **itemsPtr;\n\t";
4997 Preamble += "unsigned long *mutationsPtr;\n\t";
4998 Preamble += "unsigned long extra[5];\n};\n";
4999 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5000 Preamble += "#define __FASTENUMERATIONSTATE\n";
5001 Preamble += "#endif\n";
5002 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5003 Preamble += "struct __NSConstantStringImpl {\n";
5004 Preamble += " int *isa;\n";
5005 Preamble += " int flags;\n";
5006 Preamble += " char *str;\n";
5007 Preamble += " long length;\n";
5009 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5010 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5011 Preamble += "#else\n";
5012 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5013 Preamble += "#endif\n";
5014 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5015 Preamble += "#endif\n";
5017 Preamble += "#ifndef BLOCK_IMPL\n";
5018 Preamble += "#define BLOCK_IMPL\n";
5019 Preamble += "struct __block_impl {\n";
5020 Preamble += " void *isa;\n";
5021 Preamble += " int Flags;\n";
5022 Preamble += " int Reserved;\n";
5023 Preamble += " void *FuncPtr;\n";
5025 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5026 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5027 Preamble += "extern \"C\" __declspec(dllexport) "
5028 "void _Block_object_assign(void *, const void *, const int);\n";
5029 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5030 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5031 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5032 Preamble += "#else\n";
5033 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5034 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5035 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5036 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5037 Preamble += "#endif\n";
5038 Preamble += "#endif\n";
5039 if (LangOpts.MicrosoftExt) {
5040 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5041 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5042 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5043 Preamble += "#define __attribute__(X)\n";
5044 Preamble += "#endif\n";
5045 Preamble += "#define __weak\n";
5048 Preamble += "#define __block\n";
5049 Preamble += "#define __weak\n";
5051 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5052 // as this avoids warning in any 64bit/32bit compilation model.
5053 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5056 /// RewriteIvarOffsetComputation - This routine synthesizes computation of
5058 void RewriteObjCFragileABI::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5059 std::string &Result) {
5060 if (ivar->isBitField()) {
5061 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5062 // place all bitfields at offset 0.
5065 Result += "__OFFSETOFIVAR__(struct ";
5066 Result += ivar->getContainingInterface()->getNameAsString();
5067 if (LangOpts.MicrosoftExt)
5070 Result += ivar->getNameAsString();
5075 /// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
5076 void RewriteObjCFragileABI::RewriteObjCProtocolMetaData(
5077 ObjCProtocolDecl *PDecl, StringRef prefix,
5078 StringRef ClassName, std::string &Result) {
5079 static bool objc_protocol_methods = false;
5081 // Output struct protocol_methods holder of method selector and type.
5082 if (!objc_protocol_methods && PDecl->hasDefinition()) {
5083 /* struct protocol_methods {
5088 Result += "\nstruct _protocol_methods {\n";
5089 Result += "\tstruct objc_selector *_cmd;\n";
5090 Result += "\tchar *method_types;\n";
5093 objc_protocol_methods = true;
5095 // Do not synthesize the protocol more than once.
5096 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
5099 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
5102 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5103 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
5104 PDecl->instmeth_end());
5105 /* struct _objc_protocol_method_list {
5106 int protocol_method_count;
5107 struct protocol_methods protocols[];
5110 Result += "\nstatic struct {\n";
5111 Result += "\tint protocol_method_count;\n";
5112 Result += "\tstruct _protocol_methods protocol_methods[";
5113 Result += utostr(NumMethods);
5114 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
5115 Result += PDecl->getNameAsString();
5116 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
5117 "{\n\t" + utostr(NumMethods) + "\n";
5119 // Output instance methods declared in this protocol.
5120 for (ObjCProtocolDecl::instmeth_iterator
5121 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
5123 if (I == PDecl->instmeth_begin())
5124 Result += "\t ,{{(struct objc_selector *)\"";
5126 Result += "\t ,{(struct objc_selector *)\"";
5127 Result += (*I)->getSelector().getAsString();
5128 std::string MethodTypeString = Context->getObjCEncodingForMethodDecl(*I);
5130 Result += MethodTypeString;
5133 Result += "\t }\n};\n";
5136 // Output class methods declared in this protocol.
5137 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
5138 PDecl->classmeth_end());
5139 if (NumMethods > 0) {
5140 /* struct _objc_protocol_method_list {
5141 int protocol_method_count;
5142 struct protocol_methods protocols[];
5145 Result += "\nstatic struct {\n";
5146 Result += "\tint protocol_method_count;\n";
5147 Result += "\tstruct _protocol_methods protocol_methods[";
5148 Result += utostr(NumMethods);
5149 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
5150 Result += PDecl->getNameAsString();
5151 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5153 Result += utostr(NumMethods);
5156 // Output instance methods declared in this protocol.
5157 for (ObjCProtocolDecl::classmeth_iterator
5158 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
5160 if (I == PDecl->classmeth_begin())
5161 Result += "\t ,{{(struct objc_selector *)\"";
5163 Result += "\t ,{(struct objc_selector *)\"";
5164 Result += (*I)->getSelector().getAsString();
5165 std::string MethodTypeString = Context->getObjCEncodingForMethodDecl(*I);
5167 Result += MethodTypeString;
5170 Result += "\t }\n};\n";
5174 /* struct _objc_protocol {
5175 // Objective-C 1.0 extensions
5176 struct _objc_protocol_extension *isa;
5177 char *protocol_name;
5178 struct _objc_protocol **protocol_list;
5179 struct _objc_protocol_method_list *instance_methods;
5180 struct _objc_protocol_method_list *class_methods;
5183 static bool objc_protocol = false;
5184 if (!objc_protocol) {
5185 Result += "\nstruct _objc_protocol {\n";
5186 Result += "\tstruct _objc_protocol_extension *isa;\n";
5187 Result += "\tchar *protocol_name;\n";
5188 Result += "\tstruct _objc_protocol **protocol_list;\n";
5189 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
5190 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
5193 objc_protocol = true;
5196 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
5197 Result += PDecl->getNameAsString();
5198 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
5200 Result += PDecl->getNameAsString();
5201 Result += "\", 0, ";
5202 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5203 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
5204 Result += PDecl->getNameAsString();
5209 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
5210 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
5211 Result += PDecl->getNameAsString();
5218 // Mark this protocol as having been generated.
5219 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()).second)
5220 llvm_unreachable("protocol already synthesized");
5223 void RewriteObjCFragileABI::RewriteObjCProtocolListMetaData(
5224 const ObjCList<ObjCProtocolDecl> &Protocols,
5225 StringRef prefix, StringRef ClassName,
5226 std::string &Result) {
5227 if (Protocols.empty()) return;
5229 for (unsigned i = 0; i != Protocols.size(); i++)
5230 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
5232 // Output the top lovel protocol meta-data for the class.
5233 /* struct _objc_protocol_list {
5234 struct _objc_protocol_list *next;
5236 struct _objc_protocol *class_protocols[];
5239 Result += "\nstatic struct {\n";
5240 Result += "\tstruct _objc_protocol_list *next;\n";
5241 Result += "\tint protocol_count;\n";
5242 Result += "\tstruct _objc_protocol *class_protocols[";
5243 Result += utostr(Protocols.size());
5244 Result += "];\n} _OBJC_";
5246 Result += "_PROTOCOLS_";
5247 Result += ClassName;
5248 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5250 Result += utostr(Protocols.size());
5253 Result += "\t,{&_OBJC_PROTOCOL_";
5254 Result += Protocols[0]->getNameAsString();
5257 for (unsigned i = 1; i != Protocols.size(); i++) {
5258 Result += "\t ,&_OBJC_PROTOCOL_";
5259 Result += Protocols[i]->getNameAsString();
5262 Result += "\t }\n};\n";
5265 void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
5266 std::string &Result) {
5267 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
5269 // Explicitly declared @interface's are already synthesized.
5270 if (CDecl->isImplicitInterfaceDecl()) {
5271 // FIXME: Implementation of a class with no @interface (legacy) does not
5272 // produce correct synthesis as yet.
5273 RewriteObjCInternalStruct(CDecl, Result);
5276 // Build _objc_ivar_list metadata for classes ivars if needed
5277 unsigned NumIvars = !IDecl->ivar_empty()
5278 ? IDecl->ivar_size()
5279 : (CDecl ? CDecl->ivar_size() : 0);
5281 static bool objc_ivar = false;
5283 /* struct _objc_ivar {
5289 Result += "\nstruct _objc_ivar {\n";
5290 Result += "\tchar *ivar_name;\n";
5291 Result += "\tchar *ivar_type;\n";
5292 Result += "\tint ivar_offset;\n";
5300 struct _objc_ivar ivar_list[nIvars];
5303 Result += "\nstatic struct {\n";
5304 Result += "\tint ivar_count;\n";
5305 Result += "\tstruct _objc_ivar ivar_list[";
5306 Result += utostr(NumIvars);
5307 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
5308 Result += IDecl->getNameAsString();
5309 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
5311 Result += utostr(NumIvars);
5314 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
5315 SmallVector<ObjCIvarDecl *, 8> IVars;
5316 if (!IDecl->ivar_empty()) {
5317 for (auto *IV : IDecl->ivars())
5318 IVars.push_back(IV);
5319 IVI = IDecl->ivar_begin();
5320 IVE = IDecl->ivar_end();
5322 IVI = CDecl->ivar_begin();
5323 IVE = CDecl->ivar_end();
5325 Result += "\t,{{\"";
5326 Result += IVI->getNameAsString();
5328 std::string TmpString, StrEncoding;
5329 Context->getObjCEncodingForType(IVI->getType(), TmpString, *IVI);
5330 QuoteDoublequotes(TmpString, StrEncoding);
5331 Result += StrEncoding;
5333 RewriteIvarOffsetComputation(*IVI, Result);
5335 for (++IVI; IVI != IVE; ++IVI) {
5336 Result += "\t ,{\"";
5337 Result += IVI->getNameAsString();
5339 std::string TmpString, StrEncoding;
5340 Context->getObjCEncodingForType(IVI->getType(), TmpString, *IVI);
5341 QuoteDoublequotes(TmpString, StrEncoding);
5342 Result += StrEncoding;
5344 RewriteIvarOffsetComputation(*IVI, Result);
5348 Result += "\t }\n};\n";
5351 // Build _objc_method_list for class's instance methods if needed
5352 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
5354 // If any of our property implementations have associated getters or
5355 // setters, produce metadata for them as well.
5356 for (const auto *Prop : IDecl->property_impls()) {
5357 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5359 if (!Prop->getPropertyIvarDecl())
5361 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
5364 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5365 if (!Getter->isDefined())
5366 InstanceMethods.push_back(Getter);
5367 if (PD->isReadOnly())
5369 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5370 if (!Setter->isDefined())
5371 InstanceMethods.push_back(Setter);
5373 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5374 true, "", IDecl->getName(), Result);
5376 // Build _objc_method_list for class's class methods if needed
5377 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5378 false, "", IDecl->getName(), Result);
5380 // Protocols referenced in class declaration?
5381 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
5382 "CLASS", CDecl->getName(), Result);
5384 // Declaration of class/meta-class metadata
5385 /* struct _objc_class {
5386 struct _objc_class *isa; // or const char *root_class_name when metadata
5387 const char *super_class_name;
5392 struct _objc_ivar_list *ivars;
5393 struct _objc_method_list *methods;
5394 struct objc_cache *cache;
5395 struct objc_protocol_list *protocols;
5396 const char *ivar_layout;
5397 struct _objc_class_ext *ext;
5400 static bool objc_class = false;
5402 Result += "\nstruct _objc_class {\n";
5403 Result += "\tstruct _objc_class *isa;\n";
5404 Result += "\tconst char *super_class_name;\n";
5405 Result += "\tchar *name;\n";
5406 Result += "\tlong version;\n";
5407 Result += "\tlong info;\n";
5408 Result += "\tlong instance_size;\n";
5409 Result += "\tstruct _objc_ivar_list *ivars;\n";
5410 Result += "\tstruct _objc_method_list *methods;\n";
5411 Result += "\tstruct objc_cache *cache;\n";
5412 Result += "\tstruct _objc_protocol_list *protocols;\n";
5413 Result += "\tconst char *ivar_layout;\n";
5414 Result += "\tstruct _objc_class_ext *ext;\n";
5419 // Meta-class metadata generation.
5420 ObjCInterfaceDecl *RootClass = nullptr;
5421 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
5422 while (SuperClass) {
5423 RootClass = SuperClass;
5424 SuperClass = SuperClass->getSuperClass();
5426 SuperClass = CDecl->getSuperClass();
5428 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
5429 Result += CDecl->getNameAsString();
5430 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
5431 "{\n\t(struct _objc_class *)\"";
5432 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
5437 Result += SuperClass->getNameAsString();
5439 Result += CDecl->getNameAsString();
5443 Result += ", 0, \"";
5444 Result += CDecl->getNameAsString();
5447 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
5448 // 'info' field is initialized to CLS_META(2) for metaclass
5449 Result += ", 0,2, sizeof(struct _objc_class), 0";
5450 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5451 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
5452 Result += IDecl->getNameAsString();
5457 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5458 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
5459 Result += CDecl->getNameAsString();
5463 Result += "\t,0,0,0,0\n";
5466 // class metadata generation.
5467 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
5468 Result += CDecl->getNameAsString();
5469 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
5470 "{\n\t&_OBJC_METACLASS_";
5471 Result += CDecl->getNameAsString();
5474 Result += SuperClass->getNameAsString();
5476 Result += CDecl->getNameAsString();
5480 Result += ", 0, \"";
5481 Result += CDecl->getNameAsString();
5484 // 'info' field is initialized to CLS_CLASS(1) for class
5486 if (!ObjCSynthesizedStructs.count(CDecl))
5489 // class has size. Must synthesize its size.
5490 Result += ",sizeof(struct ";
5491 Result += CDecl->getNameAsString();
5492 if (LangOpts.MicrosoftExt)
5497 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
5498 Result += CDecl->getNameAsString();
5503 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5504 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
5505 Result += CDecl->getNameAsString();
5506 Result += ", 0\n\t";
5510 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5511 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
5512 Result += CDecl->getNameAsString();
5513 Result += ", 0,0\n";
5516 Result += ",0,0,0\n";
5520 void RewriteObjCFragileABI::RewriteMetaDataIntoBuffer(std::string &Result) {
5521 int ClsDefCount = ClassImplementation.size();
5522 int CatDefCount = CategoryImplementation.size();
5524 // For each implemented class, write out all its meta data.
5525 for (int i = 0; i < ClsDefCount; i++)
5526 RewriteObjCClassMetaData(ClassImplementation[i], Result);
5528 // For each implemented category, write out all its meta data.
5529 for (int i = 0; i < CatDefCount; i++)
5530 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
5532 // Write objc_symtab metadata
5540 void *defs[cls_def_cnt + cat_def_cnt];
5544 Result += "\nstruct _objc_symtab {\n";
5545 Result += "\tlong sel_ref_cnt;\n";
5546 Result += "\tSEL *refs;\n";
5547 Result += "\tshort cls_def_cnt;\n";
5548 Result += "\tshort cat_def_cnt;\n";
5549 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
5552 Result += "static struct _objc_symtab "
5553 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
5554 Result += "\t0, 0, " + utostr(ClsDefCount)
5555 + ", " + utostr(CatDefCount) + "\n";
5556 for (int i = 0; i < ClsDefCount; i++) {
5557 Result += "\t,&_OBJC_CLASS_";
5558 Result += ClassImplementation[i]->getNameAsString();
5562 for (int i = 0; i < CatDefCount; i++) {
5563 Result += "\t,&_OBJC_CATEGORY_";
5564 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
5566 Result += CategoryImplementation[i]->getNameAsString();
5572 // Write objc_module metadata
5575 struct _objc_module {
5579 struct _objc_symtab *symtab;
5583 Result += "\nstruct _objc_module {\n";
5584 Result += "\tlong version;\n";
5585 Result += "\tlong size;\n";
5586 Result += "\tconst char *name;\n";
5587 Result += "\tstruct _objc_symtab *symtab;\n";
5589 Result += "static struct _objc_module "
5590 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
5591 Result += "\t" + utostr(OBJC_ABI_VERSION) +
5592 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
5595 if (LangOpts.MicrosoftExt) {
5596 if (ProtocolExprDecls.size()) {
5597 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
5598 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
5599 for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls) {
5600 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
5601 Result += ProtDecl->getNameAsString();
5602 Result += " = &_OBJC_PROTOCOL_";
5603 Result += ProtDecl->getNameAsString();
5606 Result += "#pragma data_seg(pop)\n\n";
5608 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
5609 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
5610 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
5611 Result += "&_OBJC_MODULES;\n";
5612 Result += "#pragma data_seg(pop)\n\n";
5616 /// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
5618 void RewriteObjCFragileABI::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
5619 std::string &Result) {
5620 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
5621 // Find category declaration for this implementation.
5622 ObjCCategoryDecl *CDecl
5623 = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
5625 std::string FullCategoryName = ClassDecl->getNameAsString();
5626 FullCategoryName += '_';
5627 FullCategoryName += IDecl->getNameAsString();
5629 // Build _objc_method_list for class's instance methods if needed
5630 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
5632 // If any of our property implementations have associated getters or
5633 // setters, produce metadata for them as well.
5634 for (const auto *Prop : IDecl->property_impls()) {
5635 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5637 if (!Prop->getPropertyIvarDecl())
5639 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
5642 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5643 InstanceMethods.push_back(Getter);
5644 if (PD->isReadOnly())
5646 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5647 InstanceMethods.push_back(Setter);
5649 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5650 true, "CATEGORY_", FullCategoryName, Result);
5652 // Build _objc_method_list for class's class methods if needed
5653 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5654 false, "CATEGORY_", FullCategoryName, Result);
5656 // Protocols referenced in class declaration?
5657 // Null CDecl is case of a category implementation with no category interface
5659 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
5660 FullCategoryName, Result);
5661 /* struct _objc_category {
5662 char *category_name;
5664 struct _objc_method_list *instance_methods;
5665 struct _objc_method_list *class_methods;
5666 struct _objc_protocol_list *protocols;
5667 // Objective-C 1.0 extensions
5668 uint32_t size; // sizeof (struct _objc_category)
5669 struct _objc_property_list *instance_properties; // category's own
5674 static bool objc_category = false;
5675 if (!objc_category) {
5676 Result += "\nstruct _objc_category {\n";
5677 Result += "\tchar *category_name;\n";
5678 Result += "\tchar *class_name;\n";
5679 Result += "\tstruct _objc_method_list *instance_methods;\n";
5680 Result += "\tstruct _objc_method_list *class_methods;\n";
5681 Result += "\tstruct _objc_protocol_list *protocols;\n";
5682 Result += "\tunsigned int size;\n";
5683 Result += "\tstruct _objc_property_list *instance_properties;\n";
5685 objc_category = true;
5687 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
5688 Result += FullCategoryName;
5689 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
5690 Result += IDecl->getNameAsString();
5691 Result += "\"\n\t, \"";
5692 Result += ClassDecl->getNameAsString();
5695 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5696 Result += "\t, (struct _objc_method_list *)"
5697 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
5698 Result += FullCategoryName;
5702 Result += "\t, 0\n";
5703 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5704 Result += "\t, (struct _objc_method_list *)"
5705 "&_OBJC_CATEGORY_CLASS_METHODS_";
5706 Result += FullCategoryName;
5710 Result += "\t, 0\n";
5712 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
5713 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
5714 Result += FullCategoryName;
5718 Result += "\t, 0\n";
5719 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
5722 // RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
5724 template<typename MethodIterator>
5725 void RewriteObjCFragileABI::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
5726 MethodIterator MethodEnd,
5727 bool IsInstanceMethod,
5729 StringRef ClassName,
5730 std::string &Result) {
5731 if (MethodBegin == MethodEnd) return;
5733 if (!objc_impl_method) {
5734 /* struct _objc_method {
5740 Result += "\nstruct _objc_method {\n";
5741 Result += "\tSEL _cmd;\n";
5742 Result += "\tchar *method_types;\n";
5743 Result += "\tvoid *_imp;\n";
5746 objc_impl_method = true;
5749 // Build _objc_method_list for class's methods if needed
5752 struct _objc_method_list *next_method;
5754 struct _objc_method method_list[];
5757 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
5758 Result += "\nstatic struct {\n";
5759 Result += "\tstruct _objc_method_list *next_method;\n";
5760 Result += "\tint method_count;\n";
5761 Result += "\tstruct _objc_method method_list[";
5762 Result += utostr(NumMethods);
5763 Result += "];\n} _OBJC_";
5765 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
5766 Result += "_METHODS_";
5767 Result += ClassName;
5768 Result += " __attribute__ ((used, section (\"__OBJC, __";
5769 Result += IsInstanceMethod ? "inst" : "cls";
5770 Result += "_meth\")))= ";
5771 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
5773 Result += "\t,{{(SEL)\"";
5774 Result += (*MethodBegin)->getSelector().getAsString();
5775 std::string MethodTypeString =
5776 Context->getObjCEncodingForMethodDecl(*MethodBegin);
5778 Result += MethodTypeString;
5779 Result += "\", (void *)";
5780 Result += MethodInternalNames[*MethodBegin];
5782 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
5783 Result += "\t ,{(SEL)\"";
5784 Result += (*MethodBegin)->getSelector().getAsString();
5785 std::string MethodTypeString =
5786 Context->getObjCEncodingForMethodDecl(*MethodBegin);
5788 Result += MethodTypeString;
5789 Result += "\", (void *)";
5790 Result += MethodInternalNames[*MethodBegin];
5793 Result += "\t }\n};\n";
5796 Stmt *RewriteObjCFragileABI::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
5797 SourceRange OldRange = IV->getSourceRange();
5798 Expr *BaseExpr = IV->getBase();
5800 // Rewrite the base, but without actually doing replaces.
5802 DisableReplaceStmtScope S(*this);
5803 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
5804 IV->setBase(BaseExpr);
5807 ObjCIvarDecl *D = IV->getDecl();
5809 Expr *Replacement = IV;
5811 if (BaseExpr->getType()->isObjCObjectPointerType()) {
5812 const ObjCInterfaceType *iFaceDecl =
5813 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5814 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
5815 // lookup which class implements the instance variable.
5816 ObjCInterfaceDecl *clsDeclared = nullptr;
5817 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5819 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5821 // Synthesize an explicit cast to gain access to the ivar.
5822 std::string RecName = clsDeclared->getIdentifier()->getName();
5824 IdentifierInfo *II = &Context->Idents.get(RecName);
5825 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5826 SourceLocation(), SourceLocation(),
5828 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5829 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5830 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
5833 // Don't forget the parens to enforce the proper binding.
5834 ParenExpr *PE = new (Context) ParenExpr(OldRange.getBegin(),
5837 if (IV->isFreeIvar() &&
5838 declaresSameEntity(CurMethodDef->getClassInterface(), iFaceDecl->getDecl())) {
5839 MemberExpr *ME = new (Context)
5840 MemberExpr(PE, true, SourceLocation(), D, IV->getLocation(),
5841 D->getType(), VK_LValue, OK_Ordinary);
5847 } else { // we are outside a method.
5848 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
5850 // Explicit ivar refs need to have a cast inserted.
5851 // FIXME: consider sharing some of this code with the code above.
5852 if (BaseExpr->getType()->isObjCObjectPointerType()) {
5853 const ObjCInterfaceType *iFaceDecl =
5854 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5855 // lookup which class implements the instance variable.
5856 ObjCInterfaceDecl *clsDeclared = nullptr;
5857 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5859 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5861 // Synthesize an explicit cast to gain access to the ivar.
5862 std::string RecName = clsDeclared->getIdentifier()->getName();
5864 IdentifierInfo *II = &Context->Idents.get(RecName);
5865 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5866 SourceLocation(), SourceLocation(),
5868 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5869 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5870 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
5873 // Don't forget the parens to enforce the proper binding.
5874 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
5875 IV->getBase()->getLocEnd(), castExpr);
5876 // Cannot delete IV->getBase(), since PE points to it.
5877 // Replace the old base with the cast. This is important when doing
5878 // embedded rewrites. For example, [newInv->_container addObject:0].
5883 ReplaceStmtWithRange(IV, Replacement, OldRange);
5887 #endif // CLANG_ENABLE_OBJC_REWRITER