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/Basic/TargetInfo.h"
24 #include "clang/Config/config.h"
25 #include "clang/Lex/Lexer.h"
26 #include "clang/Rewrite/Core/Rewriter.h"
27 #include "llvm/ADT/DenseSet.h"
28 #include "llvm/ADT/SmallPtrSet.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/Support/MemoryBuffer.h"
31 #include "llvm/Support/raw_ostream.h"
34 #if CLANG_ENABLE_OBJC_REWRITER
36 using namespace clang;
40 class RewriteModernObjC : public ASTConsumer {
44 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
46 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
47 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
49 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
51 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
53 BLOCK_BYREF_CURRENT_MAX = 256
57 BLOCK_NEEDS_FREE = (1 << 24),
58 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
59 BLOCK_HAS_CXX_OBJ = (1 << 26),
60 BLOCK_IS_GC = (1 << 27),
61 BLOCK_IS_GLOBAL = (1 << 28),
62 BLOCK_HAS_DESCRIPTOR = (1 << 29)
66 DiagnosticsEngine &Diags;
67 const LangOptions &LangOpts;
70 TranslationUnitDecl *TUDecl;
72 const char *MainFileStart, *MainFileEnd;
74 ParentMap *PropParentMap; // created lazily.
75 std::string InFileName;
76 std::unique_ptr<raw_ostream> OutFile;
79 TypeDecl *ProtocolTypeDecl;
80 VarDecl *GlobalVarDecl;
81 Expr *GlobalConstructionExp;
82 unsigned RewriteFailedDiag;
83 unsigned GlobalBlockRewriteFailedDiag;
84 // ObjC string constant support.
85 unsigned NumObjCStringLiterals;
86 VarDecl *ConstantStringClassReference;
87 RecordDecl *NSStringRecord;
89 // ObjC foreach break/continue generation support.
92 unsigned TryFinallyContainsReturnDiag;
94 ObjCMethodDecl *CurMethodDef;
95 RecordDecl *SuperStructDecl;
96 RecordDecl *ConstantStringDecl;
98 FunctionDecl *MsgSendFunctionDecl;
99 FunctionDecl *MsgSendSuperFunctionDecl;
100 FunctionDecl *MsgSendStretFunctionDecl;
101 FunctionDecl *MsgSendSuperStretFunctionDecl;
102 FunctionDecl *MsgSendFpretFunctionDecl;
103 FunctionDecl *GetClassFunctionDecl;
104 FunctionDecl *GetMetaClassFunctionDecl;
105 FunctionDecl *GetSuperClassFunctionDecl;
106 FunctionDecl *SelGetUidFunctionDecl;
107 FunctionDecl *CFStringFunctionDecl;
108 FunctionDecl *SuperConstructorFunctionDecl;
109 FunctionDecl *CurFunctionDef;
111 /* Misc. containers needed for meta-data rewrite. */
112 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
113 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
114 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
115 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
116 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
117 llvm::SmallPtrSet<TagDecl*, 32> GlobalDefinedTags;
118 SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
119 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
120 SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
122 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
123 SmallVector<ObjCCategoryDecl *, 8> DefinedNonLazyCategories;
125 SmallVector<Stmt *, 32> Stmts;
126 SmallVector<int, 8> ObjCBcLabelNo;
127 // Remember all the @protocol(<expr>) expressions.
128 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
130 llvm::DenseSet<uint64_t> CopyDestroyCache;
132 // Block expressions.
133 SmallVector<BlockExpr *, 32> Blocks;
134 SmallVector<int, 32> InnerDeclRefsCount;
135 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
137 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
139 // Block related declarations.
140 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
141 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
142 SmallVector<ValueDecl *, 8> BlockByRefDecls;
143 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
144 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
145 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
146 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
148 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
149 llvm::DenseMap<ObjCInterfaceDecl *,
150 llvm::SmallSetVector<ObjCIvarDecl *, 8> > ReferencedIvars;
152 // ivar bitfield grouping containers
153 llvm::DenseSet<const ObjCInterfaceDecl *> ObjCInterefaceHasBitfieldGroups;
154 llvm::DenseMap<const ObjCIvarDecl* , unsigned> IvarGroupNumber;
155 // This container maps an <class, group number for ivar> tuple to the type
156 // of the struct where the bitfield belongs.
157 llvm::DenseMap<std::pair<const ObjCInterfaceDecl*, unsigned>, QualType> GroupRecordType;
158 SmallVector<FunctionDecl*, 32> FunctionDefinitionsSeen;
160 // This maps an original source AST to it's rewritten form. This allows
161 // us to avoid rewriting the same node twice (which is very uncommon).
162 // This is needed to support some of the exotic property rewriting.
163 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
165 // Needed for header files being rewritten
167 bool SilenceRewriteMacroWarning;
168 bool GenerateLineInfo;
169 bool objc_impl_method;
171 bool DisableReplaceStmt;
172 class DisableReplaceStmtScope {
173 RewriteModernObjC &R;
177 DisableReplaceStmtScope(RewriteModernObjC &R)
178 : R(R), SavedValue(R.DisableReplaceStmt) {
179 R.DisableReplaceStmt = true;
181 ~DisableReplaceStmtScope() {
182 R.DisableReplaceStmt = SavedValue;
185 void InitializeCommon(ASTContext &context);
188 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
190 // Top Level Driver code.
191 bool HandleTopLevelDecl(DeclGroupRef D) override {
192 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
193 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
194 if (!Class->isThisDeclarationADefinition()) {
195 RewriteForwardClassDecl(D);
198 // Keep track of all interface declarations seen.
199 ObjCInterfacesSeen.push_back(Class);
204 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
205 if (!Proto->isThisDeclarationADefinition()) {
206 RewriteForwardProtocolDecl(D);
211 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*I)) {
212 // Under modern abi, we cannot translate body of the function
213 // yet until all class extensions and its implementation is seen.
214 // This is because they may introduce new bitfields which must go
215 // into their grouping struct.
216 if (FDecl->isThisDeclarationADefinition() &&
217 // Not c functions defined inside an objc container.
218 !FDecl->isTopLevelDeclInObjCContainer()) {
219 FunctionDefinitionsSeen.push_back(FDecl);
223 HandleTopLevelSingleDecl(*I);
228 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
229 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
230 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(*I)) {
231 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
232 RewriteBlockPointerDecl(TD);
233 else if (TD->getUnderlyingType()->isFunctionPointerType())
234 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
236 RewriteObjCQualifiedInterfaceTypes(TD);
241 void HandleTopLevelSingleDecl(Decl *D);
242 void HandleDeclInMainFile(Decl *D);
243 RewriteModernObjC(std::string inFile, std::unique_ptr<raw_ostream> OS,
244 DiagnosticsEngine &D, const LangOptions &LOpts,
245 bool silenceMacroWarn, bool LineInfo);
247 ~RewriteModernObjC() override {}
249 void HandleTranslationUnit(ASTContext &C) override;
251 void ReplaceStmt(Stmt *Old, Stmt *New) {
252 ReplaceStmtWithRange(Old, New, Old->getSourceRange());
255 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
256 assert(Old != nullptr && New != nullptr && "Expected non-null Stmt's");
258 Stmt *ReplacingStmt = ReplacedNodes[Old];
260 return; // We can't rewrite the same node twice.
262 if (DisableReplaceStmt)
265 // Measure the old text.
266 int Size = Rewrite.getRangeSize(SrcRange);
268 Diags.Report(Context->getFullLoc(Old->getBeginLoc()), RewriteFailedDiag)
269 << Old->getSourceRange();
274 llvm::raw_string_ostream S(SStr);
275 New->printPretty(S, nullptr, PrintingPolicy(LangOpts));
276 const std::string &Str = S.str();
278 // If replacement succeeded or warning disabled return with no warning.
279 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
280 ReplacedNodes[Old] = New;
283 if (SilenceRewriteMacroWarning)
285 Diags.Report(Context->getFullLoc(Old->getBeginLoc()), RewriteFailedDiag)
286 << Old->getSourceRange();
289 void InsertText(SourceLocation Loc, StringRef Str,
290 bool InsertAfter = true) {
291 // If insertion succeeded or warning disabled return with no warning.
292 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
293 SilenceRewriteMacroWarning)
296 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
299 void ReplaceText(SourceLocation Start, unsigned OrigLength,
301 // If removal succeeded or warning disabled return with no warning.
302 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
303 SilenceRewriteMacroWarning)
306 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
309 // Syntactic Rewriting.
310 void RewriteRecordBody(RecordDecl *RD);
311 void RewriteInclude();
312 void RewriteLineDirective(const Decl *D);
313 void ConvertSourceLocationToLineDirective(SourceLocation Loc,
314 std::string &LineString);
315 void RewriteForwardClassDecl(DeclGroupRef D);
316 void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG);
317 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
318 const std::string &typedefString);
319 void RewriteImplementations();
320 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
321 ObjCImplementationDecl *IMD,
322 ObjCCategoryImplDecl *CID);
323 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
324 void RewriteImplementationDecl(Decl *Dcl);
325 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
326 ObjCMethodDecl *MDecl, std::string &ResultStr);
327 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
328 const FunctionType *&FPRetType);
329 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
330 ValueDecl *VD, bool def=false);
331 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
332 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
333 void RewriteForwardProtocolDecl(DeclGroupRef D);
334 void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG);
335 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
336 void RewriteProperty(ObjCPropertyDecl *prop);
337 void RewriteFunctionDecl(FunctionDecl *FD);
338 void RewriteBlockPointerType(std::string& Str, QualType Type);
339 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
340 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
341 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
342 void RewriteTypeOfDecl(VarDecl *VD);
343 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
345 std::string getIvarAccessString(ObjCIvarDecl *D);
347 // Expression Rewriting.
348 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
349 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
350 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
351 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
352 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
353 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
354 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
355 Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
356 Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
357 Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
358 Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
359 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
360 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
361 Stmt *RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
362 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
363 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
364 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
365 SourceLocation OrigEnd);
366 Stmt *RewriteBreakStmt(BreakStmt *S);
367 Stmt *RewriteContinueStmt(ContinueStmt *S);
368 void RewriteCastExpr(CStyleCastExpr *CE);
369 void RewriteImplicitCastObjCExpr(CastExpr *IE);
371 // Computes ivar bitfield group no.
372 unsigned ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV);
373 // Names field decl. for ivar bitfield group.
374 void ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV, std::string &Result);
375 // Names struct type for ivar bitfield group.
376 void ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV, std::string &Result);
377 // Names symbol for ivar bitfield group field offset.
378 void ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV, std::string &Result);
379 // Given an ivar bitfield, it builds (or finds) its group record type.
380 QualType GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV);
381 QualType SynthesizeBitfieldGroupStructType(
383 SmallVectorImpl<ObjCIvarDecl *> &IVars);
386 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
388 // Block specific rewrite rules.
389 void RewriteBlockPointerDecl(NamedDecl *VD);
390 void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
391 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
392 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
393 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
395 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
396 std::string &Result);
398 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
399 bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
400 bool &IsNamedDefinition);
401 void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
402 std::string &Result);
404 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
406 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
407 std::string &Result);
409 void Initialize(ASTContext &context) override;
411 // Misc. AST transformation routines. Sometimes they end up calling
412 // rewriting routines on the new ASTs.
413 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
414 ArrayRef<Expr *> Args,
415 SourceLocation StartLoc=SourceLocation(),
416 SourceLocation EndLoc=SourceLocation());
418 Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
420 SmallVectorImpl<QualType> &ArgTypes,
421 SmallVectorImpl<Expr*> &MsgExprs,
422 ObjCMethodDecl *Method);
424 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
425 SourceLocation StartLoc=SourceLocation(),
426 SourceLocation EndLoc=SourceLocation());
428 void SynthCountByEnumWithState(std::string &buf);
429 void SynthMsgSendFunctionDecl();
430 void SynthMsgSendSuperFunctionDecl();
431 void SynthMsgSendStretFunctionDecl();
432 void SynthMsgSendFpretFunctionDecl();
433 void SynthMsgSendSuperStretFunctionDecl();
434 void SynthGetClassFunctionDecl();
435 void SynthGetMetaClassFunctionDecl();
436 void SynthGetSuperClassFunctionDecl();
437 void SynthSelGetUidFunctionDecl();
438 void SynthSuperConstructorFunctionDecl();
440 // Rewriting metadata
441 template<typename MethodIterator>
442 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
443 MethodIterator MethodEnd,
444 bool IsInstanceMethod,
447 std::string &Result);
448 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
449 std::string &Result);
450 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
451 std::string &Result);
452 void RewriteClassSetupInitHook(std::string &Result);
454 void RewriteMetaDataIntoBuffer(std::string &Result);
455 void WriteImageInfo(std::string &Result);
456 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
457 std::string &Result);
458 void RewriteCategorySetupInitHook(std::string &Result);
461 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
462 std::string &Result);
463 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
466 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
467 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
468 StringRef funcName, std::string Tag);
469 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
470 StringRef funcName, std::string Tag);
471 std::string SynthesizeBlockImpl(BlockExpr *CE,
472 std::string Tag, std::string Desc);
473 std::string SynthesizeBlockDescriptor(std::string DescTag,
475 int i, StringRef funcName,
477 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
478 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
480 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
481 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
482 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
484 // Misc. helper routines.
485 QualType getProtocolType();
486 void WarnAboutReturnGotoStmts(Stmt *S);
487 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
488 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
489 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
491 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
492 void CollectBlockDeclRefInfo(BlockExpr *Exp);
493 void GetBlockDeclRefExprs(Stmt *S);
494 void GetInnerBlockDeclRefExprs(Stmt *S,
495 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
496 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts);
498 // We avoid calling Type::isBlockPointerType(), since it operates on the
499 // canonical type. We only care if the top-level type is a closure pointer.
500 bool isTopLevelBlockPointerType(QualType T) {
501 return isa<BlockPointerType>(T);
504 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
505 /// to a function pointer type and upon success, returns true; false
507 bool convertBlockPointerToFunctionPointer(QualType &T) {
508 if (isTopLevelBlockPointerType(T)) {
509 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
510 T = Context->getPointerType(BPT->getPointeeType());
516 bool convertObjCTypeToCStyleType(QualType &T);
518 bool needToScanForQualifiers(QualType T);
519 QualType getSuperStructType();
520 QualType getConstantStringStructType();
521 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
523 void convertToUnqualifiedObjCType(QualType &T) {
524 if (T->isObjCQualifiedIdType()) {
525 bool isConst = T.isConstQualified();
526 T = isConst ? Context->getObjCIdType().withConst()
527 : Context->getObjCIdType();
529 else if (T->isObjCQualifiedClassType())
530 T = Context->getObjCClassType();
531 else if (T->isObjCObjectPointerType() &&
532 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
533 if (const ObjCObjectPointerType * OBJPT =
534 T->getAsObjCInterfacePointerType()) {
535 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
536 T = QualType(IFaceT, 0);
537 T = Context->getPointerType(T);
542 // FIXME: This predicate seems like it would be useful to add to ASTContext.
543 bool isObjCType(QualType T) {
547 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
549 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
550 OCT == Context->getCanonicalType(Context->getObjCClassType()))
553 if (const PointerType *PT = OCT->getAs<PointerType>()) {
554 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
555 PT->getPointeeType()->isObjCQualifiedIdType())
561 bool PointerTypeTakesAnyBlockArguments(QualType QT);
562 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
563 void GetExtentOfArgList(const char *Name, const char *&LParen,
564 const char *&RParen);
566 void QuoteDoublequotes(std::string &From, std::string &To) {
567 for (unsigned i = 0; i < From.length(); i++) {
575 QualType getSimpleFunctionType(QualType result,
576 ArrayRef<QualType> args,
577 bool variadic = false) {
578 if (result == Context->getObjCInstanceType())
579 result = Context->getObjCIdType();
580 FunctionProtoType::ExtProtoInfo fpi;
581 fpi.Variadic = variadic;
582 return Context->getFunctionType(result, args, fpi);
585 // Helper function: create a CStyleCastExpr with trivial type source info.
586 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
587 CastKind Kind, Expr *E) {
588 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
589 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, nullptr,
590 TInfo, SourceLocation(), SourceLocation());
593 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
594 IdentifierInfo* II = &Context->Idents.get("load");
595 Selector LoadSel = Context->Selectors.getSelector(0, &II);
596 return OD->getClassMethod(LoadSel) != nullptr;
599 StringLiteral *getStringLiteral(StringRef Str) {
600 QualType StrType = Context->getConstantArrayType(
601 Context->CharTy, llvm::APInt(32, Str.size() + 1), ArrayType::Normal,
603 return StringLiteral::Create(*Context, Str, StringLiteral::Ascii,
604 /*Pascal=*/false, StrType, SourceLocation());
607 } // end anonymous namespace
609 void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
611 if (const FunctionProtoType *fproto
612 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
613 for (const auto &I : fproto->param_types())
614 if (isTopLevelBlockPointerType(I)) {
615 // All the args are checked/rewritten. Don't call twice!
616 RewriteBlockPointerDecl(D);
622 void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
623 const PointerType *PT = funcType->getAs<PointerType>();
624 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
625 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
628 static bool IsHeaderFile(const std::string &Filename) {
629 std::string::size_type DotPos = Filename.rfind('.');
631 if (DotPos == std::string::npos) {
636 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
638 // C++ header: .hh or .H;
639 return Ext == "h" || Ext == "hh" || Ext == "H";
642 RewriteModernObjC::RewriteModernObjC(std::string inFile,
643 std::unique_ptr<raw_ostream> OS,
644 DiagnosticsEngine &D,
645 const LangOptions &LOpts,
646 bool silenceMacroWarn, bool LineInfo)
647 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(std::move(OS)),
648 SilenceRewriteMacroWarning(silenceMacroWarn), GenerateLineInfo(LineInfo) {
649 IsHeader = IsHeaderFile(inFile);
650 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
651 "rewriting sub-expression within a macro (may not be correct)");
652 // FIXME. This should be an error. But if block is not called, it is OK. And it
653 // may break including some headers.
654 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
655 "rewriting block literal declared in global scope is not implemented");
657 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
658 DiagnosticsEngine::Warning,
659 "rewriter doesn't support user-specified control flow semantics "
660 "for @try/@finally (code may not execute properly)");
663 std::unique_ptr<ASTConsumer> clang::CreateModernObjCRewriter(
664 const std::string &InFile, std::unique_ptr<raw_ostream> OS,
665 DiagnosticsEngine &Diags, const LangOptions &LOpts,
666 bool SilenceRewriteMacroWarning, bool LineInfo) {
667 return llvm::make_unique<RewriteModernObjC>(InFile, std::move(OS), Diags,
668 LOpts, SilenceRewriteMacroWarning,
672 void RewriteModernObjC::InitializeCommon(ASTContext &context) {
674 SM = &Context->getSourceManager();
675 TUDecl = Context->getTranslationUnitDecl();
676 MsgSendFunctionDecl = nullptr;
677 MsgSendSuperFunctionDecl = nullptr;
678 MsgSendStretFunctionDecl = nullptr;
679 MsgSendSuperStretFunctionDecl = nullptr;
680 MsgSendFpretFunctionDecl = nullptr;
681 GetClassFunctionDecl = nullptr;
682 GetMetaClassFunctionDecl = nullptr;
683 GetSuperClassFunctionDecl = nullptr;
684 SelGetUidFunctionDecl = nullptr;
685 CFStringFunctionDecl = nullptr;
686 ConstantStringClassReference = nullptr;
687 NSStringRecord = nullptr;
688 CurMethodDef = nullptr;
689 CurFunctionDef = nullptr;
690 GlobalVarDecl = nullptr;
691 GlobalConstructionExp = nullptr;
692 SuperStructDecl = nullptr;
693 ProtocolTypeDecl = nullptr;
694 ConstantStringDecl = nullptr;
696 SuperConstructorFunctionDecl = nullptr;
697 NumObjCStringLiterals = 0;
698 PropParentMap = nullptr;
699 CurrentBody = nullptr;
700 DisableReplaceStmt = false;
701 objc_impl_method = false;
703 // Get the ID and start/end of the main file.
704 MainFileID = SM->getMainFileID();
705 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
706 MainFileStart = MainBuf->getBufferStart();
707 MainFileEnd = MainBuf->getBufferEnd();
709 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
712 //===----------------------------------------------------------------------===//
713 // Top Level Driver Code
714 //===----------------------------------------------------------------------===//
716 void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
717 if (Diags.hasErrorOccurred())
720 // Two cases: either the decl could be in the main file, or it could be in a
721 // #included file. If the former, rewrite it now. If the later, check to see
722 // if we rewrote the #include/#import.
723 SourceLocation Loc = D->getLocation();
724 Loc = SM->getExpansionLoc(Loc);
726 // If this is for a builtin, ignore it.
727 if (Loc.isInvalid()) return;
729 // Look for built-in declarations that we need to refer during the rewrite.
730 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
731 RewriteFunctionDecl(FD);
732 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
733 // declared in <Foundation/NSString.h>
734 if (FVD->getName() == "_NSConstantStringClassReference") {
735 ConstantStringClassReference = FVD;
738 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
739 RewriteCategoryDecl(CD);
740 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
741 if (PD->isThisDeclarationADefinition())
742 RewriteProtocolDecl(PD);
743 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
744 // Recurse into linkage specifications
745 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
746 DIEnd = LSD->decls_end();
748 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
749 if (!IFace->isThisDeclarationADefinition()) {
750 SmallVector<Decl *, 8> DG;
751 SourceLocation StartLoc = IFace->getBeginLoc();
753 if (isa<ObjCInterfaceDecl>(*DI) &&
754 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
755 StartLoc == (*DI)->getBeginLoc())
761 } while (DI != DIEnd);
762 RewriteForwardClassDecl(DG);
766 // Keep track of all interface declarations seen.
767 ObjCInterfacesSeen.push_back(IFace);
773 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
774 if (!Proto->isThisDeclarationADefinition()) {
775 SmallVector<Decl *, 8> DG;
776 SourceLocation StartLoc = Proto->getBeginLoc();
778 if (isa<ObjCProtocolDecl>(*DI) &&
779 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
780 StartLoc == (*DI)->getBeginLoc())
786 } while (DI != DIEnd);
787 RewriteForwardProtocolDecl(DG);
792 HandleTopLevelSingleDecl(*DI);
796 // If we have a decl in the main file, see if we should rewrite it.
797 if (SM->isWrittenInMainFile(Loc))
798 return HandleDeclInMainFile(D);
801 //===----------------------------------------------------------------------===//
802 // Syntactic (non-AST) Rewriting Code
803 //===----------------------------------------------------------------------===//
805 void RewriteModernObjC::RewriteInclude() {
806 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
807 StringRef MainBuf = SM->getBufferData(MainFileID);
808 const char *MainBufStart = MainBuf.begin();
809 const char *MainBufEnd = MainBuf.end();
810 size_t ImportLen = strlen("import");
812 // Loop over the whole file, looking for includes.
813 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
814 if (*BufPtr == '#') {
815 if (++BufPtr == MainBufEnd)
817 while (*BufPtr == ' ' || *BufPtr == '\t')
818 if (++BufPtr == MainBufEnd)
820 if (!strncmp(BufPtr, "import", ImportLen)) {
821 // replace import with include
822 SourceLocation ImportLoc =
823 LocStart.getLocWithOffset(BufPtr-MainBufStart);
824 ReplaceText(ImportLoc, ImportLen, "include");
831 static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
832 ObjCIvarDecl *IvarDecl, std::string &Result) {
833 Result += "OBJC_IVAR_$_";
834 Result += IDecl->getName();
836 Result += IvarDecl->getName();
840 RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
841 const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
843 // Build name of symbol holding ivar offset.
844 std::string IvarOffsetName;
846 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
848 WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
850 std::string S = "(*(";
851 QualType IvarT = D->getType();
853 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
855 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
856 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
857 RD = RD->getDefinition();
858 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
859 // decltype(((Foo_IMPL*)0)->bar) *
860 ObjCContainerDecl *CDecl =
861 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
862 // ivar in class extensions requires special treatment.
863 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
864 CDecl = CatDecl->getClassInterface();
865 std::string RecName = CDecl->getName();
868 RecordDecl::Create(*Context, TTK_Struct, TUDecl, SourceLocation(),
869 SourceLocation(), &Context->Idents.get(RecName));
870 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
871 unsigned UnsignedIntSize =
872 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
873 Expr *Zero = IntegerLiteral::Create(*Context,
874 llvm::APInt(UnsignedIntSize, 0),
875 Context->UnsignedIntTy, SourceLocation());
876 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
877 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
879 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
881 &Context->Idents.get(D->getNameAsString()),
883 /*BitWidth=*/nullptr, /*Mutable=*/true,
885 MemberExpr *ME = new (Context)
886 MemberExpr(PE, true, SourceLocation(), FD, SourceLocation(),
887 FD->getType(), VK_LValue, OK_Ordinary);
888 IvarT = Context->getDecltypeType(ME, ME->getType());
891 convertObjCTypeToCStyleType(IvarT);
892 QualType castT = Context->getPointerType(IvarT);
893 std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
897 // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
898 S += "((char *)self + ";
901 if (D->isBitField()) {
903 S += D->getNameAsString();
905 ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
909 /// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
910 /// been found in the class implementation. In this case, it must be synthesized.
911 static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
912 ObjCPropertyDecl *PD,
914 return getter ? !IMP->getInstanceMethod(PD->getGetterName())
915 : !IMP->getInstanceMethod(PD->getSetterName());
919 void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
920 ObjCImplementationDecl *IMD,
921 ObjCCategoryImplDecl *CID) {
922 static bool objcGetPropertyDefined = false;
923 static bool objcSetPropertyDefined = false;
924 SourceLocation startGetterSetterLoc;
926 if (PID->getBeginLoc().isValid()) {
927 SourceLocation startLoc = PID->getBeginLoc();
928 InsertText(startLoc, "// ");
929 const char *startBuf = SM->getCharacterData(startLoc);
930 assert((*startBuf == '@') && "bogus @synthesize location");
931 const char *semiBuf = strchr(startBuf, ';');
932 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
933 startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
935 startGetterSetterLoc = IMD ? IMD->getEndLoc() : CID->getEndLoc();
937 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
938 return; // FIXME: is this correct?
940 // Generate the 'getter' function.
941 ObjCPropertyDecl *PD = PID->getPropertyDecl();
942 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
943 assert(IMD && OID && "Synthesized ivars must be attached to @implementation");
945 unsigned Attributes = PD->getPropertyAttributes();
946 if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
947 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
948 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
949 ObjCPropertyDecl::OBJC_PR_copy));
951 if (GenGetProperty && !objcGetPropertyDefined) {
952 objcGetPropertyDefined = true;
953 // FIXME. Is this attribute correct in all cases?
954 Getr = "\nextern \"C\" __declspec(dllimport) "
955 "id objc_getProperty(id, SEL, long, bool);\n";
957 RewriteObjCMethodDecl(OID->getContainingInterface(),
958 PD->getGetterMethodDecl(), Getr);
960 // Synthesize an explicit cast to gain access to the ivar.
961 // See objc-act.c:objc_synthesize_new_getter() for details.
962 if (GenGetProperty) {
963 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
965 const FunctionType *FPRetType = nullptr;
966 RewriteTypeIntoString(PD->getGetterMethodDecl()->getReturnType(), Getr,
970 Getr += ")"; // close the precedence "scope" for "*".
972 // Now, emit the argument types (if any).
973 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
975 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
977 std::string ParamStr =
978 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
981 if (FT->isVariadic()) {
982 if (FT->getNumParams())
991 Getr += "return (_TYPE)";
992 Getr += "objc_getProperty(self, _cmd, ";
993 RewriteIvarOffsetComputation(OID, Getr);
997 Getr += "return " + getIvarAccessString(OID);
999 InsertText(startGetterSetterLoc, Getr);
1002 if (PD->isReadOnly() ||
1003 !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
1006 // Generate the 'setter' function.
1008 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
1009 ObjCPropertyDecl::OBJC_PR_copy);
1010 if (GenSetProperty && !objcSetPropertyDefined) {
1011 objcSetPropertyDefined = true;
1012 // FIXME. Is this attribute correct in all cases?
1013 Setr = "\nextern \"C\" __declspec(dllimport) "
1014 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
1017 RewriteObjCMethodDecl(OID->getContainingInterface(),
1018 PD->getSetterMethodDecl(), Setr);
1020 // Synthesize an explicit cast to initialize the ivar.
1021 // See objc-act.c:objc_synthesize_new_setter() for details.
1022 if (GenSetProperty) {
1023 Setr += "objc_setProperty (self, _cmd, ";
1024 RewriteIvarOffsetComputation(OID, Setr);
1026 Setr += PD->getName();
1028 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
1032 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
1038 Setr += getIvarAccessString(OID) + " = ";
1039 Setr += PD->getName();
1042 InsertText(startGetterSetterLoc, Setr);
1045 static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
1046 std::string &typedefString) {
1047 typedefString += "\n#ifndef _REWRITER_typedef_";
1048 typedefString += ForwardDecl->getNameAsString();
1049 typedefString += "\n";
1050 typedefString += "#define _REWRITER_typedef_";
1051 typedefString += ForwardDecl->getNameAsString();
1052 typedefString += "\n";
1053 typedefString += "typedef struct objc_object ";
1054 typedefString += ForwardDecl->getNameAsString();
1055 // typedef struct { } _objc_exc_Classname;
1056 typedefString += ";\ntypedef struct {} _objc_exc_";
1057 typedefString += ForwardDecl->getNameAsString();
1058 typedefString += ";\n#endif\n";
1061 void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
1062 const std::string &typedefString) {
1063 SourceLocation startLoc = ClassDecl->getBeginLoc();
1064 const char *startBuf = SM->getCharacterData(startLoc);
1065 const char *semiPtr = strchr(startBuf, ';');
1066 // Replace the @class with typedefs corresponding to the classes.
1067 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
1070 void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
1071 std::string typedefString;
1072 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
1073 if (ObjCInterfaceDecl *ForwardDecl = dyn_cast<ObjCInterfaceDecl>(*I)) {
1074 if (I == D.begin()) {
1075 // Translate to typedef's that forward reference structs with the same name
1076 // as the class. As a convenience, we include the original declaration
1078 typedefString += "// @class ";
1079 typedefString += ForwardDecl->getNameAsString();
1080 typedefString += ";";
1082 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1085 HandleTopLevelSingleDecl(*I);
1087 DeclGroupRef::iterator I = D.begin();
1088 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
1091 void RewriteModernObjC::RewriteForwardClassDecl(
1092 const SmallVectorImpl<Decl *> &D) {
1093 std::string typedefString;
1094 for (unsigned i = 0; i < D.size(); i++) {
1095 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
1097 typedefString += "// @class ";
1098 typedefString += ForwardDecl->getNameAsString();
1099 typedefString += ";";
1101 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1103 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
1106 void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
1107 // When method is a synthesized one, such as a getter/setter there is
1108 // nothing to rewrite.
1109 if (Method->isImplicit())
1111 SourceLocation LocStart = Method->getBeginLoc();
1112 SourceLocation LocEnd = Method->getEndLoc();
1114 if (SM->getExpansionLineNumber(LocEnd) >
1115 SM->getExpansionLineNumber(LocStart)) {
1116 InsertText(LocStart, "#if 0\n");
1117 ReplaceText(LocEnd, 1, ";\n#endif\n");
1119 InsertText(LocStart, "// ");
1123 void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
1124 SourceLocation Loc = prop->getAtLoc();
1126 ReplaceText(Loc, 0, "// ");
1127 // FIXME: handle properties that are declared across multiple lines.
1130 void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
1131 SourceLocation LocStart = CatDecl->getBeginLoc();
1133 // FIXME: handle category headers that are declared across multiple lines.
1134 if (CatDecl->getIvarRBraceLoc().isValid()) {
1135 ReplaceText(LocStart, 1, "/** ");
1136 ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1139 ReplaceText(LocStart, 0, "// ");
1142 for (auto *I : CatDecl->instance_properties())
1145 for (auto *I : CatDecl->instance_methods())
1146 RewriteMethodDeclaration(I);
1147 for (auto *I : CatDecl->class_methods())
1148 RewriteMethodDeclaration(I);
1150 // Lastly, comment out the @end.
1151 ReplaceText(CatDecl->getAtEndRange().getBegin(),
1152 strlen("@end"), "/* @end */\n");
1155 void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1156 SourceLocation LocStart = PDecl->getBeginLoc();
1157 assert(PDecl->isThisDeclarationADefinition());
1159 // FIXME: handle protocol headers that are declared across multiple lines.
1160 ReplaceText(LocStart, 0, "// ");
1162 for (auto *I : PDecl->instance_methods())
1163 RewriteMethodDeclaration(I);
1164 for (auto *I : PDecl->class_methods())
1165 RewriteMethodDeclaration(I);
1166 for (auto *I : PDecl->instance_properties())
1169 // Lastly, comment out the @end.
1170 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1171 ReplaceText(LocEnd, strlen("@end"), "/* @end */\n");
1173 // Must comment out @optional/@required
1174 const char *startBuf = SM->getCharacterData(LocStart);
1175 const char *endBuf = SM->getCharacterData(LocEnd);
1176 for (const char *p = startBuf; p < endBuf; p++) {
1177 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1178 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1179 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1182 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1183 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1184 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1190 void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1191 SourceLocation LocStart = (*D.begin())->getBeginLoc();
1192 if (LocStart.isInvalid())
1193 llvm_unreachable("Invalid SourceLocation");
1194 // FIXME: handle forward protocol that are declared across multiple lines.
1195 ReplaceText(LocStart, 0, "// ");
1199 RewriteModernObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
1200 SourceLocation LocStart = DG[0]->getBeginLoc();
1201 if (LocStart.isInvalid())
1202 llvm_unreachable("Invalid SourceLocation");
1203 // FIXME: handle forward protocol that are declared across multiple lines.
1204 ReplaceText(LocStart, 0, "// ");
1207 void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1208 const FunctionType *&FPRetType) {
1209 if (T->isObjCQualifiedIdType())
1211 else if (T->isFunctionPointerType() ||
1212 T->isBlockPointerType()) {
1213 // needs special handling, since pointer-to-functions have special
1214 // syntax (where a decaration models use).
1215 QualType retType = T;
1217 if (const PointerType* PT = retType->getAs<PointerType>())
1218 PointeeTy = PT->getPointeeType();
1219 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1220 PointeeTy = BPT->getPointeeType();
1221 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1223 FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
1227 ResultStr += T.getAsString(Context->getPrintingPolicy());
1230 void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1231 ObjCMethodDecl *OMD,
1232 std::string &ResultStr) {
1233 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1234 const FunctionType *FPRetType = nullptr;
1235 ResultStr += "\nstatic ";
1236 RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
1239 // Unique method name
1240 std::string NameStr;
1242 if (OMD->isInstanceMethod())
1247 NameStr += IDecl->getNameAsString();
1250 if (ObjCCategoryImplDecl *CID =
1251 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1252 NameStr += CID->getNameAsString();
1255 // Append selector names, replacing ':' with '_'
1257 std::string selString = OMD->getSelector().getAsString();
1258 int len = selString.size();
1259 for (int i = 0; i < len; i++)
1260 if (selString[i] == ':')
1262 NameStr += selString;
1264 // Remember this name for metadata emission
1265 MethodInternalNames[OMD] = NameStr;
1266 ResultStr += NameStr;
1268 // Rewrite arguments
1271 // invisible arguments
1272 if (OMD->isInstanceMethod()) {
1273 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1274 selfTy = Context->getPointerType(selfTy);
1275 if (!LangOpts.MicrosoftExt) {
1276 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1277 ResultStr += "struct ";
1279 // When rewriting for Microsoft, explicitly omit the structure name.
1280 ResultStr += IDecl->getNameAsString();
1284 ResultStr += Context->getObjCClassType().getAsString(
1285 Context->getPrintingPolicy());
1287 ResultStr += " self, ";
1288 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1289 ResultStr += " _cmd";
1291 // Method arguments.
1292 for (const auto *PDecl : OMD->parameters()) {
1294 if (PDecl->getType()->isObjCQualifiedIdType()) {
1296 ResultStr += PDecl->getNameAsString();
1298 std::string Name = PDecl->getNameAsString();
1299 QualType QT = PDecl->getType();
1300 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1301 (void)convertBlockPointerToFunctionPointer(QT);
1302 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
1306 if (OMD->isVariadic())
1307 ResultStr += ", ...";
1311 ResultStr += ")"; // close the precedence "scope" for "*".
1313 // Now, emit the argument types (if any).
1314 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1316 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1317 if (i) ResultStr += ", ";
1318 std::string ParamStr =
1319 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
1320 ResultStr += ParamStr;
1322 if (FT->isVariadic()) {
1323 if (FT->getNumParams())
1334 void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1335 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1336 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1339 if (IMD->getIvarRBraceLoc().isValid()) {
1340 ReplaceText(IMD->getBeginLoc(), 1, "/** ");
1341 ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
1344 InsertText(IMD->getBeginLoc(), "// ");
1348 InsertText(CID->getBeginLoc(), "// ");
1350 for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) {
1351 std::string ResultStr;
1352 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1353 SourceLocation LocStart = OMD->getBeginLoc();
1354 SourceLocation LocEnd = OMD->getCompoundBody()->getBeginLoc();
1356 const char *startBuf = SM->getCharacterData(LocStart);
1357 const char *endBuf = SM->getCharacterData(LocEnd);
1358 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1361 for (auto *OMD : IMD ? IMD->class_methods() : CID->class_methods()) {
1362 std::string ResultStr;
1363 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1364 SourceLocation LocStart = OMD->getBeginLoc();
1365 SourceLocation LocEnd = OMD->getCompoundBody()->getBeginLoc();
1367 const char *startBuf = SM->getCharacterData(LocStart);
1368 const char *endBuf = SM->getCharacterData(LocEnd);
1369 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1371 for (auto *I : IMD ? IMD->property_impls() : CID->property_impls())
1372 RewritePropertyImplDecl(I, IMD, CID);
1374 InsertText(IMD ? IMD->getEndLoc() : CID->getEndLoc(), "// ");
1377 void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
1378 // Do not synthesize more than once.
1379 if (ObjCSynthesizedStructs.count(ClassDecl))
1381 // Make sure super class's are written before current class is written.
1382 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1383 while (SuperClass) {
1384 RewriteInterfaceDecl(SuperClass);
1385 SuperClass = SuperClass->getSuperClass();
1387 std::string ResultStr;
1388 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
1389 // we haven't seen a forward decl - generate a typedef.
1390 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
1391 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1393 RewriteObjCInternalStruct(ClassDecl, ResultStr);
1394 // Mark this typedef as having been written into its c++ equivalent.
1395 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
1397 for (auto *I : ClassDecl->instance_properties())
1399 for (auto *I : ClassDecl->instance_methods())
1400 RewriteMethodDeclaration(I);
1401 for (auto *I : ClassDecl->class_methods())
1402 RewriteMethodDeclaration(I);
1404 // Lastly, comment out the @end.
1405 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1410 Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1411 SourceRange OldRange = PseudoOp->getSourceRange();
1413 // We just magically know some things about the structure of this
1415 ObjCMessageExpr *OldMsg =
1416 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1417 PseudoOp->getNumSemanticExprs() - 1));
1419 // Because the rewriter doesn't allow us to rewrite rewritten code,
1420 // we need to suppress rewriting the sub-statements.
1422 SmallVector<Expr*, 2> Args;
1424 DisableReplaceStmtScope S(*this);
1426 // Rebuild the base expression if we have one.
1428 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1429 Base = OldMsg->getInstanceReceiver();
1430 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1431 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1434 unsigned numArgs = OldMsg->getNumArgs();
1435 for (unsigned i = 0; i < numArgs; i++) {
1436 Expr *Arg = OldMsg->getArg(i);
1437 if (isa<OpaqueValueExpr>(Arg))
1438 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1439 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1440 Args.push_back(Arg);
1444 // TODO: avoid this copy.
1445 SmallVector<SourceLocation, 1> SelLocs;
1446 OldMsg->getSelectorLocs(SelLocs);
1448 ObjCMessageExpr *NewMsg = nullptr;
1449 switch (OldMsg->getReceiverKind()) {
1450 case ObjCMessageExpr::Class:
1451 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1452 OldMsg->getValueKind(),
1453 OldMsg->getLeftLoc(),
1454 OldMsg->getClassReceiverTypeInfo(),
1455 OldMsg->getSelector(),
1457 OldMsg->getMethodDecl(),
1459 OldMsg->getRightLoc(),
1460 OldMsg->isImplicit());
1463 case ObjCMessageExpr::Instance:
1464 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1465 OldMsg->getValueKind(),
1466 OldMsg->getLeftLoc(),
1468 OldMsg->getSelector(),
1470 OldMsg->getMethodDecl(),
1472 OldMsg->getRightLoc(),
1473 OldMsg->isImplicit());
1476 case ObjCMessageExpr::SuperClass:
1477 case ObjCMessageExpr::SuperInstance:
1478 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1479 OldMsg->getValueKind(),
1480 OldMsg->getLeftLoc(),
1481 OldMsg->getSuperLoc(),
1482 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1483 OldMsg->getSuperType(),
1484 OldMsg->getSelector(),
1486 OldMsg->getMethodDecl(),
1488 OldMsg->getRightLoc(),
1489 OldMsg->isImplicit());
1493 Stmt *Replacement = SynthMessageExpr(NewMsg);
1494 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1498 Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1499 SourceRange OldRange = PseudoOp->getSourceRange();
1501 // We just magically know some things about the structure of this
1503 ObjCMessageExpr *OldMsg =
1504 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1506 // Because the rewriter doesn't allow us to rewrite rewritten code,
1507 // we need to suppress rewriting the sub-statements.
1508 Expr *Base = nullptr;
1509 SmallVector<Expr*, 1> Args;
1511 DisableReplaceStmtScope S(*this);
1512 // Rebuild the base expression if we have one.
1513 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1514 Base = OldMsg->getInstanceReceiver();
1515 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1516 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1518 unsigned numArgs = OldMsg->getNumArgs();
1519 for (unsigned i = 0; i < numArgs; i++) {
1520 Expr *Arg = OldMsg->getArg(i);
1521 if (isa<OpaqueValueExpr>(Arg))
1522 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1523 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1524 Args.push_back(Arg);
1528 // Intentionally empty.
1529 SmallVector<SourceLocation, 1> SelLocs;
1531 ObjCMessageExpr *NewMsg = nullptr;
1532 switch (OldMsg->getReceiverKind()) {
1533 case ObjCMessageExpr::Class:
1534 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1535 OldMsg->getValueKind(),
1536 OldMsg->getLeftLoc(),
1537 OldMsg->getClassReceiverTypeInfo(),
1538 OldMsg->getSelector(),
1540 OldMsg->getMethodDecl(),
1542 OldMsg->getRightLoc(),
1543 OldMsg->isImplicit());
1546 case ObjCMessageExpr::Instance:
1547 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1548 OldMsg->getValueKind(),
1549 OldMsg->getLeftLoc(),
1551 OldMsg->getSelector(),
1553 OldMsg->getMethodDecl(),
1555 OldMsg->getRightLoc(),
1556 OldMsg->isImplicit());
1559 case ObjCMessageExpr::SuperClass:
1560 case ObjCMessageExpr::SuperInstance:
1561 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1562 OldMsg->getValueKind(),
1563 OldMsg->getLeftLoc(),
1564 OldMsg->getSuperLoc(),
1565 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1566 OldMsg->getSuperType(),
1567 OldMsg->getSelector(),
1569 OldMsg->getMethodDecl(),
1571 OldMsg->getRightLoc(),
1572 OldMsg->isImplicit());
1576 Stmt *Replacement = SynthMessageExpr(NewMsg);
1577 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1581 /// SynthCountByEnumWithState - To print:
1582 /// ((NSUInteger (*)
1583 /// (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
1584 /// (void *)objc_msgSend)((id)l_collection,
1585 /// sel_registerName(
1586 /// "countByEnumeratingWithState:objects:count:"),
1588 /// (id *)__rw_items, (NSUInteger)16)
1590 void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1591 buf += "((_WIN_NSUInteger (*) (id, SEL, struct __objcFastEnumerationState *, "
1592 "id *, _WIN_NSUInteger))(void *)objc_msgSend)";
1594 buf += "((id)l_collection,\n\t\t";
1595 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1597 buf += "&enumState, "
1598 "(id *)__rw_items, (_WIN_NSUInteger)16)";
1601 /// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1602 /// statement to exit to its outer synthesized loop.
1604 Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1605 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1607 // replace break with goto __break_label
1610 SourceLocation startLoc = S->getBeginLoc();
1611 buf = "goto __break_label_";
1612 buf += utostr(ObjCBcLabelNo.back());
1613 ReplaceText(startLoc, strlen("break"), buf);
1618 void RewriteModernObjC::ConvertSourceLocationToLineDirective(
1620 std::string &LineString) {
1621 if (Loc.isFileID() && GenerateLineInfo) {
1622 LineString += "\n#line ";
1623 PresumedLoc PLoc = SM->getPresumedLoc(Loc);
1624 LineString += utostr(PLoc.getLine());
1625 LineString += " \"";
1626 LineString += Lexer::Stringify(PLoc.getFilename());
1627 LineString += "\"\n";
1631 /// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1632 /// statement to continue with its inner synthesized loop.
1634 Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1635 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1637 // replace continue with goto __continue_label
1640 SourceLocation startLoc = S->getBeginLoc();
1641 buf = "goto __continue_label_";
1642 buf += utostr(ObjCBcLabelNo.back());
1643 ReplaceText(startLoc, strlen("continue"), buf);
1648 /// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1650 /// for ( type elem in collection) { stmts; }
1655 /// struct __objcFastEnumerationState enumState = { 0 };
1656 /// id __rw_items[16];
1657 /// id l_collection = (id)collection;
1658 /// NSUInteger limit = [l_collection countByEnumeratingWithState:&enumState
1659 /// objects:__rw_items count:16];
1661 /// unsigned long startMutations = *enumState.mutationsPtr;
1663 /// unsigned long counter = 0;
1665 /// if (startMutations != *enumState.mutationsPtr)
1666 /// objc_enumerationMutation(l_collection);
1667 /// elem = (type)enumState.itemsPtr[counter++];
1669 /// __continue_label: ;
1670 /// } while (counter < limit);
1671 /// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1672 /// objects:__rw_items count:16]));
1674 /// __break_label: ;
1680 Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1681 SourceLocation OrigEnd) {
1682 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1683 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1684 "ObjCForCollectionStmt Statement stack mismatch");
1685 assert(!ObjCBcLabelNo.empty() &&
1686 "ObjCForCollectionStmt - Label No stack empty");
1688 SourceLocation startLoc = S->getBeginLoc();
1689 const char *startBuf = SM->getCharacterData(startLoc);
1690 StringRef elementName;
1691 std::string elementTypeAsString;
1693 // line directive first.
1694 SourceLocation ForEachLoc = S->getForLoc();
1695 ConvertSourceLocationToLineDirective(ForEachLoc, buf);
1697 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1699 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1700 QualType ElementType = cast<ValueDecl>(D)->getType();
1701 if (ElementType->isObjCQualifiedIdType() ||
1702 ElementType->isObjCQualifiedInterfaceType())
1703 // Simply use 'id' for all qualified types.
1704 elementTypeAsString = "id";
1706 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1707 buf += elementTypeAsString;
1709 elementName = D->getName();
1714 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1715 elementName = DR->getDecl()->getName();
1716 ValueDecl *VD = DR->getDecl();
1717 if (VD->getType()->isObjCQualifiedIdType() ||
1718 VD->getType()->isObjCQualifiedInterfaceType())
1719 // Simply use 'id' for all qualified types.
1720 elementTypeAsString = "id";
1722 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1725 // struct __objcFastEnumerationState enumState = { 0 };
1726 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1727 // id __rw_items[16];
1728 buf += "id __rw_items[16];\n\t";
1729 // id l_collection = (id)
1730 buf += "id l_collection = (id)";
1731 // Find start location of 'collection' the hard way!
1732 const char *startCollectionBuf = startBuf;
1733 startCollectionBuf += 3; // skip 'for'
1734 startCollectionBuf = strchr(startCollectionBuf, '(');
1735 startCollectionBuf++; // skip '('
1736 // find 'in' and skip it.
1737 while (*startCollectionBuf != ' ' ||
1738 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1739 (*(startCollectionBuf+3) != ' ' &&
1740 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1741 startCollectionBuf++;
1742 startCollectionBuf += 3;
1744 // Replace: "for (type element in" with string constructed thus far.
1745 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1746 // Replace ')' in for '(' type elem in collection ')' with ';'
1747 SourceLocation rightParenLoc = S->getRParenLoc();
1748 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1749 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1752 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1753 // objects:__rw_items count:16];
1754 // which is synthesized into:
1755 // NSUInteger limit =
1757 // (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
1758 // (void *)objc_msgSend)((id)l_collection,
1759 // sel_registerName(
1760 // "countByEnumeratingWithState:objects:count:"),
1761 // (struct __objcFastEnumerationState *)&state,
1762 // (id *)__rw_items, (NSUInteger)16);
1763 buf += "_WIN_NSUInteger limit =\n\t\t";
1764 SynthCountByEnumWithState(buf);
1767 /// unsigned long startMutations = *enumState.mutationsPtr;
1769 /// unsigned long counter = 0;
1771 /// if (startMutations != *enumState.mutationsPtr)
1772 /// objc_enumerationMutation(l_collection);
1773 /// elem = (type)enumState.itemsPtr[counter++];
1774 buf += "if (limit) {\n\t";
1775 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1776 buf += "do {\n\t\t";
1777 buf += "unsigned long counter = 0;\n\t\t";
1778 buf += "do {\n\t\t\t";
1779 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1780 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1783 buf += elementTypeAsString;
1784 buf += ")enumState.itemsPtr[counter++];";
1785 // Replace ')' in for '(' type elem in collection ')' with all of these.
1786 ReplaceText(lparenLoc, 1, buf);
1788 /// __continue_label: ;
1789 /// } while (counter < limit);
1790 /// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1791 /// objects:__rw_items count:16]));
1793 /// __break_label: ;
1800 buf += "__continue_label_";
1801 buf += utostr(ObjCBcLabelNo.back());
1804 buf += "} while (counter < limit);\n\t";
1805 buf += "} while ((limit = ";
1806 SynthCountByEnumWithState(buf);
1810 buf += elementTypeAsString;
1812 buf += "__break_label_";
1813 buf += utostr(ObjCBcLabelNo.back());
1816 buf += "else\n\t\t";
1819 buf += elementTypeAsString;
1823 // Insert all these *after* the statement body.
1824 // FIXME: If this should support Obj-C++, support CXXTryStmt
1825 if (isa<CompoundStmt>(S->getBody())) {
1826 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1827 InsertText(endBodyLoc, buf);
1829 /* Need to treat single statements specially. For example:
1831 * for (A *a in b) if (stuff()) break;
1832 * for (A *a in b) xxxyy;
1834 * The following code simply scans ahead to the semi to find the actual end.
1836 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1837 const char *semiBuf = strchr(stmtBuf, ';');
1838 assert(semiBuf && "Can't find ';'");
1839 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1840 InsertText(endBodyLoc, buf);
1843 ObjCBcLabelNo.pop_back();
1847 static void Write_RethrowObject(std::string &buf) {
1848 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1849 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1850 buf += "\tid rethrow;\n";
1851 buf += "\t} _fin_force_rethow(_rethrow);";
1854 /// RewriteObjCSynchronizedStmt -
1855 /// This routine rewrites @synchronized(expr) stmt;
1857 /// objc_sync_enter(expr);
1858 /// @try stmt @finally { objc_sync_exit(expr); }
1860 Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1861 // Get the start location and compute the semi location.
1862 SourceLocation startLoc = S->getBeginLoc();
1863 const char *startBuf = SM->getCharacterData(startLoc);
1865 assert((*startBuf == '@') && "bogus @synchronized location");
1868 SourceLocation SynchLoc = S->getAtSynchronizedLoc();
1869 ConvertSourceLocationToLineDirective(SynchLoc, buf);
1870 buf += "{ id _rethrow = 0; id _sync_obj = (id)";
1872 const char *lparenBuf = startBuf;
1873 while (*lparenBuf != '(') lparenBuf++;
1874 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
1876 buf = "; objc_sync_enter(_sync_obj);\n";
1877 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1878 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1879 buf += "\n\tid sync_exit;";
1880 buf += "\n\t} _sync_exit(_sync_obj);\n";
1882 // We can't use S->getSynchExpr()->getEndLoc() to find the end location, since
1883 // the sync expression is typically a message expression that's already
1884 // been rewritten! (which implies the SourceLocation's are invalid).
1885 SourceLocation RParenExprLoc = S->getSynchBody()->getBeginLoc();
1886 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1887 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1888 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1890 SourceLocation LBranceLoc = S->getSynchBody()->getBeginLoc();
1891 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1892 assert (*LBraceLocBuf == '{');
1893 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
1895 SourceLocation startRBraceLoc = S->getSynchBody()->getEndLoc();
1896 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1897 "bogus @synchronized block");
1899 buf = "} catch (id e) {_rethrow = e;}\n";
1900 Write_RethrowObject(buf);
1904 ReplaceText(startRBraceLoc, 1, buf);
1909 void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1911 // Perform a bottom up traversal of all children.
1912 for (Stmt *SubStmt : S->children())
1914 WarnAboutReturnGotoStmts(SubStmt);
1916 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1917 Diags.Report(Context->getFullLoc(S->getBeginLoc()),
1918 TryFinallyContainsReturnDiag);
1922 Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
1923 SourceLocation startLoc = S->getAtLoc();
1924 ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
1925 ReplaceText(S->getSubStmt()->getBeginLoc(), 1,
1926 "{ __AtAutoreleasePool __autoreleasepool; ");
1931 Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
1932 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
1933 bool noCatch = S->getNumCatchStmts() == 0;
1935 SourceLocation TryLocation = S->getAtTryLoc();
1936 ConvertSourceLocationToLineDirective(TryLocation, buf);
1940 buf += "{ id volatile _rethrow = 0;\n";
1942 buf += "{ id volatile _rethrow = 0;\ntry {\n";
1945 // Get the start location and compute the semi location.
1946 SourceLocation startLoc = S->getBeginLoc();
1947 const char *startBuf = SM->getCharacterData(startLoc);
1949 assert((*startBuf == '@') && "bogus @try location");
1951 ReplaceText(startLoc, 1, buf);
1954 ReplaceText(startLoc, 1, "");
1956 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1957 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
1958 VarDecl *catchDecl = Catch->getCatchParamDecl();
1960 startLoc = Catch->getBeginLoc();
1961 bool AtRemoved = false;
1963 QualType t = catchDecl->getType();
1964 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1965 // Should be a pointer to a class.
1966 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1969 ConvertSourceLocationToLineDirective(Catch->getBeginLoc(), Result);
1971 startBuf = SM->getCharacterData(startLoc);
1972 assert((*startBuf == '@') && "bogus @catch location");
1973 SourceLocation rParenLoc = Catch->getRParenLoc();
1974 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1976 // _objc_exc_Foo *_e as argument to catch.
1977 Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString();
1978 Result += " *_"; Result += catchDecl->getNameAsString();
1980 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1981 // Foo *e = (Foo *)_e;
1984 Result += IDecl->getNameAsString();
1985 Result += " *"; Result += catchDecl->getNameAsString();
1986 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1987 Result += "_"; Result += catchDecl->getNameAsString();
1990 SourceLocation lBraceLoc = Catch->getCatchBody()->getBeginLoc();
1991 ReplaceText(lBraceLoc, 1, Result);
1998 ReplaceText(startLoc, 1, "");
2003 SourceLocation FinallyLoc = finalStmt->getBeginLoc();
2006 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2007 buf += "catch (id e) {_rethrow = e;}\n";
2011 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2012 buf += "catch (id e) {_rethrow = e;}\n";
2015 SourceLocation startFinalLoc = finalStmt->getBeginLoc();
2016 ReplaceText(startFinalLoc, 8, buf);
2017 Stmt *body = finalStmt->getFinallyBody();
2018 SourceLocation startFinalBodyLoc = body->getBeginLoc();
2020 Write_RethrowObject(buf);
2021 ReplaceText(startFinalBodyLoc, 1, buf);
2023 SourceLocation endFinalBodyLoc = body->getEndLoc();
2024 ReplaceText(endFinalBodyLoc, 1, "}\n}");
2025 // Now check for any return/continue/go statements within the @try.
2026 WarnAboutReturnGotoStmts(S->getTryBody());
2032 // This can't be done with ReplaceStmt(S, ThrowExpr), since
2033 // the throw expression is typically a message expression that's already
2034 // been rewritten! (which implies the SourceLocation's are invalid).
2035 Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
2036 // Get the start location and compute the semi location.
2037 SourceLocation startLoc = S->getBeginLoc();
2038 const char *startBuf = SM->getCharacterData(startLoc);
2040 assert((*startBuf == '@') && "bogus @throw location");
2043 /* void objc_exception_throw(id) __attribute__((noreturn)); */
2044 if (S->getThrowExpr())
2045 buf = "objc_exception_throw(";
2049 // handle "@ throw" correctly.
2050 const char *wBuf = strchr(startBuf, 'w');
2051 assert((*wBuf == 'w') && "@throw: can't find 'w'");
2052 ReplaceText(startLoc, wBuf-startBuf+1, buf);
2054 SourceLocation endLoc = S->getEndLoc();
2055 const char *endBuf = SM->getCharacterData(endLoc);
2056 const char *semiBuf = strchr(endBuf, ';');
2057 assert((*semiBuf == ';') && "@throw: can't find ';'");
2058 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
2059 if (S->getThrowExpr())
2060 ReplaceText(semiLoc, 1, ");");
2064 Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2065 // Create a new string expression.
2066 std::string StrEncoding;
2067 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
2068 Expr *Replacement = getStringLiteral(StrEncoding);
2069 ReplaceStmt(Exp, Replacement);
2071 // Replace this subexpr in the parent.
2072 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2076 Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2077 if (!SelGetUidFunctionDecl)
2078 SynthSelGetUidFunctionDecl();
2079 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2080 // Create a call to sel_registerName("selName").
2081 SmallVector<Expr*, 8> SelExprs;
2082 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
2083 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2085 ReplaceStmt(Exp, SelExp);
2086 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2091 RewriteModernObjC::SynthesizeCallToFunctionDecl(FunctionDecl *FD,
2092 ArrayRef<Expr *> Args,
2093 SourceLocation StartLoc,
2094 SourceLocation EndLoc) {
2095 // Get the type, we will need to reference it in a couple spots.
2096 QualType msgSendType = FD->getType();
2098 // Create a reference to the objc_msgSend() declaration.
2099 DeclRefExpr *DRE = new (Context) DeclRefExpr(*Context, FD, false, msgSendType,
2100 VK_LValue, SourceLocation());
2102 // Now, we cast the reference to a pointer to the objc_msgSend type.
2103 QualType pToFunc = Context->getPointerType(msgSendType);
2104 ImplicitCastExpr *ICE =
2105 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2106 DRE, nullptr, VK_RValue);
2108 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2110 CallExpr *Exp = CallExpr::Create(
2111 *Context, ICE, Args, FT->getCallResultType(*Context), VK_RValue, EndLoc);
2115 static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2116 const char *&startRef, const char *&endRef) {
2117 while (startBuf < endBuf) {
2118 if (*startBuf == '<')
2119 startRef = startBuf; // mark the start.
2120 if (*startBuf == '>') {
2121 if (startRef && *startRef == '<') {
2122 endRef = startBuf; // mark the end.
2132 static void scanToNextArgument(const char *&argRef) {
2134 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2137 else if (*argRef == '>')
2141 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2144 bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2145 if (T->isObjCQualifiedIdType())
2147 if (const PointerType *PT = T->getAs<PointerType>()) {
2148 if (PT->getPointeeType()->isObjCQualifiedIdType())
2151 if (T->isObjCObjectPointerType()) {
2152 T = T->getPointeeType();
2153 return T->isObjCQualifiedInterfaceType();
2155 if (T->isArrayType()) {
2156 QualType ElemTy = Context->getBaseElementType(T);
2157 return needToScanForQualifiers(ElemTy);
2162 void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2163 QualType Type = E->getType();
2164 if (needToScanForQualifiers(Type)) {
2165 SourceLocation Loc, EndLoc;
2167 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2168 Loc = ECE->getLParenLoc();
2169 EndLoc = ECE->getRParenLoc();
2171 Loc = E->getBeginLoc();
2172 EndLoc = E->getEndLoc();
2174 // This will defend against trying to rewrite synthesized expressions.
2175 if (Loc.isInvalid() || EndLoc.isInvalid())
2178 const char *startBuf = SM->getCharacterData(Loc);
2179 const char *endBuf = SM->getCharacterData(EndLoc);
2180 const char *startRef = nullptr, *endRef = nullptr;
2181 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2182 // Get the locations of the startRef, endRef.
2183 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2184 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2185 // Comment out the protocol references.
2186 InsertText(LessLoc, "/*");
2187 InsertText(GreaterLoc, "*/");
2192 void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2195 const FunctionProtoType *proto = nullptr;
2196 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2197 Loc = VD->getLocation();
2198 Type = VD->getType();
2200 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2201 Loc = FD->getLocation();
2202 // Check for ObjC 'id' and class types that have been adorned with protocol
2203 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2204 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2205 assert(funcType && "missing function type");
2206 proto = dyn_cast<FunctionProtoType>(funcType);
2209 Type = proto->getReturnType();
2211 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2212 Loc = FD->getLocation();
2213 Type = FD->getType();
2215 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Dcl)) {
2216 Loc = TD->getLocation();
2217 Type = TD->getUnderlyingType();
2222 if (needToScanForQualifiers(Type)) {
2223 // Since types are unique, we need to scan the buffer.
2225 const char *endBuf = SM->getCharacterData(Loc);
2226 const char *startBuf = endBuf;
2227 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2228 startBuf--; // scan backward (from the decl location) for return type.
2229 const char *startRef = nullptr, *endRef = nullptr;
2230 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2231 // Get the locations of the startRef, endRef.
2232 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2233 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2234 // Comment out the protocol references.
2235 InsertText(LessLoc, "/*");
2236 InsertText(GreaterLoc, "*/");
2240 return; // most likely, was a variable
2241 // Now check arguments.
2242 const char *startBuf = SM->getCharacterData(Loc);
2243 const char *startFuncBuf = startBuf;
2244 for (unsigned i = 0; i < proto->getNumParams(); i++) {
2245 if (needToScanForQualifiers(proto->getParamType(i))) {
2246 // Since types are unique, we need to scan the buffer.
2248 const char *endBuf = startBuf;
2249 // scan forward (from the decl location) for argument types.
2250 scanToNextArgument(endBuf);
2251 const char *startRef = nullptr, *endRef = nullptr;
2252 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2253 // Get the locations of the startRef, endRef.
2254 SourceLocation LessLoc =
2255 Loc.getLocWithOffset(startRef-startFuncBuf);
2256 SourceLocation GreaterLoc =
2257 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2258 // Comment out the protocol references.
2259 InsertText(LessLoc, "/*");
2260 InsertText(GreaterLoc, "*/");
2262 startBuf = ++endBuf;
2265 // If the function name is derived from a macro expansion, then the
2266 // argument buffer will not follow the name. Need to speak with Chris.
2267 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2268 startBuf++; // scan forward (from the decl location) for argument types.
2274 void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2275 QualType QT = ND->getType();
2276 const Type* TypePtr = QT->getAs<Type>();
2277 if (!isa<TypeOfExprType>(TypePtr))
2279 while (isa<TypeOfExprType>(TypePtr)) {
2280 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2281 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2282 TypePtr = QT->getAs<Type>();
2284 // FIXME. This will not work for multiple declarators; as in:
2285 // __typeof__(a) b,c,d;
2286 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2287 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2288 const char *startBuf = SM->getCharacterData(DeclLoc);
2289 if (ND->getInit()) {
2290 std::string Name(ND->getNameAsString());
2291 TypeAsString += " " + Name + " = ";
2292 Expr *E = ND->getInit();
2293 SourceLocation startLoc;
2294 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2295 startLoc = ECE->getLParenLoc();
2297 startLoc = E->getBeginLoc();
2298 startLoc = SM->getExpansionLoc(startLoc);
2299 const char *endBuf = SM->getCharacterData(startLoc);
2300 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2303 SourceLocation X = ND->getEndLoc();
2304 X = SM->getExpansionLoc(X);
2305 const char *endBuf = SM->getCharacterData(X);
2306 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2310 // SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2311 void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2312 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2313 SmallVector<QualType, 16> ArgTys;
2314 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2315 QualType getFuncType =
2316 getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
2317 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2320 SelGetUidIdent, getFuncType,
2321 nullptr, SC_Extern);
2324 void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2325 // declared in <objc/objc.h>
2326 if (FD->getIdentifier() &&
2327 FD->getName() == "sel_registerName") {
2328 SelGetUidFunctionDecl = FD;
2331 RewriteObjCQualifiedInterfaceTypes(FD);
2334 void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2335 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2336 const char *argPtr = TypeString.c_str();
2337 if (!strchr(argPtr, '^')) {
2342 Str += (*argPtr == '^' ? '*' : *argPtr);
2347 // FIXME. Consolidate this routine with RewriteBlockPointerType.
2348 void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2350 QualType Type = VD->getType();
2351 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2352 const char *argPtr = TypeString.c_str();
2367 Str += VD->getNameAsString();
2377 void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2378 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2379 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2380 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2383 QualType Type = proto->getReturnType();
2384 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2386 FdStr += FD->getName();
2388 unsigned numArgs = proto->getNumParams();
2389 for (unsigned i = 0; i < numArgs; i++) {
2390 QualType ArgType = proto->getParamType(i);
2391 RewriteBlockPointerType(FdStr, ArgType);
2395 if (FD->isVariadic()) {
2396 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2400 InsertText(FunLocStart, FdStr);
2403 // SynthSuperConstructorFunctionDecl - id __rw_objc_super(id obj, id super);
2404 void RewriteModernObjC::SynthSuperConstructorFunctionDecl() {
2405 if (SuperConstructorFunctionDecl)
2407 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2408 SmallVector<QualType, 16> ArgTys;
2409 QualType argT = Context->getObjCIdType();
2410 assert(!argT.isNull() && "Can't find 'id' type");
2411 ArgTys.push_back(argT);
2412 ArgTys.push_back(argT);
2413 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2415 SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2418 msgSendIdent, msgSendType,
2419 nullptr, SC_Extern);
2422 // SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2423 void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2424 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2425 SmallVector<QualType, 16> ArgTys;
2426 QualType argT = Context->getObjCIdType();
2427 assert(!argT.isNull() && "Can't find 'id' type");
2428 ArgTys.push_back(argT);
2429 argT = Context->getObjCSelType();
2430 assert(!argT.isNull() && "Can't find 'SEL' type");
2431 ArgTys.push_back(argT);
2432 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2433 ArgTys, /*isVariadic=*/true);
2434 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2437 msgSendIdent, msgSendType, nullptr,
2441 // SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
2442 void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2443 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2444 SmallVector<QualType, 2> ArgTys;
2445 ArgTys.push_back(Context->VoidTy);
2446 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2447 ArgTys, /*isVariadic=*/true);
2448 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2451 msgSendIdent, msgSendType,
2452 nullptr, SC_Extern);
2455 // SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2456 void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2457 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2458 SmallVector<QualType, 16> ArgTys;
2459 QualType argT = Context->getObjCIdType();
2460 assert(!argT.isNull() && "Can't find 'id' type");
2461 ArgTys.push_back(argT);
2462 argT = Context->getObjCSelType();
2463 assert(!argT.isNull() && "Can't find 'SEL' type");
2464 ArgTys.push_back(argT);
2465 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2466 ArgTys, /*isVariadic=*/true);
2467 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2470 msgSendIdent, msgSendType,
2471 nullptr, SC_Extern);
2474 // SynthMsgSendSuperStretFunctionDecl -
2475 // id objc_msgSendSuper_stret(void);
2476 void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2477 IdentifierInfo *msgSendIdent =
2478 &Context->Idents.get("objc_msgSendSuper_stret");
2479 SmallVector<QualType, 2> ArgTys;
2480 ArgTys.push_back(Context->VoidTy);
2481 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2482 ArgTys, /*isVariadic=*/true);
2483 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2487 msgSendType, nullptr,
2491 // SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2492 void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2493 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2494 SmallVector<QualType, 16> ArgTys;
2495 QualType argT = Context->getObjCIdType();
2496 assert(!argT.isNull() && "Can't find 'id' type");
2497 ArgTys.push_back(argT);
2498 argT = Context->getObjCSelType();
2499 assert(!argT.isNull() && "Can't find 'SEL' type");
2500 ArgTys.push_back(argT);
2501 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2502 ArgTys, /*isVariadic=*/true);
2503 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2506 msgSendIdent, msgSendType,
2507 nullptr, SC_Extern);
2510 // SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
2511 void RewriteModernObjC::SynthGetClassFunctionDecl() {
2512 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2513 SmallVector<QualType, 16> ArgTys;
2514 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2515 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2517 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2520 getClassIdent, getClassType,
2521 nullptr, SC_Extern);
2524 // SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2525 void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2526 IdentifierInfo *getSuperClassIdent =
2527 &Context->Idents.get("class_getSuperclass");
2528 SmallVector<QualType, 16> ArgTys;
2529 ArgTys.push_back(Context->getObjCClassType());
2530 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2532 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2536 getClassType, nullptr,
2540 // SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
2541 void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2542 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2543 SmallVector<QualType, 16> ArgTys;
2544 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2545 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2547 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2550 getClassIdent, getClassType,
2551 nullptr, SC_Extern);
2554 Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2555 assert (Exp != nullptr && "Expected non-null ObjCStringLiteral");
2556 QualType strType = getConstantStringStructType();
2558 std::string S = "__NSConstantStringImpl_";
2560 std::string tmpName = InFileName;
2562 for (i=0; i < tmpName.length(); i++) {
2563 char c = tmpName.at(i);
2564 // replace any non-alphanumeric characters with '_'.
2565 if (!isAlphanumeric(c))
2570 S += utostr(NumObjCStringLiterals++);
2572 Preamble += "static __NSConstantStringImpl " + S;
2573 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2574 Preamble += "0x000007c8,"; // utf8_str
2575 // The pretty printer for StringLiteral handles escape characters properly.
2576 std::string prettyBufS;
2577 llvm::raw_string_ostream prettyBuf(prettyBufS);
2578 Exp->getString()->printPretty(prettyBuf, nullptr, PrintingPolicy(LangOpts));
2579 Preamble += prettyBuf.str();
2581 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2583 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2584 SourceLocation(), &Context->Idents.get(S),
2585 strType, nullptr, SC_Static);
2586 DeclRefExpr *DRE = new (Context)
2587 DeclRefExpr(*Context, NewVD, false, strType, VK_LValue, SourceLocation());
2588 Expr *Unop = new (Context)
2589 UnaryOperator(DRE, UO_AddrOf, Context->getPointerType(DRE->getType()),
2590 VK_RValue, OK_Ordinary, SourceLocation(), false);
2591 // cast to NSConstantString *
2592 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2593 CK_CPointerToObjCPointerCast, Unop);
2594 ReplaceStmt(Exp, cast);
2595 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2599 Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2601 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2603 Expr *FlagExp = IntegerLiteral::Create(*Context,
2604 llvm::APInt(IntSize, Exp->getValue()),
2605 Context->IntTy, Exp->getLocation());
2606 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2607 CK_BitCast, FlagExp);
2608 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2610 ReplaceStmt(Exp, PE);
2614 Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
2615 // synthesize declaration of helper functions needed in this routine.
2616 if (!SelGetUidFunctionDecl)
2617 SynthSelGetUidFunctionDecl();
2618 // use objc_msgSend() for all.
2619 if (!MsgSendFunctionDecl)
2620 SynthMsgSendFunctionDecl();
2621 if (!GetClassFunctionDecl)
2622 SynthGetClassFunctionDecl();
2624 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2625 SourceLocation StartLoc = Exp->getBeginLoc();
2626 SourceLocation EndLoc = Exp->getEndLoc();
2628 // Synthesize a call to objc_msgSend().
2629 SmallVector<Expr*, 4> MsgExprs;
2630 SmallVector<Expr*, 4> ClsExprs;
2632 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2633 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2634 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
2636 IdentifierInfo *clsName = BoxingClass->getIdentifier();
2637 ClsExprs.push_back(getStringLiteral(clsName->getName()));
2638 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
2640 MsgExprs.push_back(Cls);
2642 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
2643 // it will be the 2nd argument.
2644 SmallVector<Expr*, 4> SelExprs;
2646 getStringLiteral(BoxingMethod->getSelector().getAsString()));
2647 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2648 SelExprs, StartLoc, EndLoc);
2649 MsgExprs.push_back(SelExp);
2651 // User provided sub-expression is the 3rd, and last, argument.
2652 Expr *subExpr = Exp->getSubExpr();
2653 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
2654 QualType type = ICE->getType();
2655 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2656 CastKind CK = CK_BitCast;
2657 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2658 CK = CK_IntegralToBoolean;
2659 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
2661 MsgExprs.push_back(subExpr);
2663 SmallVector<QualType, 4> ArgTypes;
2664 ArgTypes.push_back(Context->getObjCClassType());
2665 ArgTypes.push_back(Context->getObjCSelType());
2666 for (const auto PI : BoxingMethod->parameters())
2667 ArgTypes.push_back(PI->getType());
2669 QualType returnType = Exp->getType();
2670 // Get the type, we will need to reference it in a couple spots.
2671 QualType msgSendType = MsgSendFlavor->getType();
2673 // Create a reference to the objc_msgSend() declaration.
2674 DeclRefExpr *DRE = new (Context) DeclRefExpr(
2675 *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
2677 CastExpr *cast = NoTypeInfoCStyleCastExpr(
2678 Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE);
2680 // Now do the "normal" pointer to function cast.
2682 getSimpleFunctionType(returnType, ArgTypes, BoxingMethod->isVariadic());
2683 castType = Context->getPointerType(castType);
2684 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2687 // Don't forget the parens to enforce the proper binding.
2688 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2690 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2691 CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
2693 ReplaceStmt(Exp, CE);
2697 Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2698 // synthesize declaration of helper functions needed in this routine.
2699 if (!SelGetUidFunctionDecl)
2700 SynthSelGetUidFunctionDecl();
2701 // use objc_msgSend() for all.
2702 if (!MsgSendFunctionDecl)
2703 SynthMsgSendFunctionDecl();
2704 if (!GetClassFunctionDecl)
2705 SynthGetClassFunctionDecl();
2707 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2708 SourceLocation StartLoc = Exp->getBeginLoc();
2709 SourceLocation EndLoc = Exp->getEndLoc();
2711 // Build the expression: __NSContainer_literal(int, ...).arr
2712 QualType IntQT = Context->IntTy;
2713 QualType NSArrayFType =
2714 getSimpleFunctionType(Context->VoidTy, IntQT, true);
2715 std::string NSArrayFName("__NSContainer_literal");
2716 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2717 DeclRefExpr *NSArrayDRE = new (Context) DeclRefExpr(
2718 *Context, NSArrayFD, false, NSArrayFType, VK_RValue, SourceLocation());
2720 SmallVector<Expr*, 16> InitExprs;
2721 unsigned NumElements = Exp->getNumElements();
2722 unsigned UnsignedIntSize =
2723 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2724 Expr *count = IntegerLiteral::Create(*Context,
2725 llvm::APInt(UnsignedIntSize, NumElements),
2726 Context->UnsignedIntTy, SourceLocation());
2727 InitExprs.push_back(count);
2728 for (unsigned i = 0; i < NumElements; i++)
2729 InitExprs.push_back(Exp->getElement(i));
2730 Expr *NSArrayCallExpr =
2731 CallExpr::Create(*Context, NSArrayDRE, InitExprs, NSArrayFType, VK_LValue,
2734 FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
2736 &Context->Idents.get("arr"),
2737 Context->getPointerType(Context->VoidPtrTy),
2738 nullptr, /*BitWidth=*/nullptr,
2739 /*Mutable=*/true, ICIS_NoInit);
2740 MemberExpr *ArrayLiteralME = new (Context)
2741 MemberExpr(NSArrayCallExpr, false, SourceLocation(), ARRFD,
2742 SourceLocation(), ARRFD->getType(), VK_LValue, OK_Ordinary);
2743 QualType ConstIdT = Context->getObjCIdType().withConst();
2744 CStyleCastExpr * ArrayLiteralObjects =
2745 NoTypeInfoCStyleCastExpr(Context,
2746 Context->getPointerType(ConstIdT),
2750 // Synthesize a call to objc_msgSend().
2751 SmallVector<Expr*, 32> MsgExprs;
2752 SmallVector<Expr*, 4> ClsExprs;
2753 QualType expType = Exp->getType();
2755 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2756 ObjCInterfaceDecl *Class =
2757 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2759 IdentifierInfo *clsName = Class->getIdentifier();
2760 ClsExprs.push_back(getStringLiteral(clsName->getName()));
2761 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
2763 MsgExprs.push_back(Cls);
2765 // Create a call to sel_registerName("arrayWithObjects:count:").
2766 // it will be the 2nd argument.
2767 SmallVector<Expr*, 4> SelExprs;
2768 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
2770 getStringLiteral(ArrayMethod->getSelector().getAsString()));
2771 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2772 SelExprs, StartLoc, EndLoc);
2773 MsgExprs.push_back(SelExp);
2775 // (const id [])objects
2776 MsgExprs.push_back(ArrayLiteralObjects);
2779 Expr *cnt = IntegerLiteral::Create(*Context,
2780 llvm::APInt(UnsignedIntSize, NumElements),
2781 Context->UnsignedIntTy, SourceLocation());
2782 MsgExprs.push_back(cnt);
2784 SmallVector<QualType, 4> ArgTypes;
2785 ArgTypes.push_back(Context->getObjCClassType());
2786 ArgTypes.push_back(Context->getObjCSelType());
2787 for (const auto *PI : ArrayMethod->parameters())
2788 ArgTypes.push_back(PI->getType());
2790 QualType returnType = Exp->getType();
2791 // Get the type, we will need to reference it in a couple spots.
2792 QualType msgSendType = MsgSendFlavor->getType();
2794 // Create a reference to the objc_msgSend() declaration.
2795 DeclRefExpr *DRE = new (Context) DeclRefExpr(
2796 *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
2798 CastExpr *cast = NoTypeInfoCStyleCastExpr(
2799 Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE);
2801 // Now do the "normal" pointer to function cast.
2803 getSimpleFunctionType(returnType, ArgTypes, ArrayMethod->isVariadic());
2804 castType = Context->getPointerType(castType);
2805 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2808 // Don't forget the parens to enforce the proper binding.
2809 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2811 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2812 CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
2814 ReplaceStmt(Exp, CE);
2818 Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2819 // synthesize declaration of helper functions needed in this routine.
2820 if (!SelGetUidFunctionDecl)
2821 SynthSelGetUidFunctionDecl();
2822 // use objc_msgSend() for all.
2823 if (!MsgSendFunctionDecl)
2824 SynthMsgSendFunctionDecl();
2825 if (!GetClassFunctionDecl)
2826 SynthGetClassFunctionDecl();
2828 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2829 SourceLocation StartLoc = Exp->getBeginLoc();
2830 SourceLocation EndLoc = Exp->getEndLoc();
2832 // Build the expression: __NSContainer_literal(int, ...).arr
2833 QualType IntQT = Context->IntTy;
2834 QualType NSDictFType =
2835 getSimpleFunctionType(Context->VoidTy, IntQT, true);
2836 std::string NSDictFName("__NSContainer_literal");
2837 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2838 DeclRefExpr *NSDictDRE = new (Context) DeclRefExpr(
2839 *Context, NSDictFD, false, NSDictFType, VK_RValue, SourceLocation());
2841 SmallVector<Expr*, 16> KeyExprs;
2842 SmallVector<Expr*, 16> ValueExprs;
2844 unsigned NumElements = Exp->getNumElements();
2845 unsigned UnsignedIntSize =
2846 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2847 Expr *count = IntegerLiteral::Create(*Context,
2848 llvm::APInt(UnsignedIntSize, NumElements),
2849 Context->UnsignedIntTy, SourceLocation());
2850 KeyExprs.push_back(count);
2851 ValueExprs.push_back(count);
2852 for (unsigned i = 0; i < NumElements; i++) {
2853 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2854 KeyExprs.push_back(Element.Key);
2855 ValueExprs.push_back(Element.Value);
2858 // (const id [])objects
2859 Expr *NSValueCallExpr =
2860 CallExpr::Create(*Context, NSDictDRE, ValueExprs, NSDictFType, VK_LValue,
2863 FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
2865 &Context->Idents.get("arr"),
2866 Context->getPointerType(Context->VoidPtrTy),
2867 nullptr, /*BitWidth=*/nullptr,
2868 /*Mutable=*/true, ICIS_NoInit);
2869 MemberExpr *DictLiteralValueME = new (Context)
2870 MemberExpr(NSValueCallExpr, false, SourceLocation(), ARRFD,
2871 SourceLocation(), ARRFD->getType(), VK_LValue, OK_Ordinary);
2872 QualType ConstIdT = Context->getObjCIdType().withConst();
2873 CStyleCastExpr * DictValueObjects =
2874 NoTypeInfoCStyleCastExpr(Context,
2875 Context->getPointerType(ConstIdT),
2877 DictLiteralValueME);
2878 // (const id <NSCopying> [])keys
2879 Expr *NSKeyCallExpr = CallExpr::Create(
2880 *Context, NSDictDRE, KeyExprs, NSDictFType, VK_LValue, SourceLocation());
2882 MemberExpr *DictLiteralKeyME = new (Context)
2883 MemberExpr(NSKeyCallExpr, false, SourceLocation(), ARRFD,
2884 SourceLocation(), ARRFD->getType(), VK_LValue, OK_Ordinary);
2886 CStyleCastExpr * DictKeyObjects =
2887 NoTypeInfoCStyleCastExpr(Context,
2888 Context->getPointerType(ConstIdT),
2892 // Synthesize a call to objc_msgSend().
2893 SmallVector<Expr*, 32> MsgExprs;
2894 SmallVector<Expr*, 4> ClsExprs;
2895 QualType expType = Exp->getType();
2897 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2898 ObjCInterfaceDecl *Class =
2899 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2901 IdentifierInfo *clsName = Class->getIdentifier();
2902 ClsExprs.push_back(getStringLiteral(clsName->getName()));
2903 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
2905 MsgExprs.push_back(Cls);
2907 // Create a call to sel_registerName("arrayWithObjects:count:").
2908 // it will be the 2nd argument.
2909 SmallVector<Expr*, 4> SelExprs;
2910 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
2911 SelExprs.push_back(getStringLiteral(DictMethod->getSelector().getAsString()));
2912 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2913 SelExprs, StartLoc, EndLoc);
2914 MsgExprs.push_back(SelExp);
2916 // (const id [])objects
2917 MsgExprs.push_back(DictValueObjects);
2919 // (const id <NSCopying> [])keys
2920 MsgExprs.push_back(DictKeyObjects);
2923 Expr *cnt = IntegerLiteral::Create(*Context,
2924 llvm::APInt(UnsignedIntSize, NumElements),
2925 Context->UnsignedIntTy, SourceLocation());
2926 MsgExprs.push_back(cnt);
2928 SmallVector<QualType, 8> ArgTypes;
2929 ArgTypes.push_back(Context->getObjCClassType());
2930 ArgTypes.push_back(Context->getObjCSelType());
2931 for (const auto *PI : DictMethod->parameters()) {
2932 QualType T = PI->getType();
2933 if (const PointerType* PT = T->getAs<PointerType>()) {
2934 QualType PointeeTy = PT->getPointeeType();
2935 convertToUnqualifiedObjCType(PointeeTy);
2936 T = Context->getPointerType(PointeeTy);
2938 ArgTypes.push_back(T);
2941 QualType returnType = Exp->getType();
2942 // Get the type, we will need to reference it in a couple spots.
2943 QualType msgSendType = MsgSendFlavor->getType();
2945 // Create a reference to the objc_msgSend() declaration.
2946 DeclRefExpr *DRE = new (Context) DeclRefExpr(
2947 *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
2949 CastExpr *cast = NoTypeInfoCStyleCastExpr(
2950 Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE);
2952 // Now do the "normal" pointer to function cast.
2954 getSimpleFunctionType(returnType, ArgTypes, DictMethod->isVariadic());
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 = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
2965 ReplaceStmt(Exp, CE);
2969 // struct __rw_objc_super {
2970 // struct objc_object *object; struct objc_object *superClass;
2972 QualType RewriteModernObjC::getSuperStructType() {
2973 if (!SuperStructDecl) {
2974 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2975 SourceLocation(), SourceLocation(),
2976 &Context->Idents.get("__rw_objc_super"));
2977 QualType FieldTypes[2];
2979 // struct objc_object *object;
2980 FieldTypes[0] = Context->getObjCIdType();
2981 // struct objc_object *superClass;
2982 FieldTypes[1] = Context->getObjCIdType();
2985 for (unsigned i = 0; i < 2; ++i) {
2986 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2988 SourceLocation(), nullptr,
2989 FieldTypes[i], nullptr,
2990 /*BitWidth=*/nullptr,
2995 SuperStructDecl->completeDefinition();
2997 return Context->getTagDeclType(SuperStructDecl);
3000 QualType RewriteModernObjC::getConstantStringStructType() {
3001 if (!ConstantStringDecl) {
3002 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3003 SourceLocation(), SourceLocation(),
3004 &Context->Idents.get("__NSConstantStringImpl"));
3005 QualType FieldTypes[4];
3007 // struct objc_object *receiver;
3008 FieldTypes[0] = Context->getObjCIdType();
3010 FieldTypes[1] = Context->IntTy;
3012 FieldTypes[2] = Context->getPointerType(Context->CharTy);
3014 FieldTypes[3] = Context->LongTy;
3017 for (unsigned i = 0; i < 4; ++i) {
3018 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3021 SourceLocation(), nullptr,
3022 FieldTypes[i], nullptr,
3023 /*BitWidth=*/nullptr,
3028 ConstantStringDecl->completeDefinition();
3030 return Context->getTagDeclType(ConstantStringDecl);
3033 /// getFunctionSourceLocation - returns start location of a function
3034 /// definition. Complication arises when function has declared as
3035 /// extern "C" or extern "C" {...}
3036 static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3038 if (FD->isExternC() && !FD->isMain()) {
3039 const DeclContext *DC = FD->getDeclContext();
3040 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3041 // if it is extern "C" {...}, return function decl's own location.
3042 if (!LSD->getRBraceLoc().isValid())
3043 return LSD->getExternLoc();
3045 if (FD->getStorageClass() != SC_None)
3046 R.RewriteBlockLiteralFunctionDecl(FD);
3047 return FD->getTypeSpecStartLoc();
3050 void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
3052 SourceLocation Location = D->getLocation();
3054 if (Location.isFileID() && GenerateLineInfo) {
3055 std::string LineString("\n#line ");
3056 PresumedLoc PLoc = SM->getPresumedLoc(Location);
3057 LineString += utostr(PLoc.getLine());
3058 LineString += " \"";
3059 LineString += Lexer::Stringify(PLoc.getFilename());
3060 if (isa<ObjCMethodDecl>(D))
3062 else LineString += "\"\n";
3064 Location = D->getBeginLoc();
3065 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3066 if (FD->isExternC() && !FD->isMain()) {
3067 const DeclContext *DC = FD->getDeclContext();
3068 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3069 // if it is extern "C" {...}, return function decl's own location.
3070 if (!LSD->getRBraceLoc().isValid())
3071 Location = LSD->getExternLoc();
3074 InsertText(Location, LineString);
3078 /// SynthMsgSendStretCallExpr - This routine translates message expression
3079 /// into a call to objc_msgSend_stret() entry point. Tricky part is that
3080 /// nil check on receiver must be performed before calling objc_msgSend_stret.
3081 /// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3082 /// msgSendType - function type of objc_msgSend_stret(...)
3083 /// returnType - Result type of the method being synthesized.
3084 /// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
3085 /// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
3086 /// starting with receiver.
3087 /// Method - Method being rewritten.
3088 Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
3089 QualType returnType,
3090 SmallVectorImpl<QualType> &ArgTypes,
3091 SmallVectorImpl<Expr*> &MsgExprs,
3092 ObjCMethodDecl *Method) {
3093 // Now do the "normal" pointer to function cast.
3094 QualType FuncType = getSimpleFunctionType(
3095 returnType, ArgTypes, Method ? Method->isVariadic() : false);
3096 QualType castType = Context->getPointerType(FuncType);
3098 // build type for containing the objc_msgSend_stret object.
3099 static unsigned stretCount=0;
3100 std::string name = "__Stret"; name += utostr(stretCount);
3102 "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
3103 str += "namespace {\n";
3104 str += "struct "; str += name;
3107 str += "(id receiver, SEL sel";
3108 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3109 std::string ArgName = "arg"; ArgName += utostr(i);
3110 ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3111 str += ", "; str += ArgName;
3114 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3115 std::string ArgName = "arg"; ArgName += utostr(i);
3116 MsgExprs[i]->getType().getAsStringInternal(ArgName,
3117 Context->getPrintingPolicy());
3118 str += ", "; str += ArgName;
3122 str += "\t unsigned size = sizeof(";
3123 str += returnType.getAsString(Context->getPrintingPolicy()); str += ");\n";
3125 str += "\t if (size == 1 || size == 2 || size == 4 || size == 8)\n";
3127 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3128 str += ")(void *)objc_msgSend)(receiver, sel";
3129 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3130 str += ", arg"; str += utostr(i);
3133 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3134 str += ", arg"; str += utostr(i);
3138 str += "\t else if (receiver == 0)\n";
3139 str += "\t memset((void*)&s, 0, sizeof(s));\n";
3142 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3143 str += ")(void *)objc_msgSend_stret)(receiver, sel";
3144 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3145 str += ", arg"; str += utostr(i);
3148 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3149 str += ", arg"; str += utostr(i);
3154 str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3156 str += "};\n};\n\n";
3157 SourceLocation FunLocStart;
3159 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3161 assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
3162 FunLocStart = CurMethodDef->getBeginLoc();
3165 InsertText(FunLocStart, str);
3168 // AST for __Stretn(receiver, args).s;
3169 IdentifierInfo *ID = &Context->Idents.get(name);
3171 FunctionDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(),
3172 ID, FuncType, nullptr, SC_Extern, false, false);
3173 DeclRefExpr *DRE = new (Context)
3174 DeclRefExpr(*Context, FD, false, castType, VK_RValue, SourceLocation());
3175 CallExpr *STCE = CallExpr::Create(*Context, DRE, MsgExprs, castType,
3176 VK_LValue, SourceLocation());
3178 FieldDecl *FieldD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
3180 &Context->Idents.get("s"),
3181 returnType, nullptr,
3182 /*BitWidth=*/nullptr,
3183 /*Mutable=*/true, ICIS_NoInit);
3184 MemberExpr *ME = new (Context)
3185 MemberExpr(STCE, false, SourceLocation(), FieldD, SourceLocation(),
3186 FieldD->getType(), VK_LValue, OK_Ordinary);
3191 Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3192 SourceLocation StartLoc,
3193 SourceLocation EndLoc) {
3194 if (!SelGetUidFunctionDecl)
3195 SynthSelGetUidFunctionDecl();
3196 if (!MsgSendFunctionDecl)
3197 SynthMsgSendFunctionDecl();
3198 if (!MsgSendSuperFunctionDecl)
3199 SynthMsgSendSuperFunctionDecl();
3200 if (!MsgSendStretFunctionDecl)
3201 SynthMsgSendStretFunctionDecl();
3202 if (!MsgSendSuperStretFunctionDecl)
3203 SynthMsgSendSuperStretFunctionDecl();
3204 if (!MsgSendFpretFunctionDecl)
3205 SynthMsgSendFpretFunctionDecl();
3206 if (!GetClassFunctionDecl)
3207 SynthGetClassFunctionDecl();
3208 if (!GetSuperClassFunctionDecl)
3209 SynthGetSuperClassFunctionDecl();
3210 if (!GetMetaClassFunctionDecl)
3211 SynthGetMetaClassFunctionDecl();
3213 // default to objc_msgSend().
3214 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3215 // May need to use objc_msgSend_stret() as well.
3216 FunctionDecl *MsgSendStretFlavor = nullptr;
3217 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
3218 QualType resultType = mDecl->getReturnType();
3219 if (resultType->isRecordType())
3220 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3221 else if (resultType->isRealFloatingType())
3222 MsgSendFlavor = MsgSendFpretFunctionDecl;
3225 // Synthesize a call to objc_msgSend().
3226 SmallVector<Expr*, 8> MsgExprs;
3227 switch (Exp->getReceiverKind()) {
3228 case ObjCMessageExpr::SuperClass: {
3229 MsgSendFlavor = MsgSendSuperFunctionDecl;
3230 if (MsgSendStretFlavor)
3231 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3232 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3234 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3236 SmallVector<Expr*, 4> InitExprs;
3238 // set the receiver to self, the first argument to all methods.
3239 InitExprs.push_back(
3240 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3242 new (Context) DeclRefExpr(*Context,
3243 CurMethodDef->getSelfDecl(),
3245 Context->getObjCIdType(),
3248 ); // set the 'receiver'.
3250 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3251 SmallVector<Expr*, 8> ClsExprs;
3252 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
3253 // (Class)objc_getClass("CurrentClass")
3254 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3255 ClsExprs, StartLoc, EndLoc);
3257 ClsExprs.push_back(Cls);
3258 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
3261 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3262 // To turn off a warning, type-cast to 'id'
3263 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3264 NoTypeInfoCStyleCastExpr(Context,
3265 Context->getObjCIdType(),
3267 // struct __rw_objc_super
3268 QualType superType = getSuperStructType();
3271 if (LangOpts.MicrosoftExt) {
3272 SynthSuperConstructorFunctionDecl();
3273 // Simulate a constructor call...
3274 DeclRefExpr *DRE = new (Context)
3275 DeclRefExpr(*Context, SuperConstructorFunctionDecl, false, superType,
3276 VK_LValue, SourceLocation());
3277 SuperRep = CallExpr::Create(*Context, DRE, InitExprs, superType,
3278 VK_LValue, SourceLocation());
3279 // The code for super is a little tricky to prevent collision with
3280 // the structure definition in the header. The rewriter has it's own
3281 // internal definition (__rw_objc_super) that is uses. This is why
3282 // we need the cast below. For example:
3283 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
3285 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3286 Context->getPointerType(SuperRep->getType()),
3287 VK_RValue, OK_Ordinary,
3288 SourceLocation(), false);
3289 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3290 Context->getPointerType(superType),
3291 CK_BitCast, SuperRep);
3293 // (struct __rw_objc_super) { <exprs from above> }
3295 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
3297 TypeSourceInfo *superTInfo
3298 = Context->getTrivialTypeSourceInfo(superType);
3299 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3300 superType, VK_LValue,
3302 // struct __rw_objc_super *
3303 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3304 Context->getPointerType(SuperRep->getType()),
3305 VK_RValue, OK_Ordinary,
3306 SourceLocation(), false);
3308 MsgExprs.push_back(SuperRep);
3312 case ObjCMessageExpr::Class: {
3313 SmallVector<Expr*, 8> ClsExprs;
3314 ObjCInterfaceDecl *Class
3315 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3316 IdentifierInfo *clsName = Class->getIdentifier();
3317 ClsExprs.push_back(getStringLiteral(clsName->getName()));
3318 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
3320 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3321 Context->getObjCIdType(),
3323 MsgExprs.push_back(ArgExpr);
3327 case ObjCMessageExpr::SuperInstance:{
3328 MsgSendFlavor = MsgSendSuperFunctionDecl;
3329 if (MsgSendStretFlavor)
3330 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3331 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3332 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3333 SmallVector<Expr*, 4> InitExprs;
3335 InitExprs.push_back(
3336 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3338 new (Context) DeclRefExpr(*Context,
3339 CurMethodDef->getSelfDecl(),
3341 Context->getObjCIdType(),
3342 VK_RValue, SourceLocation()))
3343 ); // set the 'receiver'.
3345 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3346 SmallVector<Expr*, 8> ClsExprs;
3347 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
3348 // (Class)objc_getClass("CurrentClass")
3349 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
3352 ClsExprs.push_back(Cls);
3353 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
3356 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3357 // To turn off a warning, type-cast to 'id'
3358 InitExprs.push_back(
3359 // set 'super class', using class_getSuperclass().
3360 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3362 // struct __rw_objc_super
3363 QualType superType = getSuperStructType();
3366 if (LangOpts.MicrosoftExt) {
3367 SynthSuperConstructorFunctionDecl();
3368 // Simulate a constructor call...
3369 DeclRefExpr *DRE = new (Context)
3370 DeclRefExpr(*Context, SuperConstructorFunctionDecl, false, superType,
3371 VK_LValue, SourceLocation());
3372 SuperRep = CallExpr::Create(*Context, DRE, InitExprs, superType,
3373 VK_LValue, SourceLocation());
3374 // The code for super is a little tricky to prevent collision with
3375 // the structure definition in the header. The rewriter has it's own
3376 // internal definition (__rw_objc_super) that is uses. This is why
3377 // we need the cast below. For example:
3378 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
3380 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3381 Context->getPointerType(SuperRep->getType()),
3382 VK_RValue, OK_Ordinary,
3383 SourceLocation(), false);
3384 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3385 Context->getPointerType(superType),
3386 CK_BitCast, SuperRep);
3388 // (struct __rw_objc_super) { <exprs from above> }
3390 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
3392 TypeSourceInfo *superTInfo
3393 = Context->getTrivialTypeSourceInfo(superType);
3394 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3395 superType, VK_RValue, ILE,
3398 MsgExprs.push_back(SuperRep);
3402 case ObjCMessageExpr::Instance: {
3403 // Remove all type-casts because it may contain objc-style types; e.g.
3405 Expr *recExpr = Exp->getInstanceReceiver();
3406 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3407 recExpr = CE->getSubExpr();
3408 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3409 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3410 ? CK_BlockPointerToObjCPointerCast
3411 : CK_CPointerToObjCPointerCast;
3413 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3415 MsgExprs.push_back(recExpr);
3420 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3421 SmallVector<Expr*, 8> SelExprs;
3422 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
3423 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3424 SelExprs, StartLoc, EndLoc);
3425 MsgExprs.push_back(SelExp);
3427 // Now push any user supplied arguments.
3428 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3429 Expr *userExpr = Exp->getArg(i);
3430 // Make all implicit casts explicit...ICE comes in handy:-)
3431 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3432 // Reuse the ICE type, it is exactly what the doctor ordered.
3433 QualType type = ICE->getType();
3434 if (needToScanForQualifiers(type))
3435 type = Context->getObjCIdType();
3436 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3437 (void)convertBlockPointerToFunctionPointer(type);
3438 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3440 if (SubExpr->getType()->isIntegralType(*Context) &&
3441 type->isBooleanType()) {
3442 CK = CK_IntegralToBoolean;
3443 } else if (type->isObjCObjectPointerType()) {
3444 if (SubExpr->getType()->isBlockPointerType()) {
3445 CK = CK_BlockPointerToObjCPointerCast;
3446 } else if (SubExpr->getType()->isPointerType()) {
3447 CK = CK_CPointerToObjCPointerCast;
3455 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3457 // Make id<P...> cast into an 'id' cast.
3458 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3459 if (CE->getType()->isObjCQualifiedIdType()) {
3460 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3461 userExpr = CE->getSubExpr();
3463 if (userExpr->getType()->isIntegralType(*Context)) {
3464 CK = CK_IntegralToPointer;
3465 } else if (userExpr->getType()->isBlockPointerType()) {
3466 CK = CK_BlockPointerToObjCPointerCast;
3467 } else if (userExpr->getType()->isPointerType()) {
3468 CK = CK_CPointerToObjCPointerCast;
3472 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3476 MsgExprs.push_back(userExpr);
3477 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3478 // out the argument in the original expression (since we aren't deleting
3479 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3480 //Exp->setArg(i, 0);
3482 // Generate the funky cast.
3484 SmallVector<QualType, 8> ArgTypes;
3485 QualType returnType;
3487 // Push 'id' and 'SEL', the 2 implicit arguments.
3488 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3489 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3491 ArgTypes.push_back(Context->getObjCIdType());
3492 ArgTypes.push_back(Context->getObjCSelType());
3493 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3494 // Push any user argument types.
3495 for (const auto *PI : OMD->parameters()) {
3496 QualType t = PI->getType()->isObjCQualifiedIdType()
3497 ? Context->getObjCIdType()
3499 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3500 (void)convertBlockPointerToFunctionPointer(t);
3501 ArgTypes.push_back(t);
3503 returnType = Exp->getType();
3504 convertToUnqualifiedObjCType(returnType);
3505 (void)convertBlockPointerToFunctionPointer(returnType);
3507 returnType = Context->getObjCIdType();
3509 // Get the type, we will need to reference it in a couple spots.
3510 QualType msgSendType = MsgSendFlavor->getType();
3512 // Create a reference to the objc_msgSend() declaration.
3513 DeclRefExpr *DRE = new (Context) DeclRefExpr(
3514 *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
3516 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3517 // If we don't do this cast, we get the following bizarre warning/note:
3518 // xx.m:13: warning: function called through a non-compatible type
3519 // xx.m:13: note: if this code is reached, the program will abort
3520 cast = NoTypeInfoCStyleCastExpr(Context,
3521 Context->getPointerType(Context->VoidTy),
3524 // Now do the "normal" pointer to function cast.
3525 // If we don't have a method decl, force a variadic cast.
3526 const ObjCMethodDecl *MD = Exp->getMethodDecl();
3528 getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
3529 castType = Context->getPointerType(castType);
3530 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3533 // Don't forget the parens to enforce the proper binding.
3534 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3536 const FunctionType *FT = msgSendType->getAs<FunctionType>();
3537 CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
3539 Stmt *ReplacingStmt = CE;
3540 if (MsgSendStretFlavor) {
3541 // We have the method which returns a struct/union. Must also generate
3542 // call to objc_msgSend_stret and hang both varieties on a conditional
3543 // expression which dictate which one to envoke depending on size of
3544 // method's return type.
3546 Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3549 Exp->getMethodDecl());
3550 ReplacingStmt = STCE;
3552 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3553 return ReplacingStmt;
3556 Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3557 Stmt *ReplacingStmt =
3558 SynthMessageExpr(Exp, Exp->getBeginLoc(), Exp->getEndLoc());
3560 // Now do the actual rewrite.
3561 ReplaceStmt(Exp, ReplacingStmt);
3563 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3564 return ReplacingStmt;
3567 // typedef struct objc_object Protocol;
3568 QualType RewriteModernObjC::getProtocolType() {
3569 if (!ProtocolTypeDecl) {
3570 TypeSourceInfo *TInfo
3571 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3572 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3573 SourceLocation(), SourceLocation(),
3574 &Context->Idents.get("Protocol"),
3577 return Context->getTypeDeclType(ProtocolTypeDecl);
3580 /// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3581 /// a synthesized/forward data reference (to the protocol's metadata).
3582 /// The forward references (and metadata) are generated in
3583 /// RewriteModernObjC::HandleTranslationUnit().
3584 Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
3585 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3586 Exp->getProtocol()->getNameAsString();
3587 IdentifierInfo *ID = &Context->Idents.get(Name);
3588 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3589 SourceLocation(), ID, getProtocolType(),
3590 nullptr, SC_Extern);
3591 DeclRefExpr *DRE = new (Context) DeclRefExpr(
3592 *Context, VD, false, getProtocolType(), VK_LValue, SourceLocation());
3593 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(
3594 Context, Context->getPointerType(DRE->getType()), CK_BitCast, DRE);
3595 ReplaceStmt(Exp, castExpr);
3596 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3597 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3601 /// IsTagDefinedInsideClass - This routine checks that a named tagged type
3602 /// is defined inside an objective-c class. If so, it returns true.
3603 bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
3605 bool &IsNamedDefinition) {
3608 SourceLocation TagLocation;
3609 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3610 RD = RD->getDefinition();
3611 if (!RD || !RD->getDeclName().getAsIdentifierInfo())
3613 IsNamedDefinition = true;
3614 TagLocation = RD->getLocation();
3615 return Context->getSourceManager().isBeforeInTranslationUnit(
3616 IDecl->getLocation(), TagLocation);
3618 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3619 if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3621 IsNamedDefinition = true;
3622 TagLocation = ED->getLocation();
3623 return Context->getSourceManager().isBeforeInTranslationUnit(
3624 IDecl->getLocation(), TagLocation);
3629 /// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
3630 /// It handles elaborated types, as well as enum types in the process.
3631 bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3632 std::string &Result) {
3633 if (isa<TypedefType>(Type)) {
3638 if (Type->isArrayType()) {
3639 QualType ElemTy = Context->getBaseElementType(Type);
3640 return RewriteObjCFieldDeclType(ElemTy, Result);
3642 else if (Type->isRecordType()) {
3643 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3644 if (RD->isCompleteDefinition()) {
3646 Result += "\n\tstruct ";
3647 else if (RD->isUnion())
3648 Result += "\n\tunion ";
3650 assert(false && "class not allowed as an ivar type");
3652 Result += RD->getName();
3653 if (GlobalDefinedTags.count(RD)) {
3654 // struct/union is defined globally, use it.
3659 for (auto *FD : RD->fields())
3660 RewriteObjCFieldDecl(FD, Result);
3665 else if (Type->isEnumeralType()) {
3666 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3667 if (ED->isCompleteDefinition()) {
3668 Result += "\n\tenum ";
3669 Result += ED->getName();
3670 if (GlobalDefinedTags.count(ED)) {
3671 // Enum is globall defined, use it.
3677 for (const auto *EC : ED->enumerators()) {
3678 Result += "\t"; Result += EC->getName(); Result += " = ";
3679 llvm::APSInt Val = EC->getInitVal();
3680 Result += Val.toString(10);
3689 convertObjCTypeToCStyleType(Type);
3694 /// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3695 /// It handles elaborated types, as well as enum types in the process.
3696 void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3697 std::string &Result) {
3698 QualType Type = fieldDecl->getType();
3699 std::string Name = fieldDecl->getNameAsString();
3701 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3702 if (!EleboratedType)
3703 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
3705 if (fieldDecl->isBitField()) {
3706 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3708 else if (EleboratedType && Type->isArrayType()) {
3709 const ArrayType *AT = Context->getAsArrayType(Type);
3711 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
3713 llvm::APInt Dim = CAT->getSize();
3714 Result += utostr(Dim.getZExtValue());
3717 AT = Context->getAsArrayType(AT->getElementType());
3724 /// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3725 /// named aggregate types into the input buffer.
3726 void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3727 std::string &Result) {
3728 QualType Type = fieldDecl->getType();
3729 if (isa<TypedefType>(Type))
3731 if (Type->isArrayType())
3732 Type = Context->getBaseElementType(Type);
3733 ObjCContainerDecl *IDecl =
3734 dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
3736 TagDecl *TD = nullptr;
3737 if (Type->isRecordType()) {
3738 TD = Type->getAs<RecordType>()->getDecl();
3740 else if (Type->isEnumeralType()) {
3741 TD = Type->getAs<EnumType>()->getDecl();
3745 if (GlobalDefinedTags.count(TD))
3748 bool IsNamedDefinition = false;
3749 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3750 RewriteObjCFieldDeclType(Type, Result);
3753 if (IsNamedDefinition)
3754 GlobalDefinedTags.insert(TD);
3758 unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) {
3759 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3760 if (ObjCInterefaceHasBitfieldGroups.count(CDecl)) {
3761 return IvarGroupNumber[IV];
3763 unsigned GroupNo = 0;
3764 SmallVector<const ObjCIvarDecl *, 8> IVars;
3765 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3766 IVD; IVD = IVD->getNextIvar())
3767 IVars.push_back(IVD);
3769 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3770 if (IVars[i]->isBitField()) {
3771 IvarGroupNumber[IVars[i++]] = ++GroupNo;
3772 while (i < e && IVars[i]->isBitField())
3773 IvarGroupNumber[IVars[i++]] = GroupNo;
3778 ObjCInterefaceHasBitfieldGroups.insert(CDecl);
3779 return IvarGroupNumber[IV];
3782 QualType RewriteModernObjC::SynthesizeBitfieldGroupStructType(
3784 SmallVectorImpl<ObjCIvarDecl *> &IVars) {
3785 std::string StructTagName;
3786 ObjCIvarBitfieldGroupType(IV, StructTagName);
3787 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct,
3788 Context->getTranslationUnitDecl(),
3789 SourceLocation(), SourceLocation(),
3790 &Context->Idents.get(StructTagName));
3791 for (unsigned i=0, e = IVars.size(); i < e; i++) {
3792 ObjCIvarDecl *Ivar = IVars[i];
3793 RD->addDecl(FieldDecl::Create(*Context, RD, SourceLocation(), SourceLocation(),
3794 &Context->Idents.get(Ivar->getName()),
3796 nullptr, /*Expr *BW */Ivar->getBitWidth(),
3797 false, ICIS_NoInit));
3799 RD->completeDefinition();
3800 return Context->getTagDeclType(RD);
3803 QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV) {
3804 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3805 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3806 std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo);
3807 if (GroupRecordType.count(tuple))
3808 return GroupRecordType[tuple];
3810 SmallVector<ObjCIvarDecl *, 8> IVars;
3811 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3812 IVD; IVD = IVD->getNextIvar()) {
3813 if (IVD->isBitField())
3814 IVars.push_back(const_cast<ObjCIvarDecl *>(IVD));
3816 if (!IVars.empty()) {
3817 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3818 // Generate the struct type for this group of bitfield ivars.
3819 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3820 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3825 if (!IVars.empty()) {
3827 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3828 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3829 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3831 QualType RetQT = GroupRecordType[tuple];
3832 assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL");
3837 /// ObjCIvarBitfieldGroupDecl - Names field decl. for ivar bitfield group.
3838 /// Name would be: classname__GRBF_n where n is the group number for this ivar.
3839 void RewriteModernObjC::ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV,
3840 std::string &Result) {
3841 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3842 Result += CDecl->getName();
3843 Result += "__GRBF_";
3844 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3845 Result += utostr(GroupNo);
3848 /// ObjCIvarBitfieldGroupType - Names struct type for ivar bitfield group.
3849 /// Name of the struct would be: classname__T_n where n is the group number for
3851 void RewriteModernObjC::ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV,
3852 std::string &Result) {
3853 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3854 Result += CDecl->getName();
3856 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3857 Result += utostr(GroupNo);
3860 /// ObjCIvarBitfieldGroupOffset - Names symbol for ivar bitfield group field offset.
3861 /// Name would be: OBJC_IVAR_$_classname__GRBF_n where n is the group number for
3863 void RewriteModernObjC::ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV,
3864 std::string &Result) {
3865 Result += "OBJC_IVAR_$_";
3866 ObjCIvarBitfieldGroupDecl(IV, Result);
3869 #define SKIP_BITFIELDS(IX, ENDIX, VEC) { \
3870 while ((IX < ENDIX) && VEC[IX]->isBitField()) \
3876 /// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3877 /// an objective-c class with ivars.
3878 void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3879 std::string &Result) {
3880 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3881 assert(CDecl->getName() != "" &&
3882 "Name missing in SynthesizeObjCInternalStruct");
3883 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
3884 SmallVector<ObjCIvarDecl *, 8> IVars;
3885 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3886 IVD; IVD = IVD->getNextIvar())
3887 IVars.push_back(IVD);
3889 SourceLocation LocStart = CDecl->getBeginLoc();
3890 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
3892 const char *startBuf = SM->getCharacterData(LocStart);
3893 const char *endBuf = SM->getCharacterData(LocEnd);
3895 // If no ivars and no root or if its root, directly or indirectly,
3896 // have no ivars (thus not synthesized) then no need to synthesize this class.
3897 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
3898 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3899 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3900 ReplaceText(LocStart, endBuf-startBuf, Result);
3904 // Insert named struct/union definitions inside class to
3905 // outer scope. This follows semantics of locally defined
3906 // struct/unions in objective-c classes.
3907 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3908 RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
3910 // Insert named structs which are syntheized to group ivar bitfields
3911 // to outer scope as well.
3912 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3913 if (IVars[i]->isBitField()) {
3914 ObjCIvarDecl *IV = IVars[i];
3915 QualType QT = GetGroupRecordTypeForObjCIvarBitfield(IV);
3916 RewriteObjCFieldDeclType(QT, Result);
3918 // skip over ivar bitfields in this group.
3919 SKIP_BITFIELDS(i , e, IVars);
3922 Result += "\nstruct ";
3923 Result += CDecl->getNameAsString();
3924 Result += "_IMPL {\n";
3926 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
3927 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3928 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3929 Result += "_IVARS;\n";
3932 for (unsigned i = 0, e = IVars.size(); i < e; i++) {
3933 if (IVars[i]->isBitField()) {
3934 ObjCIvarDecl *IV = IVars[i];
3935 Result += "\tstruct ";
3936 ObjCIvarBitfieldGroupType(IV, Result); Result += " ";
3937 ObjCIvarBitfieldGroupDecl(IV, Result); Result += ";\n";
3938 // skip over ivar bitfields in this group.
3939 SKIP_BITFIELDS(i , e, IVars);
3942 RewriteObjCFieldDecl(IVars[i], Result);
3946 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3947 ReplaceText(LocStart, endBuf-startBuf, Result);
3948 // Mark this struct as having been generated.
3949 if (!ObjCSynthesizedStructs.insert(CDecl).second)
3950 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
3953 /// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3954 /// have been referenced in an ivar access expression.
3955 void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3956 std::string &Result) {
3957 // write out ivar offset symbols which have been referenced in an ivar
3958 // access expression.
3959 llvm::SmallSetVector<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3964 llvm::DenseSet<std::pair<const ObjCInterfaceDecl*, unsigned> > GroupSymbolOutput;
3965 for (ObjCIvarDecl *IvarDecl : Ivars) {
3966 const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface();
3967 unsigned GroupNo = 0;
3968 if (IvarDecl->isBitField()) {
3969 GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl);
3970 if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo)))
3974 if (LangOpts.MicrosoftExt)
3975 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
3976 Result += "extern \"C\" ";
3977 if (LangOpts.MicrosoftExt &&
3978 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
3979 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
3980 Result += "__declspec(dllimport) ";
3982 Result += "unsigned long ";
3983 if (IvarDecl->isBitField()) {
3984 ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
3985 GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo));
3988 WriteInternalIvarName(CDecl, IvarDecl, Result);
3993 //===----------------------------------------------------------------------===//
3994 // Meta Data Emission
3995 //===----------------------------------------------------------------------===//
3997 /// RewriteImplementations - This routine rewrites all method implementations
3998 /// and emits meta-data.
4000 void RewriteModernObjC::RewriteImplementations() {
4001 int ClsDefCount = ClassImplementation.size();
4002 int CatDefCount = CategoryImplementation.size();
4004 // Rewrite implemented methods
4005 for (int i = 0; i < ClsDefCount; i++) {
4006 ObjCImplementationDecl *OIMP = ClassImplementation[i];
4007 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
4008 if (CDecl->isImplicitInterfaceDecl())
4010 "Legacy implicit interface rewriting not supported in moder abi");
4011 RewriteImplementationDecl(OIMP);
4014 for (int i = 0; i < CatDefCount; i++) {
4015 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
4016 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
4017 if (CDecl->isImplicitInterfaceDecl())
4019 "Legacy implicit interface rewriting not supported in moder abi");
4020 RewriteImplementationDecl(CIMP);
4024 void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
4025 const std::string &Name,
4026 ValueDecl *VD, bool def) {
4027 assert(BlockByRefDeclNo.count(VD) &&
4028 "RewriteByRefString: ByRef decl missing");
4030 ResultStr += "struct ";
4031 ResultStr += "__Block_byref_" + Name +
4032 "_" + utostr(BlockByRefDeclNo[VD]) ;
4035 static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4036 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4037 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4041 std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4044 const FunctionType *AFT = CE->getFunctionType();
4045 QualType RT = AFT->getReturnType();
4046 std::string StructRef = "struct " + Tag;
4047 SourceLocation BlockLoc = CE->getExprLoc();
4049 ConvertSourceLocationToLineDirective(BlockLoc, S);
4051 S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
4052 funcName.str() + "_block_func_" + utostr(i);
4054 BlockDecl *BD = CE->getBlockDecl();
4056 if (isa<FunctionNoProtoType>(AFT)) {
4057 // No user-supplied arguments. Still need to pass in a pointer to the
4058 // block (to reference imported block decl refs).
4059 S += "(" + StructRef + " *__cself)";
4060 } else if (BD->param_empty()) {
4061 S += "(" + StructRef + " *__cself)";
4063 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4064 assert(FT && "SynthesizeBlockFunc: No function proto");
4066 // first add the implicit argument.
4067 S += StructRef + " *__cself, ";
4068 std::string ParamStr;
4069 for (BlockDecl::param_iterator AI = BD->param_begin(),
4070 E = BD->param_end(); AI != E; ++AI) {
4071 if (AI != BD->param_begin()) S += ", ";
4072 ParamStr = (*AI)->getNameAsString();
4073 QualType QT = (*AI)->getType();
4074 (void)convertBlockPointerToFunctionPointer(QT);
4075 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
4078 if (FT->isVariadic()) {
4079 if (!BD->param_empty()) S += ", ";
4086 // Create local declarations to avoid rewriting all closure decl ref exprs.
4087 // First, emit a declaration for all "by ref" decls.
4088 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
4089 E = BlockByRefDecls.end(); I != E; ++I) {
4091 std::string Name = (*I)->getNameAsString();
4092 std::string TypeString;
4093 RewriteByRefString(TypeString, Name, (*I));
4095 Name = TypeString + Name;
4096 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4098 // Next, emit a declaration for all "by copy" declarations.
4099 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
4100 E = BlockByCopyDecls.end(); I != E; ++I) {
4102 // Handle nested closure invocation. For example:
4104 // void (^myImportedClosure)(void);
4105 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
4107 // void (^anotherClosure)(void);
4108 // anotherClosure = ^(void) {
4109 // myImportedClosure(); // import and invoke the closure
4112 if (isTopLevelBlockPointerType((*I)->getType())) {
4113 RewriteBlockPointerTypeVariable(S, (*I));
4115 RewriteBlockPointerType(S, (*I)->getType());
4117 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4120 std::string Name = (*I)->getNameAsString();
4121 QualType QT = (*I)->getType();
4122 if (HasLocalVariableExternalStorage(*I))
4123 QT = Context->getPointerType(QT);
4124 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
4125 S += Name + " = __cself->" +
4126 (*I)->getNameAsString() + "; // bound by copy\n";
4129 std::string RewrittenStr = RewrittenBlockExprs[CE];
4130 const char *cstr = RewrittenStr.c_str();
4131 while (*cstr++ != '{') ;
4137 std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4140 std::string StructRef = "struct " + Tag;
4141 std::string S = "static void __";
4144 S += "_block_copy_" + utostr(i);
4145 S += "(" + StructRef;
4146 S += "*dst, " + StructRef;
4148 for (ValueDecl *VD : ImportedBlockDecls) {
4149 S += "_Block_object_assign((void*)&dst->";
4150 S += VD->getNameAsString();
4151 S += ", (void*)src->";
4152 S += VD->getNameAsString();
4153 if (BlockByRefDeclsPtrSet.count(VD))
4154 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4155 else if (VD->getType()->isBlockPointerType())
4156 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4158 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4162 S += "\nstatic void __";
4164 S += "_block_dispose_" + utostr(i);
4165 S += "(" + StructRef;
4167 for (ValueDecl *VD : ImportedBlockDecls) {
4168 S += "_Block_object_dispose((void*)src->";
4169 S += VD->getNameAsString();
4170 if (BlockByRefDeclsPtrSet.count(VD))
4171 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4172 else if (VD->getType()->isBlockPointerType())
4173 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4175 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4181 std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4183 std::string S = "\nstruct " + Tag;
4184 std::string Constructor = " " + Tag;
4186 S += " {\n struct __block_impl impl;\n";
4187 S += " struct " + Desc;
4190 Constructor += "(void *fp, "; // Invoke function pointer.
4191 Constructor += "struct " + Desc; // Descriptor pointer.
4192 Constructor += " *desc";
4194 if (BlockDeclRefs.size()) {
4195 // Output all "by copy" declarations.
4196 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
4197 E = BlockByCopyDecls.end(); I != E; ++I) {
4199 std::string FieldName = (*I)->getNameAsString();
4200 std::string ArgName = "_" + FieldName;
4201 // Handle nested closure invocation. For example:
4203 // void (^myImportedBlock)(void);
4204 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
4206 // void (^anotherBlock)(void);
4207 // anotherBlock = ^(void) {
4208 // myImportedBlock(); // import and invoke the closure
4211 if (isTopLevelBlockPointerType((*I)->getType())) {
4212 S += "struct __block_impl *";
4213 Constructor += ", void *" + ArgName;
4215 QualType QT = (*I)->getType();
4216 if (HasLocalVariableExternalStorage(*I))
4217 QT = Context->getPointerType(QT);
4218 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4219 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4220 Constructor += ", " + ArgName;
4222 S += FieldName + ";\n";
4224 // Output all "by ref" declarations.
4225 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
4226 E = BlockByRefDecls.end(); I != E; ++I) {
4228 std::string FieldName = (*I)->getNameAsString();
4229 std::string ArgName = "_" + FieldName;
4231 std::string TypeString;
4232 RewriteByRefString(TypeString, FieldName, (*I));
4234 FieldName = TypeString + FieldName;
4235 ArgName = TypeString + ArgName;
4236 Constructor += ", " + ArgName;
4238 S += FieldName + "; // by ref\n";
4240 // Finish writing the constructor.
4241 Constructor += ", int flags=0)";
4242 // Initialize all "by copy" arguments.
4243 bool firsTime = true;
4244 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
4245 E = BlockByCopyDecls.end(); I != E; ++I) {
4246 std::string Name = (*I)->getNameAsString();
4248 Constructor += " : ";
4252 Constructor += ", ";
4253 if (isTopLevelBlockPointerType((*I)->getType()))
4254 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4256 Constructor += Name + "(_" + Name + ")";
4258 // Initialize all "by ref" arguments.
4259 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
4260 E = BlockByRefDecls.end(); I != E; ++I) {
4261 std::string Name = (*I)->getNameAsString();
4263 Constructor += " : ";
4267 Constructor += ", ";
4268 Constructor += Name + "(_" + Name + "->__forwarding)";
4271 Constructor += " {\n";
4273 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4275 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4276 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4278 Constructor += " Desc = desc;\n";
4280 // Finish writing the constructor.
4281 Constructor += ", int flags=0) {\n";
4283 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4285 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4286 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4287 Constructor += " Desc = desc;\n";
4290 Constructor += "}\n";
4296 std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4297 std::string ImplTag, int i,
4300 std::string S = "\nstatic struct " + DescTag;
4302 S += " {\n size_t reserved;\n";
4303 S += " size_t Block_size;\n";
4305 S += " void (*copy)(struct ";
4306 S += ImplTag; S += "*, struct ";
4307 S += ImplTag; S += "*);\n";
4309 S += " void (*dispose)(struct ";
4310 S += ImplTag; S += "*);\n";
4314 S += DescTag + "_DATA = { 0, sizeof(struct ";
4317 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4318 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4324 void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4325 StringRef FunName) {
4326 bool RewriteSC = (GlobalVarDecl &&
4328 GlobalVarDecl->getStorageClass() == SC_Static &&
4329 GlobalVarDecl->getType().getCVRQualifiers());
4331 std::string SC(" void __");
4332 SC += GlobalVarDecl->getNameAsString();
4334 InsertText(FunLocStart, SC);
4337 // Insert closures that were part of the function.
4338 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4339 CollectBlockDeclRefInfo(Blocks[i]);
4340 // Need to copy-in the inner copied-in variables not actually used in this
4342 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4343 DeclRefExpr *Exp = InnerDeclRefs[count++];
4344 ValueDecl *VD = Exp->getDecl();
4345 BlockDeclRefs.push_back(Exp);
4346 if (!VD->hasAttr<BlocksAttr>()) {
4347 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4348 BlockByCopyDeclsPtrSet.insert(VD);
4349 BlockByCopyDecls.push_back(VD);
4354 if (!BlockByRefDeclsPtrSet.count(VD)) {
4355 BlockByRefDeclsPtrSet.insert(VD);
4356 BlockByRefDecls.push_back(VD);
4359 // imported objects in the inner blocks not used in the outer
4360 // blocks must be copied/disposed in the outer block as well.
4361 if (VD->getType()->isObjCObjectPointerType() ||
4362 VD->getType()->isBlockPointerType())
4363 ImportedBlockDecls.insert(VD);
4366 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4367 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4369 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4371 InsertText(FunLocStart, CI);
4373 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4375 InsertText(FunLocStart, CF);
4377 if (ImportedBlockDecls.size()) {
4378 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4379 InsertText(FunLocStart, HF);
4381 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4382 ImportedBlockDecls.size() > 0);
4383 InsertText(FunLocStart, BD);
4385 BlockDeclRefs.clear();
4386 BlockByRefDecls.clear();
4387 BlockByRefDeclsPtrSet.clear();
4388 BlockByCopyDecls.clear();
4389 BlockByCopyDeclsPtrSet.clear();
4390 ImportedBlockDecls.clear();
4393 // Must insert any 'const/volatile/static here. Since it has been
4394 // removed as result of rewriting of block literals.
4396 if (GlobalVarDecl->getStorageClass() == SC_Static)
4398 if (GlobalVarDecl->getType().isConstQualified())
4400 if (GlobalVarDecl->getType().isVolatileQualified())
4402 if (GlobalVarDecl->getType().isRestrictQualified())
4404 InsertText(FunLocStart, SC);
4406 if (GlobalConstructionExp) {
4407 // extra fancy dance for global literal expression.
4409 // Always the latest block expression on the block stack.
4410 std::string Tag = "__";
4412 Tag += "_block_impl_";
4413 Tag += utostr(Blocks.size()-1);
4414 std::string globalBuf = "static ";
4415 globalBuf += Tag; globalBuf += " ";
4418 llvm::raw_string_ostream constructorExprBuf(SStr);
4419 GlobalConstructionExp->printPretty(constructorExprBuf, nullptr,
4420 PrintingPolicy(LangOpts));
4421 globalBuf += constructorExprBuf.str();
4423 InsertText(FunLocStart, globalBuf);
4424 GlobalConstructionExp = nullptr;
4428 InnerDeclRefsCount.clear();
4429 InnerDeclRefs.clear();
4430 RewrittenBlockExprs.clear();
4433 void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4434 SourceLocation FunLocStart =
4435 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4436 : FD->getTypeSpecStartLoc();
4437 StringRef FuncName = FD->getName();
4439 SynthesizeBlockLiterals(FunLocStart, FuncName);
4442 static void BuildUniqueMethodName(std::string &Name,
4443 ObjCMethodDecl *MD) {
4444 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4445 Name = IFace->getName();
4446 Name += "__" + MD->getSelector().getAsString();
4447 // Convert colons to underscores.
4448 std::string::size_type loc = 0;
4449 while ((loc = Name.find(':', loc)) != std::string::npos)
4450 Name.replace(loc, 1, "_");
4453 void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4454 // fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4455 // SourceLocation FunLocStart = MD->getBeginLoc();
4456 SourceLocation FunLocStart = MD->getBeginLoc();
4457 std::string FuncName;
4458 BuildUniqueMethodName(FuncName, MD);
4459 SynthesizeBlockLiterals(FunLocStart, FuncName);
4462 void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4463 for (Stmt *SubStmt : S->children())
4465 if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt))
4466 GetBlockDeclRefExprs(CBE->getBody());
4468 GetBlockDeclRefExprs(SubStmt);
4470 // Handle specific things.
4471 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4472 if (DRE->refersToEnclosingVariableOrCapture() ||
4473 HasLocalVariableExternalStorage(DRE->getDecl()))
4474 // FIXME: Handle enums.
4475 BlockDeclRefs.push_back(DRE);
4478 void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4479 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
4480 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts) {
4481 for (Stmt *SubStmt : S->children())
4483 if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt)) {
4484 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4485 GetInnerBlockDeclRefExprs(CBE->getBody(),
4490 GetInnerBlockDeclRefExprs(SubStmt, InnerBlockDeclRefs, InnerContexts);
4492 // Handle specific things.
4493 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4494 if (DRE->refersToEnclosingVariableOrCapture() ||
4495 HasLocalVariableExternalStorage(DRE->getDecl())) {
4496 if (!InnerContexts.count(DRE->getDecl()->getDeclContext()))
4497 InnerBlockDeclRefs.push_back(DRE);
4498 if (VarDecl *Var = cast<VarDecl>(DRE->getDecl()))
4499 if (Var->isFunctionOrMethodVarDecl())
4500 ImportedLocalExternalDecls.insert(Var);
4505 /// convertObjCTypeToCStyleType - This routine converts such objc types
4506 /// as qualified objects, and blocks to their closest c/c++ types that
4507 /// it can. It returns true if input type was modified.
4508 bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4510 convertBlockPointerToFunctionPointer(T);
4511 if (T->isFunctionPointerType()) {
4513 if (const PointerType* PT = T->getAs<PointerType>()) {
4514 PointeeTy = PT->getPointeeType();
4515 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4516 T = convertFunctionTypeOfBlocks(FT);
4517 T = Context->getPointerType(T);
4522 convertToUnqualifiedObjCType(T);
4526 /// convertFunctionTypeOfBlocks - This routine converts a function type
4527 /// whose result type may be a block pointer or whose argument type(s)
4528 /// might be block pointers to an equivalent function type replacing
4529 /// all block pointers to function pointers.
4530 QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4531 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4532 // FTP will be null for closures that don't take arguments.
4533 // Generate a funky cast.
4534 SmallVector<QualType, 8> ArgTypes;
4535 QualType Res = FT->getReturnType();
4536 bool modified = convertObjCTypeToCStyleType(Res);
4539 for (auto &I : FTP->param_types()) {
4541 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4542 if (convertObjCTypeToCStyleType(t))
4544 ArgTypes.push_back(t);
4549 FuncType = getSimpleFunctionType(Res, ArgTypes);
4550 else FuncType = QualType(FT, 0);
4554 Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4555 // Navigate to relevant type information.
4556 const BlockPointerType *CPT = nullptr;
4558 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4559 CPT = DRE->getType()->getAs<BlockPointerType>();
4560 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4561 CPT = MExpr->getType()->getAs<BlockPointerType>();
4563 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4564 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4566 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4567 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4568 else if (const ConditionalOperator *CEXPR =
4569 dyn_cast<ConditionalOperator>(BlockExp)) {
4570 Expr *LHSExp = CEXPR->getLHS();
4571 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4572 Expr *RHSExp = CEXPR->getRHS();
4573 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4574 Expr *CONDExp = CEXPR->getCond();
4575 ConditionalOperator *CondExpr =
4576 new (Context) ConditionalOperator(CONDExp,
4577 SourceLocation(), cast<Expr>(LHSStmt),
4578 SourceLocation(), cast<Expr>(RHSStmt),
4579 Exp->getType(), VK_RValue, OK_Ordinary);
4581 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4582 CPT = IRE->getType()->getAs<BlockPointerType>();
4583 } else if (const PseudoObjectExpr *POE
4584 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4585 CPT = POE->getType()->castAs<BlockPointerType>();
4587 assert(false && "RewriteBlockClass: Bad type");
4589 assert(CPT && "RewriteBlockClass: Bad type");
4590 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4591 assert(FT && "RewriteBlockClass: Bad type");
4592 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4593 // FTP will be null for closures that don't take arguments.
4595 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4596 SourceLocation(), SourceLocation(),
4597 &Context->Idents.get("__block_impl"));
4598 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4600 // Generate a funky cast.
4601 SmallVector<QualType, 8> ArgTypes;
4603 // Push the block argument type.
4604 ArgTypes.push_back(PtrBlock);
4606 for (auto &I : FTP->param_types()) {
4608 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4609 if (!convertBlockPointerToFunctionPointer(t))
4610 convertToUnqualifiedObjCType(t);
4611 ArgTypes.push_back(t);
4614 // Now do the pointer to function cast.
4615 QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
4617 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4619 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4621 const_cast<Expr*>(BlockExp));
4622 // Don't forget the parens to enforce the proper binding.
4623 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4627 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
4629 &Context->Idents.get("FuncPtr"),
4630 Context->VoidPtrTy, nullptr,
4631 /*BitWidth=*/nullptr, /*Mutable=*/true,
4634 new (Context) MemberExpr(PE, true, SourceLocation(), FD, SourceLocation(),
4635 FD->getType(), VK_LValue, OK_Ordinary);
4637 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4639 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4641 SmallVector<Expr*, 8> BlkExprs;
4642 // Add the implicit argument.
4643 BlkExprs.push_back(BlkCast);
4644 // Add the user arguments.
4645 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4646 E = Exp->arg_end(); I != E; ++I) {
4647 BlkExprs.push_back(*I);
4649 CallExpr *CE = CallExpr::Create(*Context, PE, BlkExprs, Exp->getType(),
4650 VK_RValue, SourceLocation());
4654 // We need to return the rewritten expression to handle cases where the
4655 // DeclRefExpr is embedded in another expression being rewritten.
4662 // void (^myblock)() = ^() {
4663 // [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
4667 Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
4668 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4669 // for each DeclRefExp where BYREFVAR is name of the variable.
4670 ValueDecl *VD = DeclRefExp->getDecl();
4671 bool isArrow = DeclRefExp->refersToEnclosingVariableOrCapture() ||
4672 HasLocalVariableExternalStorage(DeclRefExp->getDecl());
4674 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
4676 &Context->Idents.get("__forwarding"),
4677 Context->VoidPtrTy, nullptr,
4678 /*BitWidth=*/nullptr, /*Mutable=*/true,
4680 MemberExpr *ME = new (Context)
4681 MemberExpr(DeclRefExp, isArrow, SourceLocation(), FD, SourceLocation(),
4682 FD->getType(), VK_LValue, OK_Ordinary);
4684 StringRef Name = VD->getName();
4685 FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(),
4686 &Context->Idents.get(Name),
4687 Context->VoidPtrTy, nullptr,
4688 /*BitWidth=*/nullptr, /*Mutable=*/true,
4691 new (Context) MemberExpr(ME, true, SourceLocation(), FD, SourceLocation(),
4692 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4694 // Need parens to enforce precedence.
4695 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4696 DeclRefExp->getExprLoc(),
4698 ReplaceStmt(DeclRefExp, PE);
4702 // Rewrites the imported local variable V with external storage
4703 // (static, extern, etc.) as *V
4705 Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4706 ValueDecl *VD = DRE->getDecl();
4707 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4708 if (!ImportedLocalExternalDecls.count(Var))
4710 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4711 VK_LValue, OK_Ordinary,
4712 DRE->getLocation(), false);
4713 // Need parens to enforce precedence.
4714 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4716 ReplaceStmt(DRE, PE);
4720 void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4721 SourceLocation LocStart = CE->getLParenLoc();
4722 SourceLocation LocEnd = CE->getRParenLoc();
4724 // Need to avoid trying to rewrite synthesized casts.
4725 if (LocStart.isInvalid())
4727 // Need to avoid trying to rewrite casts contained in macros.
4728 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4731 const char *startBuf = SM->getCharacterData(LocStart);
4732 const char *endBuf = SM->getCharacterData(LocEnd);
4733 QualType QT = CE->getType();
4734 const Type* TypePtr = QT->getAs<Type>();
4735 if (isa<TypeOfExprType>(TypePtr)) {
4736 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4737 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4738 std::string TypeAsString = "(";
4739 RewriteBlockPointerType(TypeAsString, QT);
4740 TypeAsString += ")";
4741 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4744 // advance the location to startArgList.
4745 const char *argPtr = startBuf;
4747 while (*argPtr++ && (argPtr < endBuf)) {
4750 // Replace the '^' with '*'.
4751 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4752 ReplaceText(LocStart, 1, "*");
4758 void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4759 CastKind CastKind = IC->getCastKind();
4760 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4761 CastKind != CK_AnyPointerToBlockPointerCast)
4764 QualType QT = IC->getType();
4765 (void)convertBlockPointerToFunctionPointer(QT);
4766 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4767 std::string Str = "(";
4770 InsertText(IC->getSubExpr()->getBeginLoc(), Str);
4773 void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4774 SourceLocation DeclLoc = FD->getLocation();
4775 unsigned parenCount = 0;
4777 // We have 1 or more arguments that have closure pointers.
4778 const char *startBuf = SM->getCharacterData(DeclLoc);
4779 const char *startArgList = strchr(startBuf, '(');
4781 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4784 // advance the location to startArgList.
4785 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4786 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4788 const char *argPtr = startArgList;
4790 while (*argPtr++ && parenCount) {
4793 // Replace the '^' with '*'.
4794 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4795 ReplaceText(DeclLoc, 1, "*");
4807 bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4808 const FunctionProtoType *FTP;
4809 const PointerType *PT = QT->getAs<PointerType>();
4811 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4813 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4814 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4815 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4818 for (const auto &I : FTP->param_types())
4819 if (isTopLevelBlockPointerType(I))
4825 bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4826 const FunctionProtoType *FTP;
4827 const PointerType *PT = QT->getAs<PointerType>();
4829 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4831 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4832 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4833 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4836 for (const auto &I : FTP->param_types()) {
4837 if (I->isObjCQualifiedIdType())
4839 if (I->isObjCObjectPointerType() &&
4840 I->getPointeeType()->isObjCQualifiedInterfaceType())
4848 void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4849 const char *&RParen) {
4850 const char *argPtr = strchr(Name, '(');
4851 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4853 LParen = argPtr; // output the start.
4854 argPtr++; // skip past the left paren.
4855 unsigned parenCount = 1;
4857 while (*argPtr && parenCount) {
4859 case '(': parenCount++; break;
4860 case ')': parenCount--; break;
4863 if (parenCount) argPtr++;
4865 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4866 RParen = argPtr; // output the end
4869 void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4870 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4871 RewriteBlockPointerFunctionArgs(FD);
4874 // Handle Variables and Typedefs.
4875 SourceLocation DeclLoc = ND->getLocation();
4877 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4878 DeclT = VD->getType();
4879 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4880 DeclT = TDD->getUnderlyingType();
4881 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4882 DeclT = FD->getType();
4884 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4886 const char *startBuf = SM->getCharacterData(DeclLoc);
4887 const char *endBuf = startBuf;
4888 // scan backward (from the decl location) for the end of the previous decl.
4889 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4891 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4893 unsigned OrigLength=0;
4894 // *startBuf != '^' if we are dealing with a pointer to function that
4895 // may take block argument types (which will be handled below).
4896 if (*startBuf == '^') {
4897 // Replace the '^' with '*', computing a negative offset.
4902 while (*startBuf != ')') {
4910 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4911 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4912 // Replace the '^' with '*' for arguments.
4913 // Replace id<P> with id/*<>*/
4914 DeclLoc = ND->getLocation();
4915 startBuf = SM->getCharacterData(DeclLoc);
4916 const char *argListBegin, *argListEnd;
4917 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4918 while (argListBegin < argListEnd) {
4919 if (*argListBegin == '^')
4921 else if (*argListBegin == '<') {
4923 buf += *argListBegin++;
4925 while (*argListBegin != '>') {
4926 buf += *argListBegin++;
4929 buf += *argListBegin;
4933 buf += *argListBegin;
4940 ReplaceText(Start, OrigLength, buf);
4943 /// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4944 /// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4945 /// struct Block_byref_id_object *src) {
4946 /// _Block_object_assign (&_dest->object, _src->object,
4947 /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4948 /// [|BLOCK_FIELD_IS_WEAK]) // object
4949 /// _Block_object_assign(&_dest->object, _src->object,
4950 /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4951 /// [|BLOCK_FIELD_IS_WEAK]) // block
4954 /// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4955 /// _Block_object_dispose(_src->object,
4956 /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4957 /// [|BLOCK_FIELD_IS_WEAK]) // object
4958 /// _Block_object_dispose(_src->object,
4959 /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4960 /// [|BLOCK_FIELD_IS_WEAK]) // block
4963 std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4966 if (CopyDestroyCache.count(flag))
4968 CopyDestroyCache.insert(flag);
4969 S = "static void __Block_byref_id_object_copy_";
4971 S += "(void *dst, void *src) {\n";
4973 // offset into the object pointer is computed as:
4974 // void * + void* + int + int + void* + void *
4976 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4977 unsigned VoidPtrSize =
4978 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4980 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4981 S += " _Block_object_assign((char*)dst + ";
4982 S += utostr(offset);
4983 S += ", *(void * *) ((char*)src + ";
4984 S += utostr(offset);
4989 S += "static void __Block_byref_id_object_dispose_";
4991 S += "(void *src) {\n";
4992 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4993 S += utostr(offset);
5000 /// RewriteByRefVar - For each __block typex ND variable this routine transforms
5001 /// the declaration into:
5002 /// struct __Block_byref_ND {
5003 /// void *__isa; // NULL for everything except __weak pointers
5004 /// struct __Block_byref_ND *__forwarding;
5005 /// int32_t __flags;
5007 /// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5008 /// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
5012 /// It then replaces declaration of ND variable with:
5013 /// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5014 /// __size=sizeof(struct __Block_byref_ND),
5015 /// ND=initializer-if-any};
5018 void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
5022 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
5023 if (DeclLoc.isInvalid())
5024 // If type location is missing, it is because of missing type (a warning).
5025 // Use variable's location which is good for this case.
5026 DeclLoc = ND->getLocation();
5027 const char *startBuf = SM->getCharacterData(DeclLoc);
5028 SourceLocation X = ND->getEndLoc();
5029 X = SM->getExpansionLoc(X);
5030 const char *endBuf = SM->getCharacterData(X);
5031 std::string Name(ND->getNameAsString());
5032 std::string ByrefType;
5033 RewriteByRefString(ByrefType, Name, ND, true);
5034 ByrefType += " {\n";
5035 ByrefType += " void *__isa;\n";
5036 RewriteByRefString(ByrefType, Name, ND);
5037 ByrefType += " *__forwarding;\n";
5038 ByrefType += " int __flags;\n";
5039 ByrefType += " int __size;\n";
5040 // Add void *__Block_byref_id_object_copy;
5041 // void *__Block_byref_id_object_dispose; if needed.
5042 QualType Ty = ND->getType();
5043 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
5044 if (HasCopyAndDispose) {
5045 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5046 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5050 (void)convertBlockPointerToFunctionPointer(T);
5051 T.getAsStringInternal(Name, Context->getPrintingPolicy());
5053 ByrefType += " " + Name + ";\n";
5054 ByrefType += "};\n";
5055 // Insert this type in global scope. It is needed by helper function.
5056 SourceLocation FunLocStart;
5058 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
5060 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5061 FunLocStart = CurMethodDef->getBeginLoc();
5063 InsertText(FunLocStart, ByrefType);
5065 if (Ty.isObjCGCWeak()) {
5066 flag |= BLOCK_FIELD_IS_WEAK;
5069 if (HasCopyAndDispose) {
5070 flag = BLOCK_BYREF_CALLER;
5071 QualType Ty = ND->getType();
5072 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5073 if (Ty->isBlockPointerType())
5074 flag |= BLOCK_FIELD_IS_BLOCK;
5076 flag |= BLOCK_FIELD_IS_OBJECT;
5077 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5082 // struct __Block_byref_ND ND =
5083 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5084 // initializer-if-any};
5085 bool hasInit = (ND->getInit() != nullptr);
5086 // FIXME. rewriter does not support __block c++ objects which
5087 // require construction.
5089 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5090 CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5091 if (CXXDecl && CXXDecl->isDefaultConstructor())
5096 if (HasCopyAndDispose)
5097 flags |= BLOCK_HAS_COPY_DISPOSE;
5098 Name = ND->getNameAsString();
5100 RewriteByRefString(ByrefType, Name, ND);
5101 std::string ForwardingCastType("(");
5102 ForwardingCastType += ByrefType + " *)";
5103 ByrefType += " " + Name + " = {(void*)";
5104 ByrefType += utostr(isa);
5105 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
5106 ByrefType += utostr(flags);
5108 ByrefType += "sizeof(";
5109 RewriteByRefString(ByrefType, Name, ND);
5111 if (HasCopyAndDispose) {
5112 ByrefType += ", __Block_byref_id_object_copy_";
5113 ByrefType += utostr(flag);
5114 ByrefType += ", __Block_byref_id_object_dispose_";
5115 ByrefType += utostr(flag);
5119 // In multiple __block declarations, and for all but 1st declaration,
5120 // find location of the separating comma. This would be start location
5121 // where new text is to be inserted.
5122 DeclLoc = ND->getLocation();
5123 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5124 const char *commaBuf = startDeclBuf;
5125 while (*commaBuf != ',')
5127 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5128 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5129 startBuf = commaBuf;
5133 ByrefType += "};\n";
5134 unsigned nameSize = Name.size();
5135 // for block or function pointer declaration. Name is already
5136 // part of the declaration.
5137 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5139 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5143 SourceLocation startLoc;
5144 Expr *E = ND->getInit();
5145 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5146 startLoc = ECE->getLParenLoc();
5148 startLoc = E->getBeginLoc();
5149 startLoc = SM->getExpansionLoc(startLoc);
5150 endBuf = SM->getCharacterData(startLoc);
5151 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
5153 const char separator = lastDecl ? ';' : ',';
5154 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5155 const char *separatorBuf = strchr(startInitializerBuf, separator);
5156 assert((*separatorBuf == separator) &&
5157 "RewriteByRefVar: can't find ';' or ','");
5158 SourceLocation separatorLoc =
5159 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
5161 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
5165 void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5166 // Add initializers for any closure decl refs.
5167 GetBlockDeclRefExprs(Exp->getBody());
5168 if (BlockDeclRefs.size()) {
5169 // Unique all "by copy" declarations.
5170 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5171 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
5172 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5173 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5174 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5177 // Unique all "by ref" declarations.
5178 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5179 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
5180 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5181 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5182 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5185 // Find any imported blocks...they will need special attention.
5186 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5187 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
5188 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5189 BlockDeclRefs[i]->getType()->isBlockPointerType())
5190 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5194 FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5195 IdentifierInfo *ID = &Context->Idents.get(name);
5196 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5197 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5198 SourceLocation(), ID, FType, nullptr, SC_Extern,
5202 Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
5203 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
5204 const BlockDecl *block = Exp->getBlockDecl();
5206 Blocks.push_back(Exp);
5208 CollectBlockDeclRefInfo(Exp);
5210 // Add inner imported variables now used in current block.
5211 int countOfInnerDecls = 0;
5212 if (!InnerBlockDeclRefs.empty()) {
5213 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5214 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
5215 ValueDecl *VD = Exp->getDecl();
5216 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
5217 // We need to save the copied-in variables in nested
5218 // blocks because it is needed at the end for some of the API generations.
5219 // See SynthesizeBlockLiterals routine.
5220 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5221 BlockDeclRefs.push_back(Exp);
5222 BlockByCopyDeclsPtrSet.insert(VD);
5223 BlockByCopyDecls.push_back(VD);
5225 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
5226 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5227 BlockDeclRefs.push_back(Exp);
5228 BlockByRefDeclsPtrSet.insert(VD);
5229 BlockByRefDecls.push_back(VD);
5232 // Find any imported blocks...they will need special attention.
5233 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5234 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
5235 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5236 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5237 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5239 InnerDeclRefsCount.push_back(countOfInnerDecls);
5241 std::string FuncName;
5244 FuncName = CurFunctionDef->getNameAsString();
5245 else if (CurMethodDef)
5246 BuildUniqueMethodName(FuncName, CurMethodDef);
5247 else if (GlobalVarDecl)
5248 FuncName = std::string(GlobalVarDecl->getNameAsString());
5250 bool GlobalBlockExpr =
5251 block->getDeclContext()->getRedeclContext()->isFileContext();
5253 if (GlobalBlockExpr && !GlobalVarDecl) {
5254 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5255 GlobalBlockExpr = false;
5258 std::string BlockNumber = utostr(Blocks.size()-1);
5260 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5262 // Get a pointer to the function type so we can cast appropriately.
5263 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5264 QualType FType = Context->getPointerType(BFT);
5269 // Simulate a constructor call...
5272 if (GlobalBlockExpr)
5276 Tag += FuncName + "_block_impl_" + BlockNumber;
5278 FD = SynthBlockInitFunctionDecl(Tag);
5279 DeclRefExpr *DRE = new (Context)
5280 DeclRefExpr(*Context, FD, false, FType, VK_RValue, SourceLocation());
5282 SmallVector<Expr*, 4> InitExprs;
5284 // Initialize the block function.
5285 FD = SynthBlockInitFunctionDecl(Func);
5286 DeclRefExpr *Arg = new (Context) DeclRefExpr(
5287 *Context, FD, false, FD->getType(), VK_LValue, SourceLocation());
5288 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5290 InitExprs.push_back(castExpr);
5292 // Initialize the block descriptor.
5293 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5295 VarDecl *NewVD = VarDecl::Create(
5296 *Context, TUDecl, SourceLocation(), SourceLocation(),
5297 &Context->Idents.get(DescData), Context->VoidPtrTy, nullptr, SC_Static);
5298 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
5299 new (Context) DeclRefExpr(*Context, NewVD, false, Context->VoidPtrTy,
5300 VK_LValue, SourceLocation()),
5301 UO_AddrOf, Context->getPointerType(Context->VoidPtrTy), VK_RValue,
5302 OK_Ordinary, SourceLocation(), false);
5303 InitExprs.push_back(DescRefExpr);
5305 // Add initializers for any closure decl refs.
5306 if (BlockDeclRefs.size()) {
5308 // Output all "by copy" declarations.
5309 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
5310 E = BlockByCopyDecls.end(); I != E; ++I) {
5311 if (isObjCType((*I)->getType())) {
5312 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5313 FD = SynthBlockInitFunctionDecl((*I)->getName());
5314 Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
5315 VK_LValue, SourceLocation());
5316 if (HasLocalVariableExternalStorage(*I)) {
5317 QualType QT = (*I)->getType();
5318 QT = Context->getPointerType(QT);
5319 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5320 OK_Ordinary, SourceLocation(),
5323 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5324 FD = SynthBlockInitFunctionDecl((*I)->getName());
5325 Arg = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
5326 VK_LValue, SourceLocation());
5327 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5330 FD = SynthBlockInitFunctionDecl((*I)->getName());
5331 Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
5332 VK_LValue, SourceLocation());
5333 if (HasLocalVariableExternalStorage(*I)) {
5334 QualType QT = (*I)->getType();
5335 QT = Context->getPointerType(QT);
5336 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5337 OK_Ordinary, SourceLocation(),
5342 InitExprs.push_back(Exp);
5344 // Output all "by ref" declarations.
5345 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
5346 E = BlockByRefDecls.end(); I != E; ++I) {
5347 ValueDecl *ND = (*I);
5348 std::string Name(ND->getNameAsString());
5349 std::string RecName;
5350 RewriteByRefString(RecName, Name, ND, true);
5351 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5352 + sizeof("struct"));
5353 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5354 SourceLocation(), SourceLocation(),
5356 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5357 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5359 FD = SynthBlockInitFunctionDecl((*I)->getName());
5360 Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
5361 VK_LValue, SourceLocation());
5362 bool isNestedCapturedVar = false;
5364 for (const auto &CI : block->captures()) {
5365 const VarDecl *variable = CI.getVariable();
5366 if (variable == ND && CI.isNested()) {
5367 assert (CI.isByRef() &&
5368 "SynthBlockInitExpr - captured block variable is not byref");
5369 isNestedCapturedVar = true;
5373 // captured nested byref variable has its address passed. Do not take
5374 // its address again.
5375 if (!isNestedCapturedVar)
5376 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5377 Context->getPointerType(Exp->getType()),
5378 VK_RValue, OK_Ordinary, SourceLocation(),
5380 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5381 InitExprs.push_back(Exp);
5384 if (ImportedBlockDecls.size()) {
5385 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5386 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5388 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5389 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5390 Context->IntTy, SourceLocation());
5391 InitExprs.push_back(FlagExp);
5393 NewRep = CallExpr::Create(*Context, DRE, InitExprs, FType, VK_LValue,
5396 if (GlobalBlockExpr) {
5397 assert (!GlobalConstructionExp &&
5398 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5399 GlobalConstructionExp = NewRep;
5403 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5404 Context->getPointerType(NewRep->getType()),
5405 VK_RValue, OK_Ordinary, SourceLocation(), false);
5406 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5408 // Put Paren around the call.
5409 NewRep = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
5412 BlockDeclRefs.clear();
5413 BlockByRefDecls.clear();
5414 BlockByRefDeclsPtrSet.clear();
5415 BlockByCopyDecls.clear();
5416 BlockByCopyDeclsPtrSet.clear();
5417 ImportedBlockDecls.clear();
5421 bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5422 if (const ObjCForCollectionStmt * CS =
5423 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5424 return CS->getElement() == DS;
5428 //===----------------------------------------------------------------------===//
5429 // Function Body / Expression rewriting
5430 //===----------------------------------------------------------------------===//
5432 Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5433 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5434 isa<DoStmt>(S) || isa<ForStmt>(S))
5436 else if (isa<ObjCForCollectionStmt>(S)) {
5438 ObjCBcLabelNo.push_back(++BcLabelCount);
5441 // Pseudo-object operations and ivar references need special
5442 // treatment because we're going to recursively rewrite them.
5443 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5444 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5445 return RewritePropertyOrImplicitSetter(PseudoOp);
5447 return RewritePropertyOrImplicitGetter(PseudoOp);
5449 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5450 return RewriteObjCIvarRefExpr(IvarRefExpr);
5452 else if (isa<OpaqueValueExpr>(S))
5453 S = cast<OpaqueValueExpr>(S)->getSourceExpr();
5455 SourceRange OrigStmtRange = S->getSourceRange();
5457 // Perform a bottom up rewrite of all children.
5458 for (Stmt *&childStmt : S->children())
5460 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5462 childStmt = newStmt;
5466 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
5467 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
5468 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5469 InnerContexts.insert(BE->getBlockDecl());
5470 ImportedLocalExternalDecls.clear();
5471 GetInnerBlockDeclRefExprs(BE->getBody(),
5472 InnerBlockDeclRefs, InnerContexts);
5473 // Rewrite the block body in place.
5474 Stmt *SaveCurrentBody = CurrentBody;
5475 CurrentBody = BE->getBody();
5476 PropParentMap = nullptr;
5477 // block literal on rhs of a property-dot-sytax assignment
5478 // must be replaced by its synthesize ast so getRewrittenText
5479 // works as expected. In this case, what actually ends up on RHS
5480 // is the blockTranscribed which is the helper function for the
5481 // block literal; as in: self.c = ^() {[ace ARR];};
5482 bool saveDisableReplaceStmt = DisableReplaceStmt;
5483 DisableReplaceStmt = false;
5484 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5485 DisableReplaceStmt = saveDisableReplaceStmt;
5486 CurrentBody = SaveCurrentBody;
5487 PropParentMap = nullptr;
5488 ImportedLocalExternalDecls.clear();
5489 // Now we snarf the rewritten text and stash it away for later use.
5490 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5491 RewrittenBlockExprs[BE] = Str;
5493 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5495 //blockTranscribed->dump();
5496 ReplaceStmt(S, blockTranscribed);
5497 return blockTranscribed;
5499 // Handle specific things.
5500 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5501 return RewriteAtEncode(AtEncode);
5503 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5504 return RewriteAtSelector(AtSelector);
5506 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5507 return RewriteObjCStringLiteral(AtString);
5509 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5510 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
5512 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5513 return RewriteObjCBoxedExpr(BoxedExpr);
5515 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5516 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
5518 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5519 dyn_cast<ObjCDictionaryLiteral>(S))
5520 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
5522 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5524 // Before we rewrite it, put the original message expression in a comment.
5525 SourceLocation startLoc = MessExpr->getBeginLoc();
5526 SourceLocation endLoc = MessExpr->getEndLoc();
5528 const char *startBuf = SM->getCharacterData(startLoc);
5529 const char *endBuf = SM->getCharacterData(endLoc);
5531 std::string messString;
5532 messString += "// ";
5533 messString.append(startBuf, endBuf-startBuf+1);
5536 // FIXME: Missing definition of
5537 // InsertText(clang::SourceLocation, char const*, unsigned int).
5538 // InsertText(startLoc, messString);
5539 // Tried this, but it didn't work either...
5540 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5542 return RewriteMessageExpr(MessExpr);
5545 if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
5546 dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5547 return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5550 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5551 return RewriteObjCTryStmt(StmtTry);
5553 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5554 return RewriteObjCSynchronizedStmt(StmtTry);
5556 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5557 return RewriteObjCThrowStmt(StmtThrow);
5559 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5560 return RewriteObjCProtocolExpr(ProtocolExp);
5562 if (ObjCForCollectionStmt *StmtForCollection =
5563 dyn_cast<ObjCForCollectionStmt>(S))
5564 return RewriteObjCForCollectionStmt(StmtForCollection,
5565 OrigStmtRange.getEnd());
5566 if (BreakStmt *StmtBreakStmt =
5567 dyn_cast<BreakStmt>(S))
5568 return RewriteBreakStmt(StmtBreakStmt);
5569 if (ContinueStmt *StmtContinueStmt =
5570 dyn_cast<ContinueStmt>(S))
5571 return RewriteContinueStmt(StmtContinueStmt);
5573 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5575 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5576 // FIXME: What we're doing here is modifying the type-specifier that
5577 // precedes the first Decl. In the future the DeclGroup should have
5578 // a separate type-specifier that we can rewrite.
5579 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5580 // the context of an ObjCForCollectionStmt. For example:
5581 // NSArray *someArray;
5582 // for (id <FooProtocol> index in someArray) ;
5583 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5584 // and it depends on the original text locations/positions.
5585 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5586 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5588 // Blocks rewrite rules.
5589 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5592 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5593 if (isTopLevelBlockPointerType(ND->getType()))
5594 RewriteBlockPointerDecl(ND);
5595 else if (ND->getType()->isFunctionPointerType())
5596 CheckFunctionPointerDecl(ND->getType(), ND);
5597 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5598 if (VD->hasAttr<BlocksAttr>()) {
5599 static unsigned uniqueByrefDeclCount = 0;
5600 assert(!BlockByRefDeclNo.count(ND) &&
5601 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5602 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
5603 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
5606 RewriteTypeOfDecl(VD);
5609 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5610 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5611 RewriteBlockPointerDecl(TD);
5612 else if (TD->getUnderlyingType()->isFunctionPointerType())
5613 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5618 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5619 RewriteObjCQualifiedInterfaceTypes(CE);
5621 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5622 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5623 assert(!Stmts.empty() && "Statement stack is empty");
5624 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5625 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5626 && "Statement stack mismatch");
5629 // Handle blocks rewriting.
5630 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5631 ValueDecl *VD = DRE->getDecl();
5632 if (VD->hasAttr<BlocksAttr>())
5633 return RewriteBlockDeclRefExpr(DRE);
5634 if (HasLocalVariableExternalStorage(VD))
5635 return RewriteLocalVariableExternalStorage(DRE);
5638 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5639 if (CE->getCallee()->getType()->isBlockPointerType()) {
5640 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5641 ReplaceStmt(S, BlockCall);
5645 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5646 RewriteCastExpr(CE);
5648 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5649 RewriteImplicitCastObjCExpr(ICE);
5653 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5654 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5657 // Get the new text.
5659 llvm::raw_string_ostream Buf(SStr);
5660 Replacement->printPretty(Buf);
5661 const std::string &Str = Buf.str();
5663 printf("CAST = %s\n", &Str[0]);
5664 InsertText(ICE->getSubExpr()->getBeginLoc(), Str);
5669 // Return this stmt unmodified.
5673 void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5674 for (auto *FD : RD->fields()) {
5675 if (isTopLevelBlockPointerType(FD->getType()))
5676 RewriteBlockPointerDecl(FD);
5677 if (FD->getType()->isObjCQualifiedIdType() ||
5678 FD->getType()->isObjCQualifiedInterfaceType())
5679 RewriteObjCQualifiedInterfaceTypes(FD);
5683 /// HandleDeclInMainFile - This is called for each top-level decl defined in the
5684 /// main file of the input.
5685 void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5686 switch (D->getKind()) {
5687 case Decl::Function: {
5688 FunctionDecl *FD = cast<FunctionDecl>(D);
5689 if (FD->isOverloadedOperator())
5692 // Since function prototypes don't have ParmDecl's, we check the function
5693 // prototype. This enables us to rewrite function declarations and
5694 // definitions using the same code.
5695 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5697 if (!FD->isThisDeclarationADefinition())
5700 // FIXME: If this should support Obj-C++, support CXXTryStmt
5701 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5702 CurFunctionDef = FD;
5705 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5707 CurrentBody = nullptr;
5708 if (PropParentMap) {
5709 delete PropParentMap;
5710 PropParentMap = nullptr;
5712 // This synthesizes and inserts the block "impl" struct, invoke function,
5713 // and any copy/dispose helper functions.
5714 InsertBlockLiteralsWithinFunction(FD);
5715 RewriteLineDirective(D);
5716 CurFunctionDef = nullptr;
5720 case Decl::ObjCMethod: {
5721 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5722 if (CompoundStmt *Body = MD->getCompoundBody()) {
5726 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5728 CurrentBody = nullptr;
5729 if (PropParentMap) {
5730 delete PropParentMap;
5731 PropParentMap = nullptr;
5733 InsertBlockLiteralsWithinMethod(MD);
5734 RewriteLineDirective(D);
5735 CurMethodDef = nullptr;
5739 case Decl::ObjCImplementation: {
5740 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5741 ClassImplementation.push_back(CI);
5744 case Decl::ObjCCategoryImpl: {
5745 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5746 CategoryImplementation.push_back(CI);
5750 VarDecl *VD = cast<VarDecl>(D);
5751 RewriteObjCQualifiedInterfaceTypes(VD);
5752 if (isTopLevelBlockPointerType(VD->getType()))
5753 RewriteBlockPointerDecl(VD);
5754 else if (VD->getType()->isFunctionPointerType()) {
5755 CheckFunctionPointerDecl(VD->getType(), VD);
5756 if (VD->getInit()) {
5757 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5758 RewriteCastExpr(CE);
5761 } else if (VD->getType()->isRecordType()) {
5762 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5763 if (RD->isCompleteDefinition())
5764 RewriteRecordBody(RD);
5766 if (VD->getInit()) {
5768 CurrentBody = VD->getInit();
5769 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5770 CurrentBody = nullptr;
5771 if (PropParentMap) {
5772 delete PropParentMap;
5773 PropParentMap = nullptr;
5775 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5776 GlobalVarDecl = nullptr;
5778 // This is needed for blocks.
5779 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5780 RewriteCastExpr(CE);
5785 case Decl::TypeAlias:
5786 case Decl::Typedef: {
5787 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5788 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5789 RewriteBlockPointerDecl(TD);
5790 else if (TD->getUnderlyingType()->isFunctionPointerType())
5791 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5793 RewriteObjCQualifiedInterfaceTypes(TD);
5797 case Decl::CXXRecord:
5798 case Decl::Record: {
5799 RecordDecl *RD = cast<RecordDecl>(D);
5800 if (RD->isCompleteDefinition())
5801 RewriteRecordBody(RD);
5810 /// Write_ProtocolExprReferencedMetadata - This routine writer out the
5811 /// protocol reference symbols in the for of:
5812 /// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5813 static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5814 ObjCProtocolDecl *PDecl,
5815 std::string &Result) {
5816 // Also output .objc_protorefs$B section and its meta-data.
5817 if (Context->getLangOpts().MicrosoftExt)
5818 Result += "static ";
5819 Result += "struct _protocol_t *";
5820 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5821 Result += PDecl->getNameAsString();
5823 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5827 void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5828 if (Diags.hasErrorOccurred())
5833 for (unsigned i = 0, e = FunctionDefinitionsSeen.size(); i < e; i++) {
5834 // translation of function bodies were postponed until all class and
5835 // their extensions and implementations are seen. This is because, we
5836 // cannot build grouping structs for bitfields until they are all seen.
5837 FunctionDecl *FDecl = FunctionDefinitionsSeen[i];
5838 HandleTopLevelSingleDecl(FDecl);
5841 // Here's a great place to add any extra declarations that may be needed.
5842 // Write out meta data for each @protocol(<expr>).
5843 for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls) {
5844 RewriteObjCProtocolMetaData(ProtDecl, Preamble);
5845 Write_ProtocolExprReferencedMetadata(Context, ProtDecl, Preamble);
5848 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
5850 if (ClassImplementation.size() || CategoryImplementation.size())
5851 RewriteImplementations();
5853 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5854 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5855 // Write struct declaration for the class matching its ivar declarations.
5856 // Note that for modern abi, this is postponed until the end of TU
5857 // because class extensions and the implementation might declare their own
5859 RewriteInterfaceDecl(CDecl);
5862 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5864 if (const RewriteBuffer *RewriteBuf =
5865 Rewrite.getRewriteBufferFor(MainFileID)) {
5866 //printf("Changed:\n");
5867 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5869 llvm::errs() << "No changes\n";
5872 if (ClassImplementation.size() || CategoryImplementation.size() ||
5873 ProtocolExprDecls.size()) {
5874 // Rewrite Objective-c meta data*
5875 std::string ResultStr;
5876 RewriteMetaDataIntoBuffer(ResultStr);
5878 *OutFile << ResultStr;
5882 std::string ResultStr;
5883 WriteImageInfo(ResultStr);
5884 *OutFile << ResultStr;
5889 void RewriteModernObjC::Initialize(ASTContext &context) {
5890 InitializeCommon(context);
5892 Preamble += "#ifndef __OBJC2__\n";
5893 Preamble += "#define __OBJC2__\n";
5894 Preamble += "#endif\n";
5896 // declaring objc_selector outside the parameter list removes a silly
5897 // scope related warning...
5899 Preamble = "#pragma once\n";
5900 Preamble += "struct objc_selector; struct objc_class;\n";
5901 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
5902 Preamble += "\n\tstruct objc_object *superClass; ";
5903 // Add a constructor for creating temporary objects.
5904 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
5905 Preamble += ": object(o), superClass(s) {} ";
5906 Preamble += "\n};\n";
5908 if (LangOpts.MicrosoftExt) {
5909 // Define all sections using syntax that makes sense.
5910 // These are currently generated.
5911 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
5912 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
5913 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
5914 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5915 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
5916 // These are generated but not necessary for functionality.
5917 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
5918 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5919 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
5920 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
5922 // These need be generated for performance. Currently they are not,
5923 // using API calls instead.
5924 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5925 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5926 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5929 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5930 Preamble += "typedef struct objc_object Protocol;\n";
5931 Preamble += "#define _REWRITER_typedef_Protocol\n";
5932 Preamble += "#endif\n";
5933 if (LangOpts.MicrosoftExt) {
5934 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5935 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
5938 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
5940 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
5941 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
5942 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
5943 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
5944 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
5946 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
5947 Preamble += "(const char *);\n";
5948 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5949 Preamble += "(struct objc_class *);\n";
5950 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
5951 Preamble += "(const char *);\n";
5952 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
5953 // @synchronized hooks.
5954 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
5955 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
5956 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5957 Preamble += "#ifdef _WIN64\n";
5958 Preamble += "typedef unsigned long long _WIN_NSUInteger;\n";
5959 Preamble += "#else\n";
5960 Preamble += "typedef unsigned int _WIN_NSUInteger;\n";
5961 Preamble += "#endif\n";
5962 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5963 Preamble += "struct __objcFastEnumerationState {\n\t";
5964 Preamble += "unsigned long state;\n\t";
5965 Preamble += "void **itemsPtr;\n\t";
5966 Preamble += "unsigned long *mutationsPtr;\n\t";
5967 Preamble += "unsigned long extra[5];\n};\n";
5968 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5969 Preamble += "#define __FASTENUMERATIONSTATE\n";
5970 Preamble += "#endif\n";
5971 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5972 Preamble += "struct __NSConstantStringImpl {\n";
5973 Preamble += " int *isa;\n";
5974 Preamble += " int flags;\n";
5975 Preamble += " char *str;\n";
5976 Preamble += "#if _WIN64\n";
5977 Preamble += " long long length;\n";
5978 Preamble += "#else\n";
5979 Preamble += " long length;\n";
5980 Preamble += "#endif\n";
5982 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5983 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5984 Preamble += "#else\n";
5985 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5986 Preamble += "#endif\n";
5987 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5988 Preamble += "#endif\n";
5990 Preamble += "#ifndef BLOCK_IMPL\n";
5991 Preamble += "#define BLOCK_IMPL\n";
5992 Preamble += "struct __block_impl {\n";
5993 Preamble += " void *isa;\n";
5994 Preamble += " int Flags;\n";
5995 Preamble += " int Reserved;\n";
5996 Preamble += " void *FuncPtr;\n";
5998 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5999 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
6000 Preamble += "extern \"C\" __declspec(dllexport) "
6001 "void _Block_object_assign(void *, const void *, const int);\n";
6002 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
6003 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
6004 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
6005 Preamble += "#else\n";
6006 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
6007 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
6008 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
6009 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
6010 Preamble += "#endif\n";
6011 Preamble += "#endif\n";
6012 if (LangOpts.MicrosoftExt) {
6013 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
6014 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
6015 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
6016 Preamble += "#define __attribute__(X)\n";
6017 Preamble += "#endif\n";
6018 Preamble += "#ifndef __weak\n";
6019 Preamble += "#define __weak\n";
6020 Preamble += "#endif\n";
6021 Preamble += "#ifndef __block\n";
6022 Preamble += "#define __block\n";
6023 Preamble += "#endif\n";
6026 Preamble += "#define __block\n";
6027 Preamble += "#define __weak\n";
6030 // Declarations required for modern objective-c array and dictionary literals.
6031 Preamble += "\n#include <stdarg.h>\n";
6032 Preamble += "struct __NSContainer_literal {\n";
6033 Preamble += " void * *arr;\n";
6034 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
6035 Preamble += "\tva_list marker;\n";
6036 Preamble += "\tva_start(marker, count);\n";
6037 Preamble += "\tarr = new void *[count];\n";
6038 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
6039 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
6040 Preamble += "\tva_end( marker );\n";
6041 Preamble += " };\n";
6042 Preamble += " ~__NSContainer_literal() {\n";
6043 Preamble += "\tdelete[] arr;\n";
6047 // Declaration required for implementation of @autoreleasepool statement.
6048 Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
6049 Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
6050 Preamble += "struct __AtAutoreleasePool {\n";
6051 Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
6052 Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
6053 Preamble += " void * atautoreleasepoolobj;\n";
6056 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
6057 // as this avoids warning in any 64bit/32bit compilation model.
6058 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6061 /// RewriteIvarOffsetComputation - This routine synthesizes computation of
6063 void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
6064 std::string &Result) {
6065 Result += "__OFFSETOFIVAR__(struct ";
6066 Result += ivar->getContainingInterface()->getNameAsString();
6067 if (LangOpts.MicrosoftExt)
6070 if (ivar->isBitField())
6071 ObjCIvarBitfieldGroupDecl(ivar, Result);
6073 Result += ivar->getNameAsString();
6077 /// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6078 /// struct _prop_t {
6079 /// const char *name;
6080 /// char *attributes;
6083 /// struct _prop_list_t {
6084 /// uint32_t entsize; // sizeof(struct _prop_t)
6085 /// uint32_t count_of_properties;
6086 /// struct _prop_t prop_list[count_of_properties];
6089 /// struct _protocol_t;
6091 /// struct _protocol_list_t {
6092 /// long protocol_count; // Note, this is 32/64 bit
6093 /// struct _protocol_t * protocol_list[protocol_count];
6096 /// struct _objc_method {
6098 /// const char *method_type;
6102 /// struct _method_list_t {
6103 /// uint32_t entsize; // sizeof(struct _objc_method)
6104 /// uint32_t method_count;
6105 /// struct _objc_method method_list[method_count];
6108 /// struct _protocol_t {
6110 /// const char *protocol_name;
6111 /// const struct _protocol_list_t * protocol_list; // super protocols
6112 /// const struct method_list_t *instance_methods;
6113 /// const struct method_list_t *class_methods;
6114 /// const struct method_list_t *optionalInstanceMethods;
6115 /// const struct method_list_t *optionalClassMethods;
6116 /// const struct _prop_list_t * properties;
6117 /// const uint32_t size; // sizeof(struct _protocol_t)
6118 /// const uint32_t flags; // = 0
6119 /// const char ** extendedMethodTypes;
6122 /// struct _ivar_t {
6123 /// unsigned long int *offset; // pointer to ivar offset location
6124 /// const char *name;
6125 /// const char *type;
6126 /// uint32_t alignment;
6130 /// struct _ivar_list_t {
6131 /// uint32 entsize; // sizeof(struct _ivar_t)
6133 /// struct _ivar_t list[count];
6136 /// struct _class_ro_t {
6138 /// uint32_t instanceStart;
6139 /// uint32_t instanceSize;
6140 /// uint32_t reserved; // only when building for 64bit targets
6141 /// const uint8_t *ivarLayout;
6142 /// const char *name;
6143 /// const struct _method_list_t *baseMethods;
6144 /// const struct _protocol_list_t *baseProtocols;
6145 /// const struct _ivar_list_t *ivars;
6146 /// const uint8_t *weakIvarLayout;
6147 /// const struct _prop_list_t *properties;
6150 /// struct _class_t {
6151 /// struct _class_t *isa;
6152 /// struct _class_t *superclass;
6155 /// struct _class_ro_t *ro;
6158 /// struct _category_t {
6159 /// const char *name;
6160 /// struct _class_t *cls;
6161 /// const struct _method_list_t *instance_methods;
6162 /// const struct _method_list_t *class_methods;
6163 /// const struct _protocol_list_t *protocols;
6164 /// const struct _prop_list_t *properties;
6167 /// MessageRefTy - LLVM for:
6168 /// struct _message_ref_t {
6173 /// SuperMessageRefTy - LLVM for:
6174 /// struct _super_message_ref_t {
6175 /// SUPER_IMP messenger;
6179 static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
6180 static bool meta_data_declared = false;
6181 if (meta_data_declared)
6184 Result += "\nstruct _prop_t {\n";
6185 Result += "\tconst char *name;\n";
6186 Result += "\tconst char *attributes;\n";
6189 Result += "\nstruct _protocol_t;\n";
6191 Result += "\nstruct _objc_method {\n";
6192 Result += "\tstruct objc_selector * _cmd;\n";
6193 Result += "\tconst char *method_type;\n";
6194 Result += "\tvoid *_imp;\n";
6197 Result += "\nstruct _protocol_t {\n";
6198 Result += "\tvoid * isa; // NULL\n";
6199 Result += "\tconst char *protocol_name;\n";
6200 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
6201 Result += "\tconst struct method_list_t *instance_methods;\n";
6202 Result += "\tconst struct method_list_t *class_methods;\n";
6203 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6204 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6205 Result += "\tconst struct _prop_list_t * properties;\n";
6206 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
6207 Result += "\tconst unsigned int flags; // = 0\n";
6208 Result += "\tconst char ** extendedMethodTypes;\n";
6211 Result += "\nstruct _ivar_t {\n";
6212 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
6213 Result += "\tconst char *name;\n";
6214 Result += "\tconst char *type;\n";
6215 Result += "\tunsigned int alignment;\n";
6216 Result += "\tunsigned int size;\n";
6219 Result += "\nstruct _class_ro_t {\n";
6220 Result += "\tunsigned int flags;\n";
6221 Result += "\tunsigned int instanceStart;\n";
6222 Result += "\tunsigned int instanceSize;\n";
6223 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6224 if (Triple.getArch() == llvm::Triple::x86_64)
6225 Result += "\tunsigned int reserved;\n";
6226 Result += "\tconst unsigned char *ivarLayout;\n";
6227 Result += "\tconst char *name;\n";
6228 Result += "\tconst struct _method_list_t *baseMethods;\n";
6229 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6230 Result += "\tconst struct _ivar_list_t *ivars;\n";
6231 Result += "\tconst unsigned char *weakIvarLayout;\n";
6232 Result += "\tconst struct _prop_list_t *properties;\n";
6235 Result += "\nstruct _class_t {\n";
6236 Result += "\tstruct _class_t *isa;\n";
6237 Result += "\tstruct _class_t *superclass;\n";
6238 Result += "\tvoid *cache;\n";
6239 Result += "\tvoid *vtable;\n";
6240 Result += "\tstruct _class_ro_t *ro;\n";
6243 Result += "\nstruct _category_t {\n";
6244 Result += "\tconst char *name;\n";
6245 Result += "\tstruct _class_t *cls;\n";
6246 Result += "\tconst struct _method_list_t *instance_methods;\n";
6247 Result += "\tconst struct _method_list_t *class_methods;\n";
6248 Result += "\tconst struct _protocol_list_t *protocols;\n";
6249 Result += "\tconst struct _prop_list_t *properties;\n";
6252 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
6253 Result += "#pragma warning(disable:4273)\n";
6254 meta_data_declared = true;
6257 static void Write_protocol_list_t_TypeDecl(std::string &Result,
6258 long super_protocol_count) {
6259 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6260 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6261 Result += "\tstruct _protocol_t *super_protocols[";
6262 Result += utostr(super_protocol_count); Result += "];\n";
6266 static void Write_method_list_t_TypeDecl(std::string &Result,
6267 unsigned int method_count) {
6268 Result += "struct /*_method_list_t*/"; Result += " {\n";
6269 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6270 Result += "\tunsigned int method_count;\n";
6271 Result += "\tstruct _objc_method method_list[";
6272 Result += utostr(method_count); Result += "];\n";
6276 static void Write__prop_list_t_TypeDecl(std::string &Result,
6277 unsigned int property_count) {
6278 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6279 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6280 Result += "\tunsigned int count_of_properties;\n";
6281 Result += "\tstruct _prop_t prop_list[";
6282 Result += utostr(property_count); Result += "];\n";
6286 static void Write__ivar_list_t_TypeDecl(std::string &Result,
6287 unsigned int ivar_count) {
6288 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6289 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6290 Result += "\tunsigned int count;\n";
6291 Result += "\tstruct _ivar_t ivar_list[";
6292 Result += utostr(ivar_count); Result += "];\n";
6296 static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6297 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6299 StringRef ProtocolName) {
6300 if (SuperProtocols.size() > 0) {
6301 Result += "\nstatic ";
6302 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6303 Result += " "; Result += VarName;
6304 Result += ProtocolName;
6305 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6306 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6307 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6308 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6309 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6310 Result += SuperPD->getNameAsString();
6319 static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6320 ASTContext *Context, std::string &Result,
6321 ArrayRef<ObjCMethodDecl *> Methods,
6323 StringRef TopLevelDeclName,
6325 if (Methods.size() > 0) {
6326 Result += "\nstatic ";
6327 Write_method_list_t_TypeDecl(Result, Methods.size());
6328 Result += " "; Result += VarName;
6329 Result += TopLevelDeclName;
6330 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6331 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6332 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6333 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6334 ObjCMethodDecl *MD = Methods[i];
6336 Result += "\t{{(struct objc_selector *)\"";
6338 Result += "\t{(struct objc_selector *)\"";
6339 Result += (MD)->getSelector().getAsString(); Result += "\"";
6341 std::string MethodTypeString = Context->getObjCEncodingForMethodDecl(MD);
6342 Result += "\""; Result += MethodTypeString; Result += "\"";
6347 Result += "(void *)";
6348 Result += RewriteObj.MethodInternalNames[MD];
6359 static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
6360 ASTContext *Context, std::string &Result,
6361 ArrayRef<ObjCPropertyDecl *> Properties,
6362 const Decl *Container,
6364 StringRef ProtocolName) {
6365 if (Properties.size() > 0) {
6366 Result += "\nstatic ";
6367 Write__prop_list_t_TypeDecl(Result, Properties.size());
6368 Result += " "; Result += VarName;
6369 Result += ProtocolName;
6370 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6371 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6372 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6373 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6374 ObjCPropertyDecl *PropDecl = Properties[i];
6379 Result += PropDecl->getName(); Result += "\",";
6380 std::string PropertyTypeString =
6381 Context->getObjCEncodingForPropertyDecl(PropDecl, Container);
6382 std::string QuotePropertyTypeString;
6383 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6384 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6395 enum MetaDataDlags {
6399 OBJC2_CLS_HIDDEN = 0x10,
6400 CLS_EXCEPTION = 0x20,
6402 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6403 CLS_HAS_IVAR_RELEASER = 0x40,
6404 /// class was compiled with -fobjc-arr
6405 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6408 static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6410 const std::string &InstanceStart,
6411 const std::string &InstanceSize,
6412 ArrayRef<ObjCMethodDecl *>baseMethods,
6413 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6414 ArrayRef<ObjCIvarDecl *>ivars,
6415 ArrayRef<ObjCPropertyDecl *>Properties,
6417 StringRef ClassName) {
6418 Result += "\nstatic struct _class_ro_t ";
6419 Result += VarName; Result += ClassName;
6420 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6422 Result += llvm::utostr(flags); Result += ", ";
6423 Result += InstanceStart; Result += ", ";
6424 Result += InstanceSize; Result += ", \n";
6426 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6427 if (Triple.getArch() == llvm::Triple::x86_64)
6428 // uint32_t const reserved; // only when building for 64bit targets
6429 Result += "(unsigned int)0, \n\t";
6430 // const uint8_t * const ivarLayout;
6431 Result += "0, \n\t";
6432 Result += "\""; Result += ClassName; Result += "\",\n\t";
6433 bool metaclass = ((flags & CLS_META) != 0);
6434 if (baseMethods.size() > 0) {
6435 Result += "(const struct _method_list_t *)&";
6437 Result += "_OBJC_$_CLASS_METHODS_";
6439 Result += "_OBJC_$_INSTANCE_METHODS_";
6440 Result += ClassName;
6444 Result += "0, \n\t";
6446 if (!metaclass && baseProtocols.size() > 0) {
6447 Result += "(const struct _objc_protocol_list *)&";
6448 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6452 Result += "0, \n\t";
6454 if (!metaclass && ivars.size() > 0) {
6455 Result += "(const struct _ivar_list_t *)&";
6456 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6460 Result += "0, \n\t";
6463 Result += "0, \n\t";
6464 if (!metaclass && Properties.size() > 0) {
6465 Result += "(const struct _prop_list_t *)&";
6466 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
6475 static void Write_class_t(ASTContext *Context, std::string &Result,
6477 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6478 bool rootClass = (!CDecl->getSuperClass());
6479 const ObjCInterfaceDecl *RootClass = CDecl;
6482 // Find the Root class
6483 RootClass = CDecl->getSuperClass();
6484 while (RootClass->getSuperClass()) {
6485 RootClass = RootClass->getSuperClass();
6489 if (metaclass && rootClass) {
6490 // Need to handle a case of use of forward declaration.
6492 Result += "extern \"C\" ";
6493 if (CDecl->getImplementation())
6494 Result += "__declspec(dllexport) ";
6496 Result += "__declspec(dllimport) ";
6498 Result += "struct _class_t OBJC_CLASS_$_";
6499 Result += CDecl->getNameAsString();
6502 // Also, for possibility of 'super' metadata class not having been defined yet.
6504 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
6506 Result += "extern \"C\" ";
6507 if (SuperClass->getImplementation())
6508 Result += "__declspec(dllexport) ";
6510 Result += "__declspec(dllimport) ";
6512 Result += "struct _class_t ";
6514 Result += SuperClass->getNameAsString();
6517 if (metaclass && RootClass != SuperClass) {
6518 Result += "extern \"C\" ";
6519 if (RootClass->getImplementation())
6520 Result += "__declspec(dllexport) ";
6522 Result += "__declspec(dllimport) ";
6524 Result += "struct _class_t ";
6526 Result += RootClass->getNameAsString();
6531 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6532 Result += VarName; Result += CDecl->getNameAsString();
6533 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6537 Result += "0, // &"; Result += VarName;
6538 Result += RootClass->getNameAsString();
6540 Result += "0, // &"; Result += VarName;
6541 Result += CDecl->getSuperClass()->getNameAsString();
6545 Result += "0, // &"; Result += VarName;
6546 Result += CDecl->getNameAsString();
6548 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6553 Result += "0, // &OBJC_METACLASS_$_";
6554 Result += CDecl->getNameAsString();
6557 Result += "0, // &"; Result += VarName;
6558 Result += CDecl->getSuperClass()->getNameAsString();
6564 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6565 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6567 Result += "&_OBJC_METACLASS_RO_$_";
6569 Result += "&_OBJC_CLASS_RO_$_";
6570 Result += CDecl->getNameAsString();
6571 Result += ",\n};\n";
6573 // Add static function to initialize some of the meta-data fields.
6574 // avoid doing it twice.
6578 const ObjCInterfaceDecl *SuperClass =
6579 rootClass ? CDecl : CDecl->getSuperClass();
6581 Result += "static void OBJC_CLASS_SETUP_$_";
6582 Result += CDecl->getNameAsString();
6583 Result += "(void ) {\n";
6584 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6585 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6586 Result += RootClass->getNameAsString(); Result += ";\n";
6588 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6589 Result += ".superclass = ";
6591 Result += "&OBJC_CLASS_$_";
6593 Result += "&OBJC_METACLASS_$_";
6595 Result += SuperClass->getNameAsString(); Result += ";\n";
6597 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6598 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6600 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6601 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6602 Result += CDecl->getNameAsString(); Result += ";\n";
6605 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6606 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6607 Result += SuperClass->getNameAsString(); Result += ";\n";
6610 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6611 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6615 static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6616 std::string &Result,
6617 ObjCCategoryDecl *CatDecl,
6618 ObjCInterfaceDecl *ClassDecl,
6619 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6620 ArrayRef<ObjCMethodDecl *> ClassMethods,
6621 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6622 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
6623 StringRef CatName = CatDecl->getName();
6624 StringRef ClassName = ClassDecl->getName();
6625 // must declare an extern class object in case this class is not implemented
6628 Result += "extern \"C\" ";
6629 if (ClassDecl->getImplementation())
6630 Result += "__declspec(dllexport) ";
6632 Result += "__declspec(dllimport) ";
6634 Result += "struct _class_t ";
6635 Result += "OBJC_CLASS_$_"; Result += ClassName;
6638 Result += "\nstatic struct _category_t ";
6639 Result += "_OBJC_$_CATEGORY_";
6640 Result += ClassName; Result += "_$_"; Result += CatName;
6641 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6643 Result += "\t\""; Result += ClassName; Result += "\",\n";
6644 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
6646 if (InstanceMethods.size() > 0) {
6647 Result += "\t(const struct _method_list_t *)&";
6648 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6649 Result += ClassName; Result += "_$_"; Result += CatName;
6655 if (ClassMethods.size() > 0) {
6656 Result += "\t(const struct _method_list_t *)&";
6657 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6658 Result += ClassName; Result += "_$_"; Result += CatName;
6664 if (RefedProtocols.size() > 0) {
6665 Result += "\t(const struct _protocol_list_t *)&";
6666 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6667 Result += ClassName; Result += "_$_"; Result += CatName;
6673 if (ClassProperties.size() > 0) {
6674 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6675 Result += ClassName; Result += "_$_"; Result += CatName;
6683 // Add static function to initialize the class pointer in the category structure.
6684 Result += "static void OBJC_CATEGORY_SETUP_$_";
6685 Result += ClassDecl->getNameAsString();
6688 Result += "(void ) {\n";
6689 Result += "\t_OBJC_$_CATEGORY_";
6690 Result += ClassDecl->getNameAsString();
6693 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6697 static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6698 ASTContext *Context, std::string &Result,
6699 ArrayRef<ObjCMethodDecl *> Methods,
6701 StringRef ProtocolName) {
6702 if (Methods.size() == 0)
6705 Result += "\nstatic const char *";
6706 Result += VarName; Result += ProtocolName;
6707 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6709 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6710 ObjCMethodDecl *MD = Methods[i];
6711 std::string MethodTypeString =
6712 Context->getObjCEncodingForMethodDecl(MD, true);
6713 std::string QuoteMethodTypeString;
6714 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6715 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6724 static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6725 ASTContext *Context,
6726 std::string &Result,
6727 ArrayRef<ObjCIvarDecl *> Ivars,
6728 ObjCInterfaceDecl *CDecl) {
6729 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6730 // this is what happens:
6732 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6733 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6734 Class->getVisibility() == HiddenVisibility)
6735 Visibility should be: HiddenVisibility;
6737 Visibility should be: DefaultVisibility;
6741 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6742 ObjCIvarDecl *IvarDecl = Ivars[i];
6743 if (Context->getLangOpts().MicrosoftExt)
6744 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6746 if (!Context->getLangOpts().MicrosoftExt ||
6747 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
6748 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
6749 Result += "extern \"C\" unsigned long int ";
6751 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
6752 if (Ivars[i]->isBitField())
6753 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6755 WriteInternalIvarName(CDecl, IvarDecl, Result);
6756 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6758 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6760 if (Ivars[i]->isBitField()) {
6761 // skip over rest of the ivar bitfields.
6762 SKIP_BITFIELDS(i , e, Ivars);
6767 static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6768 ASTContext *Context, std::string &Result,
6769 ArrayRef<ObjCIvarDecl *> OriginalIvars,
6771 ObjCInterfaceDecl *CDecl) {
6772 if (OriginalIvars.size() > 0) {
6773 Write_IvarOffsetVar(RewriteObj, Context, Result, OriginalIvars, CDecl);
6774 SmallVector<ObjCIvarDecl *, 8> Ivars;
6775 // strip off all but the first ivar bitfield from each group of ivars.
6776 // Such ivars in the ivar list table will be replaced by their grouping struct
6778 for (unsigned i = 0, e = OriginalIvars.size(); i < e; i++) {
6779 if (OriginalIvars[i]->isBitField()) {
6780 Ivars.push_back(OriginalIvars[i]);
6781 // skip over rest of the ivar bitfields.
6782 SKIP_BITFIELDS(i , e, OriginalIvars);
6785 Ivars.push_back(OriginalIvars[i]);
6788 Result += "\nstatic ";
6789 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6790 Result += " "; Result += VarName;
6791 Result += CDecl->getNameAsString();
6792 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6793 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6794 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6795 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6796 ObjCIvarDecl *IvarDecl = Ivars[i];
6801 Result += "(unsigned long int *)&";
6802 if (Ivars[i]->isBitField())
6803 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6805 WriteInternalIvarName(CDecl, IvarDecl, Result);
6809 if (Ivars[i]->isBitField())
6810 RewriteObj.ObjCIvarBitfieldGroupDecl(Ivars[i], Result);
6812 Result += IvarDecl->getName();
6815 QualType IVQT = IvarDecl->getType();
6816 if (IvarDecl->isBitField())
6817 IVQT = RewriteObj.GetGroupRecordTypeForObjCIvarBitfield(IvarDecl);
6819 std::string IvarTypeString, QuoteIvarTypeString;
6820 Context->getObjCEncodingForType(IVQT, IvarTypeString,
6822 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6823 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6825 // FIXME. this alignment represents the host alignment and need be changed to
6826 // represent the target alignment.
6827 unsigned Align = Context->getTypeAlign(IVQT)/8;
6828 Align = llvm::Log2_32(Align);
6829 Result += llvm::utostr(Align); Result += ", ";
6830 CharUnits Size = Context->getTypeSizeInChars(IVQT);
6831 Result += llvm::utostr(Size.getQuantity());
6841 /// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
6842 void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
6843 std::string &Result) {
6845 // Do not synthesize the protocol more than once.
6846 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6848 WriteModernMetadataDeclarations(Context, Result);
6850 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6852 // Must write out all protocol definitions in current qualifier list,
6853 // and in their nested qualifiers before writing out current definition.
6854 for (auto *I : PDecl->protocols())
6855 RewriteObjCProtocolMetaData(I, Result);
6857 // Construct method lists.
6858 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6859 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
6860 for (auto *MD : PDecl->instance_methods()) {
6861 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6862 OptInstanceMethods.push_back(MD);
6864 InstanceMethods.push_back(MD);
6868 for (auto *MD : PDecl->class_methods()) {
6869 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6870 OptClassMethods.push_back(MD);
6872 ClassMethods.push_back(MD);
6875 std::vector<ObjCMethodDecl *> AllMethods;
6876 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6877 AllMethods.push_back(InstanceMethods[i]);
6878 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6879 AllMethods.push_back(ClassMethods[i]);
6880 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6881 AllMethods.push_back(OptInstanceMethods[i]);
6882 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6883 AllMethods.push_back(OptClassMethods[i]);
6885 Write__extendedMethodTypes_initializer(*this, Context, Result,
6887 "_OBJC_PROTOCOL_METHOD_TYPES_",
6888 PDecl->getNameAsString());
6889 // Protocol's super protocol list
6890 SmallVector<ObjCProtocolDecl *, 8> SuperProtocols(PDecl->protocols());
6891 Write_protocol_list_initializer(Context, Result, SuperProtocols,
6892 "_OBJC_PROTOCOL_REFS_",
6893 PDecl->getNameAsString());
6895 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6896 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
6897 PDecl->getNameAsString(), false);
6899 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6900 "_OBJC_PROTOCOL_CLASS_METHODS_",
6901 PDecl->getNameAsString(), false);
6903 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
6904 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
6905 PDecl->getNameAsString(), false);
6907 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
6908 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
6909 PDecl->getNameAsString(), false);
6911 // Protocol's property metadata.
6912 SmallVector<ObjCPropertyDecl *, 8> ProtocolProperties(
6913 PDecl->instance_properties());
6914 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
6915 /* Container */nullptr,
6916 "_OBJC_PROTOCOL_PROPERTIES_",
6917 PDecl->getNameAsString());
6919 // Writer out root metadata for current protocol: struct _protocol_t
6921 if (LangOpts.MicrosoftExt)
6922 Result += "static ";
6923 Result += "struct _protocol_t _OBJC_PROTOCOL_";
6924 Result += PDecl->getNameAsString();
6925 Result += " __attribute__ ((used)) = {\n";
6926 Result += "\t0,\n"; // id is; is null
6927 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
6928 if (SuperProtocols.size() > 0) {
6929 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6930 Result += PDecl->getNameAsString(); Result += ",\n";
6934 if (InstanceMethods.size() > 0) {
6935 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
6936 Result += PDecl->getNameAsString(); Result += ",\n";
6941 if (ClassMethods.size() > 0) {
6942 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
6943 Result += PDecl->getNameAsString(); Result += ",\n";
6948 if (OptInstanceMethods.size() > 0) {
6949 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
6950 Result += PDecl->getNameAsString(); Result += ",\n";
6955 if (OptClassMethods.size() > 0) {
6956 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
6957 Result += PDecl->getNameAsString(); Result += ",\n";
6962 if (ProtocolProperties.size() > 0) {
6963 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
6964 Result += PDecl->getNameAsString(); Result += ",\n";
6969 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6972 if (AllMethods.size() > 0) {
6973 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6974 Result += PDecl->getNameAsString();
6978 Result += "\t0\n};\n";
6980 if (LangOpts.MicrosoftExt)
6981 Result += "static ";
6982 Result += "struct _protocol_t *";
6983 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6984 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6987 // Mark this protocol as having been generated.
6988 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()).second)
6989 llvm_unreachable("protocol already synthesized");
6992 /// hasObjCExceptionAttribute - Return true if this class or any super
6993 /// class has the __objc_exception__ attribute.
6994 /// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
6995 static bool hasObjCExceptionAttribute(ASTContext &Context,
6996 const ObjCInterfaceDecl *OID) {
6997 if (OID->hasAttr<ObjCExceptionAttr>())
6999 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
7000 return hasObjCExceptionAttribute(Context, Super);
7004 void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
7005 std::string &Result) {
7006 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7008 // Explicitly declared @interface's are already synthesized.
7009 if (CDecl->isImplicitInterfaceDecl())
7011 "Legacy implicit interface rewriting not supported in moder abi");
7013 WriteModernMetadataDeclarations(Context, Result);
7014 SmallVector<ObjCIvarDecl *, 8> IVars;
7016 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7017 IVD; IVD = IVD->getNextIvar()) {
7018 // Ignore unnamed bit-fields.
7019 if (!IVD->getDeclName())
7021 IVars.push_back(IVD);
7024 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
7025 "_OBJC_$_INSTANCE_VARIABLES_",
7028 // Build _objc_method_list for class's instance methods if needed
7029 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
7031 // If any of our property implementations have associated getters or
7032 // setters, produce metadata for them as well.
7033 for (const auto *Prop : IDecl->property_impls()) {
7034 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
7036 if (!Prop->getPropertyIvarDecl())
7038 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
7041 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7042 if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
7043 InstanceMethods.push_back(Getter);
7044 if (PD->isReadOnly())
7046 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7047 if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
7048 InstanceMethods.push_back(Setter);
7051 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7052 "_OBJC_$_INSTANCE_METHODS_",
7053 IDecl->getNameAsString(), true);
7055 SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
7057 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7058 "_OBJC_$_CLASS_METHODS_",
7059 IDecl->getNameAsString(), true);
7061 // Protocols referenced in class declaration?
7062 // Protocol's super protocol list
7063 std::vector<ObjCProtocolDecl *> RefedProtocols;
7064 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7065 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7066 E = Protocols.end();
7068 RefedProtocols.push_back(*I);
7069 // Must write out all protocol definitions in current qualifier list,
7070 // and in their nested qualifiers before writing out current definition.
7071 RewriteObjCProtocolMetaData(*I, Result);
7074 Write_protocol_list_initializer(Context, Result,
7076 "_OBJC_CLASS_PROTOCOLS_$_",
7077 IDecl->getNameAsString());
7079 // Protocol's property metadata.
7080 SmallVector<ObjCPropertyDecl *, 8> ClassProperties(
7081 CDecl->instance_properties());
7082 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
7083 /* Container */IDecl,
7084 "_OBJC_$_PROP_LIST_",
7085 CDecl->getNameAsString());
7087 // Data for initializing _class_ro_t metaclass meta-data
7088 uint32_t flags = CLS_META;
7089 std::string InstanceSize;
7090 std::string InstanceStart;
7092 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7094 flags |= OBJC2_CLS_HIDDEN;
7096 if (!CDecl->getSuperClass())
7099 InstanceSize = "sizeof(struct _class_t)";
7100 InstanceStart = InstanceSize;
7101 Write__class_ro_t_initializer(Context, Result, flags,
7102 InstanceStart, InstanceSize,
7107 "_OBJC_METACLASS_RO_$_",
7108 CDecl->getNameAsString());
7110 // Data for initializing _class_ro_t meta-data
7113 flags |= OBJC2_CLS_HIDDEN;
7115 if (hasObjCExceptionAttribute(*Context, CDecl))
7116 flags |= CLS_EXCEPTION;
7118 if (!CDecl->getSuperClass())
7122 InstanceSize.clear();
7123 InstanceStart.clear();
7124 if (!ObjCSynthesizedStructs.count(CDecl)) {
7126 InstanceStart = "0";
7129 InstanceSize = "sizeof(struct ";
7130 InstanceSize += CDecl->getNameAsString();
7131 InstanceSize += "_IMPL)";
7133 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7135 RewriteIvarOffsetComputation(IVD, InstanceStart);
7138 InstanceStart = InstanceSize;
7140 Write__class_ro_t_initializer(Context, Result, flags,
7141 InstanceStart, InstanceSize,
7146 "_OBJC_CLASS_RO_$_",
7147 CDecl->getNameAsString());
7149 Write_class_t(Context, Result,
7150 "OBJC_METACLASS_$_",
7151 CDecl, /*metaclass*/true);
7153 Write_class_t(Context, Result,
7155 CDecl, /*metaclass*/false);
7157 if (ImplementationIsNonLazy(IDecl))
7158 DefinedNonLazyClasses.push_back(CDecl);
7161 void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7162 int ClsDefCount = ClassImplementation.size();
7165 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7166 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7167 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7168 for (int i = 0; i < ClsDefCount; i++) {
7169 ObjCImplementationDecl *IDecl = ClassImplementation[i];
7170 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7171 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7172 Result += CDecl->getName(); Result += ",\n";
7177 void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7178 int ClsDefCount = ClassImplementation.size();
7179 int CatDefCount = CategoryImplementation.size();
7181 // For each implemented class, write out all its meta data.
7182 for (int i = 0; i < ClsDefCount; i++)
7183 RewriteObjCClassMetaData(ClassImplementation[i], Result);
7185 RewriteClassSetupInitHook(Result);
7187 // For each implemented category, write out all its meta data.
7188 for (int i = 0; i < CatDefCount; i++)
7189 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7191 RewriteCategorySetupInitHook(Result);
7193 if (ClsDefCount > 0) {
7194 if (LangOpts.MicrosoftExt)
7195 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
7196 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7197 Result += llvm::utostr(ClsDefCount); Result += "]";
7199 " __attribute__((used, section (\"__DATA, __objc_classlist,"
7200 "regular,no_dead_strip\")))= {\n";
7201 for (int i = 0; i < ClsDefCount; i++) {
7202 Result += "\t&OBJC_CLASS_$_";
7203 Result += ClassImplementation[i]->getNameAsString();
7208 if (!DefinedNonLazyClasses.empty()) {
7209 if (LangOpts.MicrosoftExt)
7210 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7211 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7212 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7213 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7220 if (CatDefCount > 0) {
7221 if (LangOpts.MicrosoftExt)
7222 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
7223 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7224 Result += llvm::utostr(CatDefCount); Result += "]";
7226 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7227 "regular,no_dead_strip\")))= {\n";
7228 for (int i = 0; i < CatDefCount; i++) {
7229 Result += "\t&_OBJC_$_CATEGORY_";
7231 CategoryImplementation[i]->getClassInterface()->getNameAsString();
7233 Result += CategoryImplementation[i]->getNameAsString();
7239 if (!DefinedNonLazyCategories.empty()) {
7240 if (LangOpts.MicrosoftExt)
7241 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7242 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7243 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7244 Result += "\t&_OBJC_$_CATEGORY_";
7246 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7248 Result += DefinedNonLazyCategories[i]->getNameAsString();
7255 void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7256 if (LangOpts.MicrosoftExt)
7257 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7259 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7260 // version 0, ObjCABI is 2
7261 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
7264 /// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7266 void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7267 std::string &Result) {
7268 WriteModernMetadataDeclarations(Context, Result);
7269 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7270 // Find category declaration for this implementation.
7271 ObjCCategoryDecl *CDecl
7272 = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
7274 std::string FullCategoryName = ClassDecl->getNameAsString();
7275 FullCategoryName += "_$_";
7276 FullCategoryName += CDecl->getNameAsString();
7278 // Build _objc_method_list for class's instance methods if needed
7279 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
7281 // If any of our property implementations have associated getters or
7282 // setters, produce metadata for them as well.
7283 for (const auto *Prop : IDecl->property_impls()) {
7284 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
7286 if (!Prop->getPropertyIvarDecl())
7288 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
7291 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7292 InstanceMethods.push_back(Getter);
7293 if (PD->isReadOnly())
7295 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7296 InstanceMethods.push_back(Setter);
7299 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7300 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7301 FullCategoryName, true);
7303 SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
7305 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7306 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7307 FullCategoryName, true);
7309 // Protocols referenced in class declaration?
7310 // Protocol's super protocol list
7311 SmallVector<ObjCProtocolDecl *, 8> RefedProtocols(CDecl->protocols());
7312 for (auto *I : CDecl->protocols())
7313 // Must write out all protocol definitions in current qualifier list,
7314 // and in their nested qualifiers before writing out current definition.
7315 RewriteObjCProtocolMetaData(I, Result);
7317 Write_protocol_list_initializer(Context, Result,
7319 "_OBJC_CATEGORY_PROTOCOLS_$_",
7322 // Protocol's property metadata.
7323 SmallVector<ObjCPropertyDecl *, 8> ClassProperties(
7324 CDecl->instance_properties());
7325 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
7326 /* Container */IDecl,
7327 "_OBJC_$_PROP_LIST_",
7330 Write_category_t(*this, Context, Result,
7338 // Determine if this category is also "non-lazy".
7339 if (ImplementationIsNonLazy(IDecl))
7340 DefinedNonLazyCategories.push_back(CDecl);
7343 void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7344 int CatDefCount = CategoryImplementation.size();
7347 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7348 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7349 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7350 for (int i = 0; i < CatDefCount; i++) {
7351 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7352 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7353 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7354 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7355 Result += ClassDecl->getName();
7357 Result += CatDecl->getName();
7363 // RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7365 template<typename MethodIterator>
7366 void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7367 MethodIterator MethodEnd,
7368 bool IsInstanceMethod,
7370 StringRef ClassName,
7371 std::string &Result) {
7372 if (MethodBegin == MethodEnd) return;
7374 if (!objc_impl_method) {
7375 /* struct _objc_method {
7381 Result += "\nstruct _objc_method {\n";
7382 Result += "\tSEL _cmd;\n";
7383 Result += "\tchar *method_types;\n";
7384 Result += "\tvoid *_imp;\n";
7387 objc_impl_method = true;
7390 // Build _objc_method_list for class's methods if needed
7393 struct _objc_method_list *next_method;
7395 struct _objc_method method_list[];
7398 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
7400 if (LangOpts.MicrosoftExt) {
7401 if (IsInstanceMethod)
7402 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7404 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7406 Result += "static struct {\n";
7407 Result += "\tstruct _objc_method_list *next_method;\n";
7408 Result += "\tint method_count;\n";
7409 Result += "\tstruct _objc_method method_list[";
7410 Result += utostr(NumMethods);
7411 Result += "];\n} _OBJC_";
7413 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7414 Result += "_METHODS_";
7415 Result += ClassName;
7416 Result += " __attribute__ ((used, section (\"__OBJC, __";
7417 Result += IsInstanceMethod ? "inst" : "cls";
7418 Result += "_meth\")))= ";
7419 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7421 Result += "\t,{{(SEL)\"";
7422 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7423 std::string MethodTypeString;
7424 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7426 Result += MethodTypeString;
7427 Result += "\", (void *)";
7428 Result += MethodInternalNames[*MethodBegin];
7430 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7431 Result += "\t ,{(SEL)\"";
7432 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7433 std::string MethodTypeString;
7434 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7436 Result += MethodTypeString;
7437 Result += "\", (void *)";
7438 Result += MethodInternalNames[*MethodBegin];
7441 Result += "\t }\n};\n";
7444 Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7445 SourceRange OldRange = IV->getSourceRange();
7446 Expr *BaseExpr = IV->getBase();
7448 // Rewrite the base, but without actually doing replaces.
7450 DisableReplaceStmtScope S(*this);
7451 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7452 IV->setBase(BaseExpr);
7455 ObjCIvarDecl *D = IV->getDecl();
7457 Expr *Replacement = IV;
7459 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7460 const ObjCInterfaceType *iFaceDecl =
7461 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
7462 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7463 // lookup which class implements the instance variable.
7464 ObjCInterfaceDecl *clsDeclared = nullptr;
7465 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7467 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7469 // Build name of symbol holding ivar offset.
7470 std::string IvarOffsetName;
7471 if (D->isBitField())
7472 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
7474 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
7476 ReferencedIvars[clsDeclared].insert(D);
7478 // cast offset to "char *".
7479 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7480 Context->getPointerType(Context->CharTy),
7483 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7484 SourceLocation(), &Context->Idents.get(IvarOffsetName),
7485 Context->UnsignedLongTy, nullptr,
7487 DeclRefExpr *DRE = new (Context)
7488 DeclRefExpr(*Context, NewVD, false, Context->UnsignedLongTy,
7489 VK_LValue, SourceLocation());
7490 BinaryOperator *addExpr =
7491 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7492 Context->getPointerType(Context->CharTy),
7493 VK_RValue, OK_Ordinary, SourceLocation(), FPOptions());
7494 // Don't forget the parens to enforce the proper binding.
7495 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7498 QualType IvarT = D->getType();
7499 if (D->isBitField())
7500 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
7502 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
7503 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
7504 RD = RD->getDefinition();
7505 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
7506 // decltype(((Foo_IMPL*)0)->bar) *
7507 ObjCContainerDecl *CDecl =
7508 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7509 // ivar in class extensions requires special treatment.
7510 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7511 CDecl = CatDecl->getClassInterface();
7512 std::string RecName = CDecl->getName();
7514 RecordDecl *RD = RecordDecl::Create(
7515 *Context, TTK_Struct, TUDecl, SourceLocation(), SourceLocation(),
7516 &Context->Idents.get(RecName));
7517 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7518 unsigned UnsignedIntSize =
7519 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7520 Expr *Zero = IntegerLiteral::Create(*Context,
7521 llvm::APInt(UnsignedIntSize, 0),
7522 Context->UnsignedIntTy, SourceLocation());
7523 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7524 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7526 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
7528 &Context->Idents.get(D->getNameAsString()),
7530 /*BitWidth=*/nullptr,
7531 /*Mutable=*/true, ICIS_NoInit);
7532 MemberExpr *ME = new (Context)
7533 MemberExpr(PE, true, SourceLocation(), FD, SourceLocation(),
7534 FD->getType(), VK_LValue, OK_Ordinary);
7535 IvarT = Context->getDecltypeType(ME, ME->getType());
7538 convertObjCTypeToCStyleType(IvarT);
7539 QualType castT = Context->getPointerType(IvarT);
7541 castExpr = NoTypeInfoCStyleCastExpr(Context,
7547 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
7548 VK_LValue, OK_Ordinary,
7549 SourceLocation(), false);
7550 PE = new (Context) ParenExpr(OldRange.getBegin(),
7554 if (D->isBitField()) {
7555 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
7557 &Context->Idents.get(D->getNameAsString()),
7558 D->getType(), nullptr,
7559 /*BitWidth=*/D->getBitWidth(),
7560 /*Mutable=*/true, ICIS_NoInit);
7561 MemberExpr *ME = new (Context)
7562 MemberExpr(PE, /*isArrow*/ false, SourceLocation(), FD,
7563 SourceLocation(), FD->getType(), VK_LValue, OK_Ordinary);
7571 ReplaceStmtWithRange(IV, Replacement, OldRange);
7575 #endif // CLANG_ENABLE_OBJC_REWRITER