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->getLocStart()), 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->getLocStart()), 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) {
544 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
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->getLocStart();
753 if (isa<ObjCInterfaceDecl>(*DI) &&
754 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
755 StartLoc == (*DI)->getLocStart())
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->getLocStart();
778 if (isa<ObjCProtocolDecl>(*DI) &&
779 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
780 StartLoc == (*DI)->getLocStart())
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->getLocStart().isValid()) {
927 SourceLocation startLoc = PID->getLocStart();
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);
936 startGetterSetterLoc = IMD ? IMD->getLocEnd() : CID->getLocEnd();
938 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
939 return; // FIXME: is this correct?
941 // Generate the 'getter' function.
942 ObjCPropertyDecl *PD = PID->getPropertyDecl();
943 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
944 assert(IMD && OID && "Synthesized ivars must be attached to @implementation");
946 unsigned Attributes = PD->getPropertyAttributes();
947 if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
948 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
949 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
950 ObjCPropertyDecl::OBJC_PR_copy));
952 if (GenGetProperty && !objcGetPropertyDefined) {
953 objcGetPropertyDefined = true;
954 // FIXME. Is this attribute correct in all cases?
955 Getr = "\nextern \"C\" __declspec(dllimport) "
956 "id objc_getProperty(id, SEL, long, bool);\n";
958 RewriteObjCMethodDecl(OID->getContainingInterface(),
959 PD->getGetterMethodDecl(), Getr);
961 // Synthesize an explicit cast to gain access to the ivar.
962 // See objc-act.c:objc_synthesize_new_getter() for details.
963 if (GenGetProperty) {
964 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
966 const FunctionType *FPRetType = nullptr;
967 RewriteTypeIntoString(PD->getGetterMethodDecl()->getReturnType(), Getr,
971 Getr += ")"; // close the precedence "scope" for "*".
973 // Now, emit the argument types (if any).
974 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
976 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
978 std::string ParamStr =
979 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
982 if (FT->isVariadic()) {
983 if (FT->getNumParams())
992 Getr += "return (_TYPE)";
993 Getr += "objc_getProperty(self, _cmd, ";
994 RewriteIvarOffsetComputation(OID, Getr);
998 Getr += "return " + getIvarAccessString(OID);
1000 InsertText(startGetterSetterLoc, Getr);
1003 if (PD->isReadOnly() ||
1004 !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
1007 // Generate the 'setter' function.
1009 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
1010 ObjCPropertyDecl::OBJC_PR_copy);
1011 if (GenSetProperty && !objcSetPropertyDefined) {
1012 objcSetPropertyDefined = true;
1013 // FIXME. Is this attribute correct in all cases?
1014 Setr = "\nextern \"C\" __declspec(dllimport) "
1015 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
1018 RewriteObjCMethodDecl(OID->getContainingInterface(),
1019 PD->getSetterMethodDecl(), Setr);
1021 // Synthesize an explicit cast to initialize the ivar.
1022 // See objc-act.c:objc_synthesize_new_setter() for details.
1023 if (GenSetProperty) {
1024 Setr += "objc_setProperty (self, _cmd, ";
1025 RewriteIvarOffsetComputation(OID, Setr);
1027 Setr += PD->getName();
1029 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
1033 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
1039 Setr += getIvarAccessString(OID) + " = ";
1040 Setr += PD->getName();
1043 InsertText(startGetterSetterLoc, Setr);
1046 static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
1047 std::string &typedefString) {
1048 typedefString += "\n#ifndef _REWRITER_typedef_";
1049 typedefString += ForwardDecl->getNameAsString();
1050 typedefString += "\n";
1051 typedefString += "#define _REWRITER_typedef_";
1052 typedefString += ForwardDecl->getNameAsString();
1053 typedefString += "\n";
1054 typedefString += "typedef struct objc_object ";
1055 typedefString += ForwardDecl->getNameAsString();
1056 // typedef struct { } _objc_exc_Classname;
1057 typedefString += ";\ntypedef struct {} _objc_exc_";
1058 typedefString += ForwardDecl->getNameAsString();
1059 typedefString += ";\n#endif\n";
1062 void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
1063 const std::string &typedefString) {
1064 SourceLocation startLoc = ClassDecl->getLocStart();
1065 const char *startBuf = SM->getCharacterData(startLoc);
1066 const char *semiPtr = strchr(startBuf, ';');
1067 // Replace the @class with typedefs corresponding to the classes.
1068 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
1071 void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
1072 std::string typedefString;
1073 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
1074 if (ObjCInterfaceDecl *ForwardDecl = dyn_cast<ObjCInterfaceDecl>(*I)) {
1075 if (I == D.begin()) {
1076 // Translate to typedef's that forward reference structs with the same name
1077 // as the class. As a convenience, we include the original declaration
1079 typedefString += "// @class ";
1080 typedefString += ForwardDecl->getNameAsString();
1081 typedefString += ";";
1083 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1086 HandleTopLevelSingleDecl(*I);
1088 DeclGroupRef::iterator I = D.begin();
1089 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
1092 void RewriteModernObjC::RewriteForwardClassDecl(
1093 const SmallVectorImpl<Decl *> &D) {
1094 std::string typedefString;
1095 for (unsigned i = 0; i < D.size(); i++) {
1096 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
1098 typedefString += "// @class ";
1099 typedefString += ForwardDecl->getNameAsString();
1100 typedefString += ";";
1102 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1104 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
1107 void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
1108 // When method is a synthesized one, such as a getter/setter there is
1109 // nothing to rewrite.
1110 if (Method->isImplicit())
1112 SourceLocation LocStart = Method->getLocStart();
1113 SourceLocation LocEnd = Method->getLocEnd();
1115 if (SM->getExpansionLineNumber(LocEnd) >
1116 SM->getExpansionLineNumber(LocStart)) {
1117 InsertText(LocStart, "#if 0\n");
1118 ReplaceText(LocEnd, 1, ";\n#endif\n");
1120 InsertText(LocStart, "// ");
1124 void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
1125 SourceLocation Loc = prop->getAtLoc();
1127 ReplaceText(Loc, 0, "// ");
1128 // FIXME: handle properties that are declared across multiple lines.
1131 void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
1132 SourceLocation LocStart = CatDecl->getLocStart();
1134 // FIXME: handle category headers that are declared across multiple lines.
1135 if (CatDecl->getIvarRBraceLoc().isValid()) {
1136 ReplaceText(LocStart, 1, "/** ");
1137 ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1140 ReplaceText(LocStart, 0, "// ");
1143 for (auto *I : CatDecl->instance_properties())
1146 for (auto *I : CatDecl->instance_methods())
1147 RewriteMethodDeclaration(I);
1148 for (auto *I : CatDecl->class_methods())
1149 RewriteMethodDeclaration(I);
1151 // Lastly, comment out the @end.
1152 ReplaceText(CatDecl->getAtEndRange().getBegin(),
1153 strlen("@end"), "/* @end */\n");
1156 void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1157 SourceLocation LocStart = PDecl->getLocStart();
1158 assert(PDecl->isThisDeclarationADefinition());
1160 // FIXME: handle protocol headers that are declared across multiple lines.
1161 ReplaceText(LocStart, 0, "// ");
1163 for (auto *I : PDecl->instance_methods())
1164 RewriteMethodDeclaration(I);
1165 for (auto *I : PDecl->class_methods())
1166 RewriteMethodDeclaration(I);
1167 for (auto *I : PDecl->instance_properties())
1170 // Lastly, comment out the @end.
1171 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1172 ReplaceText(LocEnd, strlen("@end"), "/* @end */\n");
1174 // Must comment out @optional/@required
1175 const char *startBuf = SM->getCharacterData(LocStart);
1176 const char *endBuf = SM->getCharacterData(LocEnd);
1177 for (const char *p = startBuf; p < endBuf; p++) {
1178 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1179 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1180 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1183 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1184 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1185 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1191 void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1192 SourceLocation LocStart = (*D.begin())->getLocStart();
1193 if (LocStart.isInvalid())
1194 llvm_unreachable("Invalid SourceLocation");
1195 // FIXME: handle forward protocol that are declared across multiple lines.
1196 ReplaceText(LocStart, 0, "// ");
1200 RewriteModernObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
1201 SourceLocation LocStart = DG[0]->getLocStart();
1202 if (LocStart.isInvalid())
1203 llvm_unreachable("Invalid SourceLocation");
1204 // FIXME: handle forward protocol that are declared across multiple lines.
1205 ReplaceText(LocStart, 0, "// ");
1208 void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1209 const FunctionType *&FPRetType) {
1210 if (T->isObjCQualifiedIdType())
1212 else if (T->isFunctionPointerType() ||
1213 T->isBlockPointerType()) {
1214 // needs special handling, since pointer-to-functions have special
1215 // syntax (where a decaration models use).
1216 QualType retType = T;
1218 if (const PointerType* PT = retType->getAs<PointerType>())
1219 PointeeTy = PT->getPointeeType();
1220 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1221 PointeeTy = BPT->getPointeeType();
1222 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1224 FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
1228 ResultStr += T.getAsString(Context->getPrintingPolicy());
1231 void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1232 ObjCMethodDecl *OMD,
1233 std::string &ResultStr) {
1234 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1235 const FunctionType *FPRetType = nullptr;
1236 ResultStr += "\nstatic ";
1237 RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
1240 // Unique method name
1241 std::string NameStr;
1243 if (OMD->isInstanceMethod())
1248 NameStr += IDecl->getNameAsString();
1251 if (ObjCCategoryImplDecl *CID =
1252 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1253 NameStr += CID->getNameAsString();
1256 // Append selector names, replacing ':' with '_'
1258 std::string selString = OMD->getSelector().getAsString();
1259 int len = selString.size();
1260 for (int i = 0; i < len; i++)
1261 if (selString[i] == ':')
1263 NameStr += selString;
1265 // Remember this name for metadata emission
1266 MethodInternalNames[OMD] = NameStr;
1267 ResultStr += NameStr;
1269 // Rewrite arguments
1272 // invisible arguments
1273 if (OMD->isInstanceMethod()) {
1274 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1275 selfTy = Context->getPointerType(selfTy);
1276 if (!LangOpts.MicrosoftExt) {
1277 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1278 ResultStr += "struct ";
1280 // When rewriting for Microsoft, explicitly omit the structure name.
1281 ResultStr += IDecl->getNameAsString();
1285 ResultStr += Context->getObjCClassType().getAsString(
1286 Context->getPrintingPolicy());
1288 ResultStr += " self, ";
1289 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1290 ResultStr += " _cmd";
1292 // Method arguments.
1293 for (const auto *PDecl : OMD->parameters()) {
1295 if (PDecl->getType()->isObjCQualifiedIdType()) {
1297 ResultStr += PDecl->getNameAsString();
1299 std::string Name = PDecl->getNameAsString();
1300 QualType QT = PDecl->getType();
1301 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1302 (void)convertBlockPointerToFunctionPointer(QT);
1303 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
1307 if (OMD->isVariadic())
1308 ResultStr += ", ...";
1312 ResultStr += ")"; // close the precedence "scope" for "*".
1314 // Now, emit the argument types (if any).
1315 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1317 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1318 if (i) ResultStr += ", ";
1319 std::string ParamStr =
1320 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
1321 ResultStr += ParamStr;
1323 if (FT->isVariadic()) {
1324 if (FT->getNumParams())
1335 void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1336 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1337 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1340 if (IMD->getIvarRBraceLoc().isValid()) {
1341 ReplaceText(IMD->getLocStart(), 1, "/** ");
1342 ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
1345 InsertText(IMD->getLocStart(), "// ");
1349 InsertText(CID->getLocStart(), "// ");
1351 for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) {
1352 std::string ResultStr;
1353 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1354 SourceLocation LocStart = OMD->getLocStart();
1355 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1357 const char *startBuf = SM->getCharacterData(LocStart);
1358 const char *endBuf = SM->getCharacterData(LocEnd);
1359 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1362 for (auto *OMD : IMD ? IMD->class_methods() : CID->class_methods()) {
1363 std::string ResultStr;
1364 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1365 SourceLocation LocStart = OMD->getLocStart();
1366 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1368 const char *startBuf = SM->getCharacterData(LocStart);
1369 const char *endBuf = SM->getCharacterData(LocEnd);
1370 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1372 for (auto *I : IMD ? IMD->property_impls() : CID->property_impls())
1373 RewritePropertyImplDecl(I, IMD, CID);
1375 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1378 void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
1379 // Do not synthesize more than once.
1380 if (ObjCSynthesizedStructs.count(ClassDecl))
1382 // Make sure super class's are written before current class is written.
1383 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1384 while (SuperClass) {
1385 RewriteInterfaceDecl(SuperClass);
1386 SuperClass = SuperClass->getSuperClass();
1388 std::string ResultStr;
1389 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
1390 // we haven't seen a forward decl - generate a typedef.
1391 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
1392 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1394 RewriteObjCInternalStruct(ClassDecl, ResultStr);
1395 // Mark this typedef as having been written into its c++ equivalent.
1396 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
1398 for (auto *I : ClassDecl->instance_properties())
1400 for (auto *I : ClassDecl->instance_methods())
1401 RewriteMethodDeclaration(I);
1402 for (auto *I : ClassDecl->class_methods())
1403 RewriteMethodDeclaration(I);
1405 // Lastly, comment out the @end.
1406 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1411 Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1412 SourceRange OldRange = PseudoOp->getSourceRange();
1414 // We just magically know some things about the structure of this
1416 ObjCMessageExpr *OldMsg =
1417 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1418 PseudoOp->getNumSemanticExprs() - 1));
1420 // Because the rewriter doesn't allow us to rewrite rewritten code,
1421 // we need to suppress rewriting the sub-statements.
1423 SmallVector<Expr*, 2> Args;
1425 DisableReplaceStmtScope S(*this);
1427 // Rebuild the base expression if we have one.
1429 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1430 Base = OldMsg->getInstanceReceiver();
1431 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1432 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1435 unsigned numArgs = OldMsg->getNumArgs();
1436 for (unsigned i = 0; i < numArgs; i++) {
1437 Expr *Arg = OldMsg->getArg(i);
1438 if (isa<OpaqueValueExpr>(Arg))
1439 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1440 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1441 Args.push_back(Arg);
1445 // TODO: avoid this copy.
1446 SmallVector<SourceLocation, 1> SelLocs;
1447 OldMsg->getSelectorLocs(SelLocs);
1449 ObjCMessageExpr *NewMsg = nullptr;
1450 switch (OldMsg->getReceiverKind()) {
1451 case ObjCMessageExpr::Class:
1452 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1453 OldMsg->getValueKind(),
1454 OldMsg->getLeftLoc(),
1455 OldMsg->getClassReceiverTypeInfo(),
1456 OldMsg->getSelector(),
1458 OldMsg->getMethodDecl(),
1460 OldMsg->getRightLoc(),
1461 OldMsg->isImplicit());
1464 case ObjCMessageExpr::Instance:
1465 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1466 OldMsg->getValueKind(),
1467 OldMsg->getLeftLoc(),
1469 OldMsg->getSelector(),
1471 OldMsg->getMethodDecl(),
1473 OldMsg->getRightLoc(),
1474 OldMsg->isImplicit());
1477 case ObjCMessageExpr::SuperClass:
1478 case ObjCMessageExpr::SuperInstance:
1479 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1480 OldMsg->getValueKind(),
1481 OldMsg->getLeftLoc(),
1482 OldMsg->getSuperLoc(),
1483 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1484 OldMsg->getSuperType(),
1485 OldMsg->getSelector(),
1487 OldMsg->getMethodDecl(),
1489 OldMsg->getRightLoc(),
1490 OldMsg->isImplicit());
1494 Stmt *Replacement = SynthMessageExpr(NewMsg);
1495 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1499 Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1500 SourceRange OldRange = PseudoOp->getSourceRange();
1502 // We just magically know some things about the structure of this
1504 ObjCMessageExpr *OldMsg =
1505 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1507 // Because the rewriter doesn't allow us to rewrite rewritten code,
1508 // we need to suppress rewriting the sub-statements.
1509 Expr *Base = nullptr;
1510 SmallVector<Expr*, 1> Args;
1512 DisableReplaceStmtScope S(*this);
1513 // Rebuild the base expression if we have one.
1514 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1515 Base = OldMsg->getInstanceReceiver();
1516 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1517 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1519 unsigned numArgs = OldMsg->getNumArgs();
1520 for (unsigned i = 0; i < numArgs; i++) {
1521 Expr *Arg = OldMsg->getArg(i);
1522 if (isa<OpaqueValueExpr>(Arg))
1523 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1524 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1525 Args.push_back(Arg);
1529 // Intentionally empty.
1530 SmallVector<SourceLocation, 1> SelLocs;
1532 ObjCMessageExpr *NewMsg = nullptr;
1533 switch (OldMsg->getReceiverKind()) {
1534 case ObjCMessageExpr::Class:
1535 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1536 OldMsg->getValueKind(),
1537 OldMsg->getLeftLoc(),
1538 OldMsg->getClassReceiverTypeInfo(),
1539 OldMsg->getSelector(),
1541 OldMsg->getMethodDecl(),
1543 OldMsg->getRightLoc(),
1544 OldMsg->isImplicit());
1547 case ObjCMessageExpr::Instance:
1548 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1549 OldMsg->getValueKind(),
1550 OldMsg->getLeftLoc(),
1552 OldMsg->getSelector(),
1554 OldMsg->getMethodDecl(),
1556 OldMsg->getRightLoc(),
1557 OldMsg->isImplicit());
1560 case ObjCMessageExpr::SuperClass:
1561 case ObjCMessageExpr::SuperInstance:
1562 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1563 OldMsg->getValueKind(),
1564 OldMsg->getLeftLoc(),
1565 OldMsg->getSuperLoc(),
1566 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1567 OldMsg->getSuperType(),
1568 OldMsg->getSelector(),
1570 OldMsg->getMethodDecl(),
1572 OldMsg->getRightLoc(),
1573 OldMsg->isImplicit());
1577 Stmt *Replacement = SynthMessageExpr(NewMsg);
1578 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1582 /// SynthCountByEnumWithState - To print:
1583 /// ((NSUInteger (*)
1584 /// (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
1585 /// (void *)objc_msgSend)((id)l_collection,
1586 /// sel_registerName(
1587 /// "countByEnumeratingWithState:objects:count:"),
1589 /// (id *)__rw_items, (NSUInteger)16)
1591 void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1592 buf += "((_WIN_NSUInteger (*) (id, SEL, struct __objcFastEnumerationState *, "
1593 "id *, _WIN_NSUInteger))(void *)objc_msgSend)";
1595 buf += "((id)l_collection,\n\t\t";
1596 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1598 buf += "&enumState, "
1599 "(id *)__rw_items, (_WIN_NSUInteger)16)";
1602 /// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1603 /// statement to exit to its outer synthesized loop.
1605 Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1606 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1608 // replace break with goto __break_label
1611 SourceLocation startLoc = S->getLocStart();
1612 buf = "goto __break_label_";
1613 buf += utostr(ObjCBcLabelNo.back());
1614 ReplaceText(startLoc, strlen("break"), buf);
1619 void RewriteModernObjC::ConvertSourceLocationToLineDirective(
1621 std::string &LineString) {
1622 if (Loc.isFileID() && GenerateLineInfo) {
1623 LineString += "\n#line ";
1624 PresumedLoc PLoc = SM->getPresumedLoc(Loc);
1625 LineString += utostr(PLoc.getLine());
1626 LineString += " \"";
1627 LineString += Lexer::Stringify(PLoc.getFilename());
1628 LineString += "\"\n";
1632 /// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1633 /// statement to continue with its inner synthesized loop.
1635 Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1636 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1638 // replace continue with goto __continue_label
1641 SourceLocation startLoc = S->getLocStart();
1642 buf = "goto __continue_label_";
1643 buf += utostr(ObjCBcLabelNo.back());
1644 ReplaceText(startLoc, strlen("continue"), buf);
1649 /// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1651 /// for ( type elem in collection) { stmts; }
1656 /// struct __objcFastEnumerationState enumState = { 0 };
1657 /// id __rw_items[16];
1658 /// id l_collection = (id)collection;
1659 /// NSUInteger limit = [l_collection countByEnumeratingWithState:&enumState
1660 /// objects:__rw_items count:16];
1662 /// unsigned long startMutations = *enumState.mutationsPtr;
1664 /// unsigned long counter = 0;
1666 /// if (startMutations != *enumState.mutationsPtr)
1667 /// objc_enumerationMutation(l_collection);
1668 /// elem = (type)enumState.itemsPtr[counter++];
1670 /// __continue_label: ;
1671 /// } while (counter < limit);
1672 /// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1673 /// objects:__rw_items count:16]));
1675 /// __break_label: ;
1681 Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1682 SourceLocation OrigEnd) {
1683 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1684 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1685 "ObjCForCollectionStmt Statement stack mismatch");
1686 assert(!ObjCBcLabelNo.empty() &&
1687 "ObjCForCollectionStmt - Label No stack empty");
1689 SourceLocation startLoc = S->getLocStart();
1690 const char *startBuf = SM->getCharacterData(startLoc);
1691 StringRef elementName;
1692 std::string elementTypeAsString;
1694 // line directive first.
1695 SourceLocation ForEachLoc = S->getForLoc();
1696 ConvertSourceLocationToLineDirective(ForEachLoc, buf);
1698 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1700 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1701 QualType ElementType = cast<ValueDecl>(D)->getType();
1702 if (ElementType->isObjCQualifiedIdType() ||
1703 ElementType->isObjCQualifiedInterfaceType())
1704 // Simply use 'id' for all qualified types.
1705 elementTypeAsString = "id";
1707 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1708 buf += elementTypeAsString;
1710 elementName = D->getName();
1715 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1716 elementName = DR->getDecl()->getName();
1717 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1718 if (VD->getType()->isObjCQualifiedIdType() ||
1719 VD->getType()->isObjCQualifiedInterfaceType())
1720 // Simply use 'id' for all qualified types.
1721 elementTypeAsString = "id";
1723 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1726 // struct __objcFastEnumerationState enumState = { 0 };
1727 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1728 // id __rw_items[16];
1729 buf += "id __rw_items[16];\n\t";
1730 // id l_collection = (id)
1731 buf += "id l_collection = (id)";
1732 // Find start location of 'collection' the hard way!
1733 const char *startCollectionBuf = startBuf;
1734 startCollectionBuf += 3; // skip 'for'
1735 startCollectionBuf = strchr(startCollectionBuf, '(');
1736 startCollectionBuf++; // skip '('
1737 // find 'in' and skip it.
1738 while (*startCollectionBuf != ' ' ||
1739 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1740 (*(startCollectionBuf+3) != ' ' &&
1741 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1742 startCollectionBuf++;
1743 startCollectionBuf += 3;
1745 // Replace: "for (type element in" with string constructed thus far.
1746 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1747 // Replace ')' in for '(' type elem in collection ')' with ';'
1748 SourceLocation rightParenLoc = S->getRParenLoc();
1749 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1750 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1753 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1754 // objects:__rw_items count:16];
1755 // which is synthesized into:
1756 // NSUInteger limit =
1758 // (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
1759 // (void *)objc_msgSend)((id)l_collection,
1760 // sel_registerName(
1761 // "countByEnumeratingWithState:objects:count:"),
1762 // (struct __objcFastEnumerationState *)&state,
1763 // (id *)__rw_items, (NSUInteger)16);
1764 buf += "_WIN_NSUInteger limit =\n\t\t";
1765 SynthCountByEnumWithState(buf);
1768 /// unsigned long startMutations = *enumState.mutationsPtr;
1770 /// unsigned long counter = 0;
1772 /// if (startMutations != *enumState.mutationsPtr)
1773 /// objc_enumerationMutation(l_collection);
1774 /// elem = (type)enumState.itemsPtr[counter++];
1775 buf += "if (limit) {\n\t";
1776 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1777 buf += "do {\n\t\t";
1778 buf += "unsigned long counter = 0;\n\t\t";
1779 buf += "do {\n\t\t\t";
1780 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1781 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1784 buf += elementTypeAsString;
1785 buf += ")enumState.itemsPtr[counter++];";
1786 // Replace ')' in for '(' type elem in collection ')' with all of these.
1787 ReplaceText(lparenLoc, 1, buf);
1789 /// __continue_label: ;
1790 /// } while (counter < limit);
1791 /// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1792 /// objects:__rw_items count:16]));
1794 /// __break_label: ;
1801 buf += "__continue_label_";
1802 buf += utostr(ObjCBcLabelNo.back());
1805 buf += "} while (counter < limit);\n\t";
1806 buf += "} while ((limit = ";
1807 SynthCountByEnumWithState(buf);
1811 buf += elementTypeAsString;
1813 buf += "__break_label_";
1814 buf += utostr(ObjCBcLabelNo.back());
1817 buf += "else\n\t\t";
1820 buf += elementTypeAsString;
1824 // Insert all these *after* the statement body.
1825 // FIXME: If this should support Obj-C++, support CXXTryStmt
1826 if (isa<CompoundStmt>(S->getBody())) {
1827 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1828 InsertText(endBodyLoc, buf);
1830 /* Need to treat single statements specially. For example:
1832 * for (A *a in b) if (stuff()) break;
1833 * for (A *a in b) xxxyy;
1835 * The following code simply scans ahead to the semi to find the actual end.
1837 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1838 const char *semiBuf = strchr(stmtBuf, ';');
1839 assert(semiBuf && "Can't find ';'");
1840 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1841 InsertText(endBodyLoc, buf);
1844 ObjCBcLabelNo.pop_back();
1848 static void Write_RethrowObject(std::string &buf) {
1849 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1850 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1851 buf += "\tid rethrow;\n";
1852 buf += "\t} _fin_force_rethow(_rethrow);";
1855 /// RewriteObjCSynchronizedStmt -
1856 /// This routine rewrites @synchronized(expr) stmt;
1858 /// objc_sync_enter(expr);
1859 /// @try stmt @finally { objc_sync_exit(expr); }
1861 Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1862 // Get the start location and compute the semi location.
1863 SourceLocation startLoc = S->getLocStart();
1864 const char *startBuf = SM->getCharacterData(startLoc);
1866 assert((*startBuf == '@') && "bogus @synchronized location");
1869 SourceLocation SynchLoc = S->getAtSynchronizedLoc();
1870 ConvertSourceLocationToLineDirective(SynchLoc, buf);
1871 buf += "{ id _rethrow = 0; id _sync_obj = (id)";
1873 const char *lparenBuf = startBuf;
1874 while (*lparenBuf != '(') lparenBuf++;
1875 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
1877 buf = "; objc_sync_enter(_sync_obj);\n";
1878 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1879 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1880 buf += "\n\tid sync_exit;";
1881 buf += "\n\t} _sync_exit(_sync_obj);\n";
1883 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1884 // the sync expression is typically a message expression that's already
1885 // been rewritten! (which implies the SourceLocation's are invalid).
1886 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1887 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1888 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1889 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1891 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1892 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1893 assert (*LBraceLocBuf == '{');
1894 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
1896 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
1897 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1898 "bogus @synchronized block");
1900 buf = "} catch (id e) {_rethrow = e;}\n";
1901 Write_RethrowObject(buf);
1905 ReplaceText(startRBraceLoc, 1, buf);
1910 void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1912 // Perform a bottom up traversal of all children.
1913 for (Stmt *SubStmt : S->children())
1915 WarnAboutReturnGotoStmts(SubStmt);
1917 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1918 Diags.Report(Context->getFullLoc(S->getLocStart()),
1919 TryFinallyContainsReturnDiag);
1923 Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
1924 SourceLocation startLoc = S->getAtLoc();
1925 ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
1926 ReplaceText(S->getSubStmt()->getLocStart(), 1,
1927 "{ __AtAutoreleasePool __autoreleasepool; ");
1932 Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
1933 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
1934 bool noCatch = S->getNumCatchStmts() == 0;
1936 SourceLocation TryLocation = S->getAtTryLoc();
1937 ConvertSourceLocationToLineDirective(TryLocation, buf);
1941 buf += "{ id volatile _rethrow = 0;\n";
1943 buf += "{ id volatile _rethrow = 0;\ntry {\n";
1946 // Get the start location and compute the semi location.
1947 SourceLocation startLoc = S->getLocStart();
1948 const char *startBuf = SM->getCharacterData(startLoc);
1950 assert((*startBuf == '@') && "bogus @try location");
1952 ReplaceText(startLoc, 1, buf);
1955 ReplaceText(startLoc, 1, "");
1957 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1958 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
1959 VarDecl *catchDecl = Catch->getCatchParamDecl();
1961 startLoc = Catch->getLocStart();
1962 bool AtRemoved = false;
1964 QualType t = catchDecl->getType();
1965 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1966 // Should be a pointer to a class.
1967 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1970 ConvertSourceLocationToLineDirective(Catch->getLocStart(), Result);
1972 startBuf = SM->getCharacterData(startLoc);
1973 assert((*startBuf == '@') && "bogus @catch location");
1974 SourceLocation rParenLoc = Catch->getRParenLoc();
1975 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1977 // _objc_exc_Foo *_e as argument to catch.
1978 Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString();
1979 Result += " *_"; Result += catchDecl->getNameAsString();
1981 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1982 // Foo *e = (Foo *)_e;
1985 Result += IDecl->getNameAsString();
1986 Result += " *"; Result += catchDecl->getNameAsString();
1987 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1988 Result += "_"; Result += catchDecl->getNameAsString();
1991 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
1992 ReplaceText(lBraceLoc, 1, Result);
1999 ReplaceText(startLoc, 1, "");
2004 SourceLocation FinallyLoc = finalStmt->getLocStart();
2007 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2008 buf += "catch (id e) {_rethrow = e;}\n";
2012 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2013 buf += "catch (id e) {_rethrow = e;}\n";
2016 SourceLocation startFinalLoc = finalStmt->getLocStart();
2017 ReplaceText(startFinalLoc, 8, buf);
2018 Stmt *body = finalStmt->getFinallyBody();
2019 SourceLocation startFinalBodyLoc = body->getLocStart();
2021 Write_RethrowObject(buf);
2022 ReplaceText(startFinalBodyLoc, 1, buf);
2024 SourceLocation endFinalBodyLoc = body->getLocEnd();
2025 ReplaceText(endFinalBodyLoc, 1, "}\n}");
2026 // Now check for any return/continue/go statements within the @try.
2027 WarnAboutReturnGotoStmts(S->getTryBody());
2033 // This can't be done with ReplaceStmt(S, ThrowExpr), since
2034 // the throw expression is typically a message expression that's already
2035 // been rewritten! (which implies the SourceLocation's are invalid).
2036 Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
2037 // Get the start location and compute the semi location.
2038 SourceLocation startLoc = S->getLocStart();
2039 const char *startBuf = SM->getCharacterData(startLoc);
2041 assert((*startBuf == '@') && "bogus @throw location");
2044 /* void objc_exception_throw(id) __attribute__((noreturn)); */
2045 if (S->getThrowExpr())
2046 buf = "objc_exception_throw(";
2050 // handle "@ throw" correctly.
2051 const char *wBuf = strchr(startBuf, 'w');
2052 assert((*wBuf == 'w') && "@throw: can't find 'w'");
2053 ReplaceText(startLoc, wBuf-startBuf+1, buf);
2055 SourceLocation endLoc = S->getLocEnd();
2056 const char *endBuf = SM->getCharacterData(endLoc);
2057 const char *semiBuf = strchr(endBuf, ';');
2058 assert((*semiBuf == ';') && "@throw: can't find ';'");
2059 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
2060 if (S->getThrowExpr())
2061 ReplaceText(semiLoc, 1, ");");
2065 Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2066 // Create a new string expression.
2067 std::string StrEncoding;
2068 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
2069 Expr *Replacement = getStringLiteral(StrEncoding);
2070 ReplaceStmt(Exp, Replacement);
2072 // Replace this subexpr in the parent.
2073 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2077 Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2078 if (!SelGetUidFunctionDecl)
2079 SynthSelGetUidFunctionDecl();
2080 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2081 // Create a call to sel_registerName("selName").
2082 SmallVector<Expr*, 8> SelExprs;
2083 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
2084 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2086 ReplaceStmt(Exp, SelExp);
2087 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2092 RewriteModernObjC::SynthesizeCallToFunctionDecl(FunctionDecl *FD,
2093 ArrayRef<Expr *> Args,
2094 SourceLocation StartLoc,
2095 SourceLocation EndLoc) {
2096 // Get the type, we will need to reference it in a couple spots.
2097 QualType msgSendType = FD->getType();
2099 // Create a reference to the objc_msgSend() declaration.
2101 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
2103 // Now, we cast the reference to a pointer to the objc_msgSend type.
2104 QualType pToFunc = Context->getPointerType(msgSendType);
2105 ImplicitCastExpr *ICE =
2106 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2107 DRE, nullptr, VK_RValue);
2109 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2111 CallExpr *Exp = new (Context) CallExpr(*Context, ICE, Args,
2112 FT->getCallResultType(*Context),
2117 static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2118 const char *&startRef, const char *&endRef) {
2119 while (startBuf < endBuf) {
2120 if (*startBuf == '<')
2121 startRef = startBuf; // mark the start.
2122 if (*startBuf == '>') {
2123 if (startRef && *startRef == '<') {
2124 endRef = startBuf; // mark the end.
2134 static void scanToNextArgument(const char *&argRef) {
2136 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2139 else if (*argRef == '>')
2143 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2146 bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2147 if (T->isObjCQualifiedIdType())
2149 if (const PointerType *PT = T->getAs<PointerType>()) {
2150 if (PT->getPointeeType()->isObjCQualifiedIdType())
2153 if (T->isObjCObjectPointerType()) {
2154 T = T->getPointeeType();
2155 return T->isObjCQualifiedInterfaceType();
2157 if (T->isArrayType()) {
2158 QualType ElemTy = Context->getBaseElementType(T);
2159 return needToScanForQualifiers(ElemTy);
2164 void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2165 QualType Type = E->getType();
2166 if (needToScanForQualifiers(Type)) {
2167 SourceLocation Loc, EndLoc;
2169 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2170 Loc = ECE->getLParenLoc();
2171 EndLoc = ECE->getRParenLoc();
2173 Loc = E->getLocStart();
2174 EndLoc = E->getLocEnd();
2176 // This will defend against trying to rewrite synthesized expressions.
2177 if (Loc.isInvalid() || EndLoc.isInvalid())
2180 const char *startBuf = SM->getCharacterData(Loc);
2181 const char *endBuf = SM->getCharacterData(EndLoc);
2182 const char *startRef = nullptr, *endRef = nullptr;
2183 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2184 // Get the locations of the startRef, endRef.
2185 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2186 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2187 // Comment out the protocol references.
2188 InsertText(LessLoc, "/*");
2189 InsertText(GreaterLoc, "*/");
2194 void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2197 const FunctionProtoType *proto = nullptr;
2198 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2199 Loc = VD->getLocation();
2200 Type = VD->getType();
2202 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2203 Loc = FD->getLocation();
2204 // Check for ObjC 'id' and class types that have been adorned with protocol
2205 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2206 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2207 assert(funcType && "missing function type");
2208 proto = dyn_cast<FunctionProtoType>(funcType);
2211 Type = proto->getReturnType();
2213 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2214 Loc = FD->getLocation();
2215 Type = FD->getType();
2217 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Dcl)) {
2218 Loc = TD->getLocation();
2219 Type = TD->getUnderlyingType();
2224 if (needToScanForQualifiers(Type)) {
2225 // Since types are unique, we need to scan the buffer.
2227 const char *endBuf = SM->getCharacterData(Loc);
2228 const char *startBuf = endBuf;
2229 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2230 startBuf--; // scan backward (from the decl location) for return type.
2231 const char *startRef = nullptr, *endRef = nullptr;
2232 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2233 // Get the locations of the startRef, endRef.
2234 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2235 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2236 // Comment out the protocol references.
2237 InsertText(LessLoc, "/*");
2238 InsertText(GreaterLoc, "*/");
2242 return; // most likely, was a variable
2243 // Now check arguments.
2244 const char *startBuf = SM->getCharacterData(Loc);
2245 const char *startFuncBuf = startBuf;
2246 for (unsigned i = 0; i < proto->getNumParams(); i++) {
2247 if (needToScanForQualifiers(proto->getParamType(i))) {
2248 // Since types are unique, we need to scan the buffer.
2250 const char *endBuf = startBuf;
2251 // scan forward (from the decl location) for argument types.
2252 scanToNextArgument(endBuf);
2253 const char *startRef = nullptr, *endRef = nullptr;
2254 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2255 // Get the locations of the startRef, endRef.
2256 SourceLocation LessLoc =
2257 Loc.getLocWithOffset(startRef-startFuncBuf);
2258 SourceLocation GreaterLoc =
2259 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2260 // Comment out the protocol references.
2261 InsertText(LessLoc, "/*");
2262 InsertText(GreaterLoc, "*/");
2264 startBuf = ++endBuf;
2267 // If the function name is derived from a macro expansion, then the
2268 // argument buffer will not follow the name. Need to speak with Chris.
2269 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2270 startBuf++; // scan forward (from the decl location) for argument types.
2276 void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2277 QualType QT = ND->getType();
2278 const Type* TypePtr = QT->getAs<Type>();
2279 if (!isa<TypeOfExprType>(TypePtr))
2281 while (isa<TypeOfExprType>(TypePtr)) {
2282 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2283 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2284 TypePtr = QT->getAs<Type>();
2286 // FIXME. This will not work for multiple declarators; as in:
2287 // __typeof__(a) b,c,d;
2288 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2289 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2290 const char *startBuf = SM->getCharacterData(DeclLoc);
2291 if (ND->getInit()) {
2292 std::string Name(ND->getNameAsString());
2293 TypeAsString += " " + Name + " = ";
2294 Expr *E = ND->getInit();
2295 SourceLocation startLoc;
2296 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2297 startLoc = ECE->getLParenLoc();
2299 startLoc = E->getLocStart();
2300 startLoc = SM->getExpansionLoc(startLoc);
2301 const char *endBuf = SM->getCharacterData(startLoc);
2302 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2305 SourceLocation X = ND->getLocEnd();
2306 X = SM->getExpansionLoc(X);
2307 const char *endBuf = SM->getCharacterData(X);
2308 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2312 // SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2313 void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2314 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2315 SmallVector<QualType, 16> ArgTys;
2316 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2317 QualType getFuncType =
2318 getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
2319 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2322 SelGetUidIdent, getFuncType,
2323 nullptr, SC_Extern);
2326 void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2327 // declared in <objc/objc.h>
2328 if (FD->getIdentifier() &&
2329 FD->getName() == "sel_registerName") {
2330 SelGetUidFunctionDecl = FD;
2333 RewriteObjCQualifiedInterfaceTypes(FD);
2336 void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2337 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2338 const char *argPtr = TypeString.c_str();
2339 if (!strchr(argPtr, '^')) {
2344 Str += (*argPtr == '^' ? '*' : *argPtr);
2349 // FIXME. Consolidate this routine with RewriteBlockPointerType.
2350 void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2352 QualType Type = VD->getType();
2353 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2354 const char *argPtr = TypeString.c_str();
2369 Str += VD->getNameAsString();
2379 void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2380 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2381 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2382 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2385 QualType Type = proto->getReturnType();
2386 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2388 FdStr += FD->getName();
2390 unsigned numArgs = proto->getNumParams();
2391 for (unsigned i = 0; i < numArgs; i++) {
2392 QualType ArgType = proto->getParamType(i);
2393 RewriteBlockPointerType(FdStr, ArgType);
2397 if (FD->isVariadic()) {
2398 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2402 InsertText(FunLocStart, FdStr);
2405 // SynthSuperConstructorFunctionDecl - id __rw_objc_super(id obj, id super);
2406 void RewriteModernObjC::SynthSuperConstructorFunctionDecl() {
2407 if (SuperConstructorFunctionDecl)
2409 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2410 SmallVector<QualType, 16> ArgTys;
2411 QualType argT = Context->getObjCIdType();
2412 assert(!argT.isNull() && "Can't find 'id' type");
2413 ArgTys.push_back(argT);
2414 ArgTys.push_back(argT);
2415 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2417 SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2420 msgSendIdent, msgSendType,
2421 nullptr, SC_Extern);
2424 // SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2425 void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2426 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2427 SmallVector<QualType, 16> ArgTys;
2428 QualType argT = Context->getObjCIdType();
2429 assert(!argT.isNull() && "Can't find 'id' type");
2430 ArgTys.push_back(argT);
2431 argT = Context->getObjCSelType();
2432 assert(!argT.isNull() && "Can't find 'SEL' type");
2433 ArgTys.push_back(argT);
2434 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2435 ArgTys, /*isVariadic=*/true);
2436 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2439 msgSendIdent, msgSendType, nullptr,
2443 // SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
2444 void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2445 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2446 SmallVector<QualType, 2> ArgTys;
2447 ArgTys.push_back(Context->VoidTy);
2448 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2449 ArgTys, /*isVariadic=*/true);
2450 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2453 msgSendIdent, msgSendType,
2454 nullptr, SC_Extern);
2457 // SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2458 void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2459 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2460 SmallVector<QualType, 16> ArgTys;
2461 QualType argT = Context->getObjCIdType();
2462 assert(!argT.isNull() && "Can't find 'id' type");
2463 ArgTys.push_back(argT);
2464 argT = Context->getObjCSelType();
2465 assert(!argT.isNull() && "Can't find 'SEL' type");
2466 ArgTys.push_back(argT);
2467 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2468 ArgTys, /*isVariadic=*/true);
2469 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2472 msgSendIdent, msgSendType,
2473 nullptr, SC_Extern);
2476 // SynthMsgSendSuperStretFunctionDecl -
2477 // id objc_msgSendSuper_stret(void);
2478 void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2479 IdentifierInfo *msgSendIdent =
2480 &Context->Idents.get("objc_msgSendSuper_stret");
2481 SmallVector<QualType, 2> ArgTys;
2482 ArgTys.push_back(Context->VoidTy);
2483 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2484 ArgTys, /*isVariadic=*/true);
2485 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2489 msgSendType, nullptr,
2493 // SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2494 void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2495 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2496 SmallVector<QualType, 16> ArgTys;
2497 QualType argT = Context->getObjCIdType();
2498 assert(!argT.isNull() && "Can't find 'id' type");
2499 ArgTys.push_back(argT);
2500 argT = Context->getObjCSelType();
2501 assert(!argT.isNull() && "Can't find 'SEL' type");
2502 ArgTys.push_back(argT);
2503 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2504 ArgTys, /*isVariadic=*/true);
2505 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2508 msgSendIdent, msgSendType,
2509 nullptr, SC_Extern);
2512 // SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
2513 void RewriteModernObjC::SynthGetClassFunctionDecl() {
2514 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2515 SmallVector<QualType, 16> ArgTys;
2516 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2517 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2519 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2522 getClassIdent, getClassType,
2523 nullptr, SC_Extern);
2526 // SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2527 void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2528 IdentifierInfo *getSuperClassIdent =
2529 &Context->Idents.get("class_getSuperclass");
2530 SmallVector<QualType, 16> ArgTys;
2531 ArgTys.push_back(Context->getObjCClassType());
2532 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2534 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2538 getClassType, nullptr,
2542 // SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
2543 void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2544 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2545 SmallVector<QualType, 16> ArgTys;
2546 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2547 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2549 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2552 getClassIdent, getClassType,
2553 nullptr, SC_Extern);
2556 Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2557 assert (Exp != nullptr && "Expected non-null ObjCStringLiteral");
2558 QualType strType = getConstantStringStructType();
2560 std::string S = "__NSConstantStringImpl_";
2562 std::string tmpName = InFileName;
2564 for (i=0; i < tmpName.length(); i++) {
2565 char c = tmpName.at(i);
2566 // replace any non-alphanumeric characters with '_'.
2567 if (!isAlphanumeric(c))
2572 S += utostr(NumObjCStringLiterals++);
2574 Preamble += "static __NSConstantStringImpl " + S;
2575 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2576 Preamble += "0x000007c8,"; // utf8_str
2577 // The pretty printer for StringLiteral handles escape characters properly.
2578 std::string prettyBufS;
2579 llvm::raw_string_ostream prettyBuf(prettyBufS);
2580 Exp->getString()->printPretty(prettyBuf, nullptr, PrintingPolicy(LangOpts));
2581 Preamble += prettyBuf.str();
2583 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2585 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2586 SourceLocation(), &Context->Idents.get(S),
2587 strType, nullptr, SC_Static);
2588 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
2590 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2591 Context->getPointerType(DRE->getType()),
2592 VK_RValue, OK_Ordinary,
2594 // cast to NSConstantString *
2595 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2596 CK_CPointerToObjCPointerCast, Unop);
2597 ReplaceStmt(Exp, cast);
2598 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2602 Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2604 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2606 Expr *FlagExp = IntegerLiteral::Create(*Context,
2607 llvm::APInt(IntSize, Exp->getValue()),
2608 Context->IntTy, Exp->getLocation());
2609 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2610 CK_BitCast, FlagExp);
2611 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2613 ReplaceStmt(Exp, PE);
2617 Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
2618 // synthesize declaration of helper functions needed in this routine.
2619 if (!SelGetUidFunctionDecl)
2620 SynthSelGetUidFunctionDecl();
2621 // use objc_msgSend() for all.
2622 if (!MsgSendFunctionDecl)
2623 SynthMsgSendFunctionDecl();
2624 if (!GetClassFunctionDecl)
2625 SynthGetClassFunctionDecl();
2627 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2628 SourceLocation StartLoc = Exp->getLocStart();
2629 SourceLocation EndLoc = Exp->getLocEnd();
2631 // Synthesize a call to objc_msgSend().
2632 SmallVector<Expr*, 4> MsgExprs;
2633 SmallVector<Expr*, 4> ClsExprs;
2635 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2636 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2637 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
2639 IdentifierInfo *clsName = BoxingClass->getIdentifier();
2640 ClsExprs.push_back(getStringLiteral(clsName->getName()));
2641 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
2643 MsgExprs.push_back(Cls);
2645 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
2646 // it will be the 2nd argument.
2647 SmallVector<Expr*, 4> SelExprs;
2649 getStringLiteral(BoxingMethod->getSelector().getAsString()));
2650 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2651 SelExprs, StartLoc, EndLoc);
2652 MsgExprs.push_back(SelExp);
2654 // User provided sub-expression is the 3rd, and last, argument.
2655 Expr *subExpr = Exp->getSubExpr();
2656 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
2657 QualType type = ICE->getType();
2658 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2659 CastKind CK = CK_BitCast;
2660 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2661 CK = CK_IntegralToBoolean;
2662 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
2664 MsgExprs.push_back(subExpr);
2666 SmallVector<QualType, 4> ArgTypes;
2667 ArgTypes.push_back(Context->getObjCClassType());
2668 ArgTypes.push_back(Context->getObjCSelType());
2669 for (const auto PI : BoxingMethod->parameters())
2670 ArgTypes.push_back(PI->getType());
2672 QualType returnType = Exp->getType();
2673 // Get the type, we will need to reference it in a couple spots.
2674 QualType msgSendType = MsgSendFlavor->getType();
2676 // Create a reference to the objc_msgSend() declaration.
2677 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2678 VK_LValue, SourceLocation());
2680 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2681 Context->getPointerType(Context->VoidTy),
2684 // Now do the "normal" pointer to function cast.
2686 getSimpleFunctionType(returnType, ArgTypes, BoxingMethod->isVariadic());
2687 castType = Context->getPointerType(castType);
2688 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2691 // Don't forget the parens to enforce the proper binding.
2692 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2694 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2695 CallExpr *CE = new (Context)
2696 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
2697 ReplaceStmt(Exp, CE);
2701 Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2702 // synthesize declaration of helper functions needed in this routine.
2703 if (!SelGetUidFunctionDecl)
2704 SynthSelGetUidFunctionDecl();
2705 // use objc_msgSend() for all.
2706 if (!MsgSendFunctionDecl)
2707 SynthMsgSendFunctionDecl();
2708 if (!GetClassFunctionDecl)
2709 SynthGetClassFunctionDecl();
2711 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2712 SourceLocation StartLoc = Exp->getLocStart();
2713 SourceLocation EndLoc = Exp->getLocEnd();
2715 // Build the expression: __NSContainer_literal(int, ...).arr
2716 QualType IntQT = Context->IntTy;
2717 QualType NSArrayFType =
2718 getSimpleFunctionType(Context->VoidTy, IntQT, true);
2719 std::string NSArrayFName("__NSContainer_literal");
2720 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2721 DeclRefExpr *NSArrayDRE =
2722 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2725 SmallVector<Expr*, 16> InitExprs;
2726 unsigned NumElements = Exp->getNumElements();
2727 unsigned UnsignedIntSize =
2728 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2729 Expr *count = IntegerLiteral::Create(*Context,
2730 llvm::APInt(UnsignedIntSize, NumElements),
2731 Context->UnsignedIntTy, SourceLocation());
2732 InitExprs.push_back(count);
2733 for (unsigned i = 0; i < NumElements; i++)
2734 InitExprs.push_back(Exp->getElement(i));
2735 Expr *NSArrayCallExpr =
2736 new (Context) CallExpr(*Context, NSArrayDRE, InitExprs,
2737 NSArrayFType, VK_LValue, SourceLocation());
2739 FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
2741 &Context->Idents.get("arr"),
2742 Context->getPointerType(Context->VoidPtrTy),
2743 nullptr, /*BitWidth=*/nullptr,
2744 /*Mutable=*/true, ICIS_NoInit);
2745 MemberExpr *ArrayLiteralME = new (Context)
2746 MemberExpr(NSArrayCallExpr, false, SourceLocation(), ARRFD,
2747 SourceLocation(), ARRFD->getType(), VK_LValue, OK_Ordinary);
2748 QualType ConstIdT = Context->getObjCIdType().withConst();
2749 CStyleCastExpr * ArrayLiteralObjects =
2750 NoTypeInfoCStyleCastExpr(Context,
2751 Context->getPointerType(ConstIdT),
2755 // Synthesize a call to objc_msgSend().
2756 SmallVector<Expr*, 32> MsgExprs;
2757 SmallVector<Expr*, 4> ClsExprs;
2758 QualType expType = Exp->getType();
2760 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2761 ObjCInterfaceDecl *Class =
2762 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2764 IdentifierInfo *clsName = Class->getIdentifier();
2765 ClsExprs.push_back(getStringLiteral(clsName->getName()));
2766 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
2768 MsgExprs.push_back(Cls);
2770 // Create a call to sel_registerName("arrayWithObjects:count:").
2771 // it will be the 2nd argument.
2772 SmallVector<Expr*, 4> SelExprs;
2773 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
2775 getStringLiteral(ArrayMethod->getSelector().getAsString()));
2776 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2777 SelExprs, StartLoc, EndLoc);
2778 MsgExprs.push_back(SelExp);
2780 // (const id [])objects
2781 MsgExprs.push_back(ArrayLiteralObjects);
2784 Expr *cnt = IntegerLiteral::Create(*Context,
2785 llvm::APInt(UnsignedIntSize, NumElements),
2786 Context->UnsignedIntTy, SourceLocation());
2787 MsgExprs.push_back(cnt);
2789 SmallVector<QualType, 4> ArgTypes;
2790 ArgTypes.push_back(Context->getObjCClassType());
2791 ArgTypes.push_back(Context->getObjCSelType());
2792 for (const auto *PI : ArrayMethod->parameters())
2793 ArgTypes.push_back(PI->getType());
2795 QualType returnType = Exp->getType();
2796 // Get the type, we will need to reference it in a couple spots.
2797 QualType msgSendType = MsgSendFlavor->getType();
2799 // Create a reference to the objc_msgSend() declaration.
2800 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2801 VK_LValue, SourceLocation());
2803 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2804 Context->getPointerType(Context->VoidTy),
2807 // Now do the "normal" pointer to function cast.
2809 getSimpleFunctionType(returnType, ArgTypes, ArrayMethod->isVariadic());
2810 castType = Context->getPointerType(castType);
2811 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2814 // Don't forget the parens to enforce the proper binding.
2815 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2817 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2818 CallExpr *CE = new (Context)
2819 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
2820 ReplaceStmt(Exp, CE);
2824 Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2825 // synthesize declaration of helper functions needed in this routine.
2826 if (!SelGetUidFunctionDecl)
2827 SynthSelGetUidFunctionDecl();
2828 // use objc_msgSend() for all.
2829 if (!MsgSendFunctionDecl)
2830 SynthMsgSendFunctionDecl();
2831 if (!GetClassFunctionDecl)
2832 SynthGetClassFunctionDecl();
2834 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2835 SourceLocation StartLoc = Exp->getLocStart();
2836 SourceLocation EndLoc = Exp->getLocEnd();
2838 // Build the expression: __NSContainer_literal(int, ...).arr
2839 QualType IntQT = Context->IntTy;
2840 QualType NSDictFType =
2841 getSimpleFunctionType(Context->VoidTy, IntQT, true);
2842 std::string NSDictFName("__NSContainer_literal");
2843 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2844 DeclRefExpr *NSDictDRE =
2845 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2848 SmallVector<Expr*, 16> KeyExprs;
2849 SmallVector<Expr*, 16> ValueExprs;
2851 unsigned NumElements = Exp->getNumElements();
2852 unsigned UnsignedIntSize =
2853 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2854 Expr *count = IntegerLiteral::Create(*Context,
2855 llvm::APInt(UnsignedIntSize, NumElements),
2856 Context->UnsignedIntTy, SourceLocation());
2857 KeyExprs.push_back(count);
2858 ValueExprs.push_back(count);
2859 for (unsigned i = 0; i < NumElements; i++) {
2860 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2861 KeyExprs.push_back(Element.Key);
2862 ValueExprs.push_back(Element.Value);
2865 // (const id [])objects
2866 Expr *NSValueCallExpr =
2867 new (Context) CallExpr(*Context, NSDictDRE, ValueExprs,
2868 NSDictFType, VK_LValue, SourceLocation());
2870 FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
2872 &Context->Idents.get("arr"),
2873 Context->getPointerType(Context->VoidPtrTy),
2874 nullptr, /*BitWidth=*/nullptr,
2875 /*Mutable=*/true, ICIS_NoInit);
2876 MemberExpr *DictLiteralValueME = new (Context)
2877 MemberExpr(NSValueCallExpr, false, SourceLocation(), ARRFD,
2878 SourceLocation(), ARRFD->getType(), VK_LValue, OK_Ordinary);
2879 QualType ConstIdT = Context->getObjCIdType().withConst();
2880 CStyleCastExpr * DictValueObjects =
2881 NoTypeInfoCStyleCastExpr(Context,
2882 Context->getPointerType(ConstIdT),
2884 DictLiteralValueME);
2885 // (const id <NSCopying> [])keys
2886 Expr *NSKeyCallExpr =
2887 new (Context) CallExpr(*Context, NSDictDRE, KeyExprs,
2888 NSDictFType, VK_LValue, SourceLocation());
2890 MemberExpr *DictLiteralKeyME = new (Context)
2891 MemberExpr(NSKeyCallExpr, false, SourceLocation(), ARRFD,
2892 SourceLocation(), ARRFD->getType(), VK_LValue, OK_Ordinary);
2894 CStyleCastExpr * DictKeyObjects =
2895 NoTypeInfoCStyleCastExpr(Context,
2896 Context->getPointerType(ConstIdT),
2900 // Synthesize a call to objc_msgSend().
2901 SmallVector<Expr*, 32> MsgExprs;
2902 SmallVector<Expr*, 4> ClsExprs;
2903 QualType expType = Exp->getType();
2905 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2906 ObjCInterfaceDecl *Class =
2907 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2909 IdentifierInfo *clsName = Class->getIdentifier();
2910 ClsExprs.push_back(getStringLiteral(clsName->getName()));
2911 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
2913 MsgExprs.push_back(Cls);
2915 // Create a call to sel_registerName("arrayWithObjects:count:").
2916 // it will be the 2nd argument.
2917 SmallVector<Expr*, 4> SelExprs;
2918 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
2919 SelExprs.push_back(getStringLiteral(DictMethod->getSelector().getAsString()));
2920 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2921 SelExprs, StartLoc, EndLoc);
2922 MsgExprs.push_back(SelExp);
2924 // (const id [])objects
2925 MsgExprs.push_back(DictValueObjects);
2927 // (const id <NSCopying> [])keys
2928 MsgExprs.push_back(DictKeyObjects);
2931 Expr *cnt = IntegerLiteral::Create(*Context,
2932 llvm::APInt(UnsignedIntSize, NumElements),
2933 Context->UnsignedIntTy, SourceLocation());
2934 MsgExprs.push_back(cnt);
2936 SmallVector<QualType, 8> ArgTypes;
2937 ArgTypes.push_back(Context->getObjCClassType());
2938 ArgTypes.push_back(Context->getObjCSelType());
2939 for (const auto *PI : DictMethod->parameters()) {
2940 QualType T = PI->getType();
2941 if (const PointerType* PT = T->getAs<PointerType>()) {
2942 QualType PointeeTy = PT->getPointeeType();
2943 convertToUnqualifiedObjCType(PointeeTy);
2944 T = Context->getPointerType(PointeeTy);
2946 ArgTypes.push_back(T);
2949 QualType returnType = Exp->getType();
2950 // Get the type, we will need to reference it in a couple spots.
2951 QualType msgSendType = MsgSendFlavor->getType();
2953 // Create a reference to the objc_msgSend() declaration.
2954 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2955 VK_LValue, SourceLocation());
2957 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2958 Context->getPointerType(Context->VoidTy),
2961 // Now do the "normal" pointer to function cast.
2963 getSimpleFunctionType(returnType, ArgTypes, DictMethod->isVariadic());
2964 castType = Context->getPointerType(castType);
2965 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2968 // Don't forget the parens to enforce the proper binding.
2969 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2971 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2972 CallExpr *CE = new (Context)
2973 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
2974 ReplaceStmt(Exp, CE);
2978 // struct __rw_objc_super {
2979 // struct objc_object *object; struct objc_object *superClass;
2981 QualType RewriteModernObjC::getSuperStructType() {
2982 if (!SuperStructDecl) {
2983 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2984 SourceLocation(), SourceLocation(),
2985 &Context->Idents.get("__rw_objc_super"));
2986 QualType FieldTypes[2];
2988 // struct objc_object *object;
2989 FieldTypes[0] = Context->getObjCIdType();
2990 // struct objc_object *superClass;
2991 FieldTypes[1] = Context->getObjCIdType();
2994 for (unsigned i = 0; i < 2; ++i) {
2995 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2997 SourceLocation(), nullptr,
2998 FieldTypes[i], nullptr,
2999 /*BitWidth=*/nullptr,
3004 SuperStructDecl->completeDefinition();
3006 return Context->getTagDeclType(SuperStructDecl);
3009 QualType RewriteModernObjC::getConstantStringStructType() {
3010 if (!ConstantStringDecl) {
3011 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3012 SourceLocation(), SourceLocation(),
3013 &Context->Idents.get("__NSConstantStringImpl"));
3014 QualType FieldTypes[4];
3016 // struct objc_object *receiver;
3017 FieldTypes[0] = Context->getObjCIdType();
3019 FieldTypes[1] = Context->IntTy;
3021 FieldTypes[2] = Context->getPointerType(Context->CharTy);
3023 FieldTypes[3] = Context->LongTy;
3026 for (unsigned i = 0; i < 4; ++i) {
3027 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3030 SourceLocation(), nullptr,
3031 FieldTypes[i], nullptr,
3032 /*BitWidth=*/nullptr,
3037 ConstantStringDecl->completeDefinition();
3039 return Context->getTagDeclType(ConstantStringDecl);
3042 /// getFunctionSourceLocation - returns start location of a function
3043 /// definition. Complication arises when function has declared as
3044 /// extern "C" or extern "C" {...}
3045 static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3047 if (FD->isExternC() && !FD->isMain()) {
3048 const DeclContext *DC = FD->getDeclContext();
3049 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3050 // if it is extern "C" {...}, return function decl's own location.
3051 if (!LSD->getRBraceLoc().isValid())
3052 return LSD->getExternLoc();
3054 if (FD->getStorageClass() != SC_None)
3055 R.RewriteBlockLiteralFunctionDecl(FD);
3056 return FD->getTypeSpecStartLoc();
3059 void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
3061 SourceLocation Location = D->getLocation();
3063 if (Location.isFileID() && GenerateLineInfo) {
3064 std::string LineString("\n#line ");
3065 PresumedLoc PLoc = SM->getPresumedLoc(Location);
3066 LineString += utostr(PLoc.getLine());
3067 LineString += " \"";
3068 LineString += Lexer::Stringify(PLoc.getFilename());
3069 if (isa<ObjCMethodDecl>(D))
3071 else LineString += "\"\n";
3073 Location = D->getLocStart();
3074 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3075 if (FD->isExternC() && !FD->isMain()) {
3076 const DeclContext *DC = FD->getDeclContext();
3077 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3078 // if it is extern "C" {...}, return function decl's own location.
3079 if (!LSD->getRBraceLoc().isValid())
3080 Location = LSD->getExternLoc();
3083 InsertText(Location, LineString);
3087 /// SynthMsgSendStretCallExpr - This routine translates message expression
3088 /// into a call to objc_msgSend_stret() entry point. Tricky part is that
3089 /// nil check on receiver must be performed before calling objc_msgSend_stret.
3090 /// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3091 /// msgSendType - function type of objc_msgSend_stret(...)
3092 /// returnType - Result type of the method being synthesized.
3093 /// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
3094 /// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
3095 /// starting with receiver.
3096 /// Method - Method being rewritten.
3097 Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
3098 QualType returnType,
3099 SmallVectorImpl<QualType> &ArgTypes,
3100 SmallVectorImpl<Expr*> &MsgExprs,
3101 ObjCMethodDecl *Method) {
3102 // Now do the "normal" pointer to function cast.
3103 QualType castType = getSimpleFunctionType(returnType, ArgTypes,
3104 Method ? Method->isVariadic()
3106 castType = Context->getPointerType(castType);
3108 // build type for containing the objc_msgSend_stret object.
3109 static unsigned stretCount=0;
3110 std::string name = "__Stret"; name += utostr(stretCount);
3112 "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
3113 str += "namespace {\n";
3114 str += "struct "; str += name;
3117 str += "(id receiver, SEL sel";
3118 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3119 std::string ArgName = "arg"; ArgName += utostr(i);
3120 ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3121 str += ", "; str += ArgName;
3124 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3125 std::string ArgName = "arg"; ArgName += utostr(i);
3126 MsgExprs[i]->getType().getAsStringInternal(ArgName,
3127 Context->getPrintingPolicy());
3128 str += ", "; str += ArgName;
3132 str += "\t unsigned size = sizeof(";
3133 str += returnType.getAsString(Context->getPrintingPolicy()); str += ");\n";
3135 str += "\t if (size == 1 || size == 2 || size == 4 || size == 8)\n";
3137 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3138 str += ")(void *)objc_msgSend)(receiver, sel";
3139 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3140 str += ", arg"; str += utostr(i);
3143 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3144 str += ", arg"; str += utostr(i);
3148 str += "\t else if (receiver == 0)\n";
3149 str += "\t memset((void*)&s, 0, sizeof(s));\n";
3152 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3153 str += ")(void *)objc_msgSend_stret)(receiver, sel";
3154 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3155 str += ", arg"; str += utostr(i);
3158 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3159 str += ", arg"; str += utostr(i);
3164 str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3166 str += "};\n};\n\n";
3167 SourceLocation FunLocStart;
3169 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3171 assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
3172 FunLocStart = CurMethodDef->getLocStart();
3175 InsertText(FunLocStart, str);
3178 // AST for __Stretn(receiver, args).s;
3179 IdentifierInfo *ID = &Context->Idents.get(name);
3180 FunctionDecl *FD = FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
3181 SourceLocation(), ID, castType,
3182 nullptr, SC_Extern, false, false);
3183 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, castType, VK_RValue,
3185 CallExpr *STCE = new (Context) CallExpr(*Context, DRE, MsgExprs,
3186 castType, VK_LValue, SourceLocation());
3188 FieldDecl *FieldD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
3190 &Context->Idents.get("s"),
3191 returnType, nullptr,
3192 /*BitWidth=*/nullptr,
3193 /*Mutable=*/true, ICIS_NoInit);
3194 MemberExpr *ME = new (Context)
3195 MemberExpr(STCE, false, SourceLocation(), FieldD, SourceLocation(),
3196 FieldD->getType(), VK_LValue, OK_Ordinary);
3201 Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3202 SourceLocation StartLoc,
3203 SourceLocation EndLoc) {
3204 if (!SelGetUidFunctionDecl)
3205 SynthSelGetUidFunctionDecl();
3206 if (!MsgSendFunctionDecl)
3207 SynthMsgSendFunctionDecl();
3208 if (!MsgSendSuperFunctionDecl)
3209 SynthMsgSendSuperFunctionDecl();
3210 if (!MsgSendStretFunctionDecl)
3211 SynthMsgSendStretFunctionDecl();
3212 if (!MsgSendSuperStretFunctionDecl)
3213 SynthMsgSendSuperStretFunctionDecl();
3214 if (!MsgSendFpretFunctionDecl)
3215 SynthMsgSendFpretFunctionDecl();
3216 if (!GetClassFunctionDecl)
3217 SynthGetClassFunctionDecl();
3218 if (!GetSuperClassFunctionDecl)
3219 SynthGetSuperClassFunctionDecl();
3220 if (!GetMetaClassFunctionDecl)
3221 SynthGetMetaClassFunctionDecl();
3223 // default to objc_msgSend().
3224 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3225 // May need to use objc_msgSend_stret() as well.
3226 FunctionDecl *MsgSendStretFlavor = nullptr;
3227 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
3228 QualType resultType = mDecl->getReturnType();
3229 if (resultType->isRecordType())
3230 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3231 else if (resultType->isRealFloatingType())
3232 MsgSendFlavor = MsgSendFpretFunctionDecl;
3235 // Synthesize a call to objc_msgSend().
3236 SmallVector<Expr*, 8> MsgExprs;
3237 switch (Exp->getReceiverKind()) {
3238 case ObjCMessageExpr::SuperClass: {
3239 MsgSendFlavor = MsgSendSuperFunctionDecl;
3240 if (MsgSendStretFlavor)
3241 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3242 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3244 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3246 SmallVector<Expr*, 4> InitExprs;
3248 // set the receiver to self, the first argument to all methods.
3249 InitExprs.push_back(
3250 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3252 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
3254 Context->getObjCIdType(),
3257 ); // set the 'receiver'.
3259 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3260 SmallVector<Expr*, 8> ClsExprs;
3261 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
3262 // (Class)objc_getClass("CurrentClass")
3263 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3264 ClsExprs, StartLoc, EndLoc);
3266 ClsExprs.push_back(Cls);
3267 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
3270 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3271 // To turn off a warning, type-cast to 'id'
3272 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3273 NoTypeInfoCStyleCastExpr(Context,
3274 Context->getObjCIdType(),
3276 // struct __rw_objc_super
3277 QualType superType = getSuperStructType();
3280 if (LangOpts.MicrosoftExt) {
3281 SynthSuperConstructorFunctionDecl();
3282 // Simulate a constructor call...
3283 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
3284 false, superType, VK_LValue,
3286 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
3287 superType, VK_LValue,
3289 // The code for super is a little tricky to prevent collision with
3290 // the structure definition in the header. The rewriter has it's own
3291 // internal definition (__rw_objc_super) that is uses. This is why
3292 // we need the cast below. For example:
3293 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
3295 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3296 Context->getPointerType(SuperRep->getType()),
3297 VK_RValue, OK_Ordinary,
3299 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3300 Context->getPointerType(superType),
3301 CK_BitCast, SuperRep);
3303 // (struct __rw_objc_super) { <exprs from above> }
3305 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
3307 TypeSourceInfo *superTInfo
3308 = Context->getTrivialTypeSourceInfo(superType);
3309 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3310 superType, VK_LValue,
3312 // struct __rw_objc_super *
3313 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3314 Context->getPointerType(SuperRep->getType()),
3315 VK_RValue, OK_Ordinary,
3318 MsgExprs.push_back(SuperRep);
3322 case ObjCMessageExpr::Class: {
3323 SmallVector<Expr*, 8> ClsExprs;
3324 ObjCInterfaceDecl *Class
3325 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3326 IdentifierInfo *clsName = Class->getIdentifier();
3327 ClsExprs.push_back(getStringLiteral(clsName->getName()));
3328 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
3330 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3331 Context->getObjCIdType(),
3333 MsgExprs.push_back(ArgExpr);
3337 case ObjCMessageExpr::SuperInstance:{
3338 MsgSendFlavor = MsgSendSuperFunctionDecl;
3339 if (MsgSendStretFlavor)
3340 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3341 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3342 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3343 SmallVector<Expr*, 4> InitExprs;
3345 InitExprs.push_back(
3346 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3348 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
3350 Context->getObjCIdType(),
3351 VK_RValue, SourceLocation()))
3352 ); // set the 'receiver'.
3354 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3355 SmallVector<Expr*, 8> ClsExprs;
3356 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
3357 // (Class)objc_getClass("CurrentClass")
3358 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
3361 ClsExprs.push_back(Cls);
3362 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
3365 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3366 // To turn off a warning, type-cast to 'id'
3367 InitExprs.push_back(
3368 // set 'super class', using class_getSuperclass().
3369 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3371 // struct __rw_objc_super
3372 QualType superType = getSuperStructType();
3375 if (LangOpts.MicrosoftExt) {
3376 SynthSuperConstructorFunctionDecl();
3377 // Simulate a constructor call...
3378 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
3379 false, superType, VK_LValue,
3381 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
3382 superType, VK_LValue, SourceLocation());
3383 // The code for super is a little tricky to prevent collision with
3384 // the structure definition in the header. The rewriter has it's own
3385 // internal definition (__rw_objc_super) that is uses. This is why
3386 // we need the cast below. For example:
3387 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
3389 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3390 Context->getPointerType(SuperRep->getType()),
3391 VK_RValue, OK_Ordinary,
3393 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3394 Context->getPointerType(superType),
3395 CK_BitCast, SuperRep);
3397 // (struct __rw_objc_super) { <exprs from above> }
3399 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
3401 TypeSourceInfo *superTInfo
3402 = Context->getTrivialTypeSourceInfo(superType);
3403 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3404 superType, VK_RValue, ILE,
3407 MsgExprs.push_back(SuperRep);
3411 case ObjCMessageExpr::Instance: {
3412 // Remove all type-casts because it may contain objc-style types; e.g.
3414 Expr *recExpr = Exp->getInstanceReceiver();
3415 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3416 recExpr = CE->getSubExpr();
3417 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3418 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3419 ? CK_BlockPointerToObjCPointerCast
3420 : CK_CPointerToObjCPointerCast;
3422 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3424 MsgExprs.push_back(recExpr);
3429 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3430 SmallVector<Expr*, 8> SelExprs;
3431 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
3432 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3433 SelExprs, StartLoc, EndLoc);
3434 MsgExprs.push_back(SelExp);
3436 // Now push any user supplied arguments.
3437 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3438 Expr *userExpr = Exp->getArg(i);
3439 // Make all implicit casts explicit...ICE comes in handy:-)
3440 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3441 // Reuse the ICE type, it is exactly what the doctor ordered.
3442 QualType type = ICE->getType();
3443 if (needToScanForQualifiers(type))
3444 type = Context->getObjCIdType();
3445 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3446 (void)convertBlockPointerToFunctionPointer(type);
3447 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3449 if (SubExpr->getType()->isIntegralType(*Context) &&
3450 type->isBooleanType()) {
3451 CK = CK_IntegralToBoolean;
3452 } else if (type->isObjCObjectPointerType()) {
3453 if (SubExpr->getType()->isBlockPointerType()) {
3454 CK = CK_BlockPointerToObjCPointerCast;
3455 } else if (SubExpr->getType()->isPointerType()) {
3456 CK = CK_CPointerToObjCPointerCast;
3464 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3466 // Make id<P...> cast into an 'id' cast.
3467 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3468 if (CE->getType()->isObjCQualifiedIdType()) {
3469 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3470 userExpr = CE->getSubExpr();
3472 if (userExpr->getType()->isIntegralType(*Context)) {
3473 CK = CK_IntegralToPointer;
3474 } else if (userExpr->getType()->isBlockPointerType()) {
3475 CK = CK_BlockPointerToObjCPointerCast;
3476 } else if (userExpr->getType()->isPointerType()) {
3477 CK = CK_CPointerToObjCPointerCast;
3481 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3485 MsgExprs.push_back(userExpr);
3486 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3487 // out the argument in the original expression (since we aren't deleting
3488 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3489 //Exp->setArg(i, 0);
3491 // Generate the funky cast.
3493 SmallVector<QualType, 8> ArgTypes;
3494 QualType returnType;
3496 // Push 'id' and 'SEL', the 2 implicit arguments.
3497 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3498 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3500 ArgTypes.push_back(Context->getObjCIdType());
3501 ArgTypes.push_back(Context->getObjCSelType());
3502 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3503 // Push any user argument types.
3504 for (const auto *PI : OMD->parameters()) {
3505 QualType t = PI->getType()->isObjCQualifiedIdType()
3506 ? Context->getObjCIdType()
3508 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3509 (void)convertBlockPointerToFunctionPointer(t);
3510 ArgTypes.push_back(t);
3512 returnType = Exp->getType();
3513 convertToUnqualifiedObjCType(returnType);
3514 (void)convertBlockPointerToFunctionPointer(returnType);
3516 returnType = Context->getObjCIdType();
3518 // Get the type, we will need to reference it in a couple spots.
3519 QualType msgSendType = MsgSendFlavor->getType();
3521 // Create a reference to the objc_msgSend() declaration.
3522 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
3523 VK_LValue, SourceLocation());
3525 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3526 // If we don't do this cast, we get the following bizarre warning/note:
3527 // xx.m:13: warning: function called through a non-compatible type
3528 // xx.m:13: note: if this code is reached, the program will abort
3529 cast = NoTypeInfoCStyleCastExpr(Context,
3530 Context->getPointerType(Context->VoidTy),
3533 // Now do the "normal" pointer to function cast.
3534 // If we don't have a method decl, force a variadic cast.
3535 const ObjCMethodDecl *MD = Exp->getMethodDecl();
3537 getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
3538 castType = Context->getPointerType(castType);
3539 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3542 // Don't forget the parens to enforce the proper binding.
3543 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3545 const FunctionType *FT = msgSendType->getAs<FunctionType>();
3546 CallExpr *CE = new (Context)
3547 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
3548 Stmt *ReplacingStmt = CE;
3549 if (MsgSendStretFlavor) {
3550 // We have the method which returns a struct/union. Must also generate
3551 // call to objc_msgSend_stret and hang both varieties on a conditional
3552 // expression which dictate which one to envoke depending on size of
3553 // method's return type.
3555 Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3558 Exp->getMethodDecl());
3559 ReplacingStmt = STCE;
3561 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3562 return ReplacingStmt;
3565 Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3566 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3569 // Now do the actual rewrite.
3570 ReplaceStmt(Exp, ReplacingStmt);
3572 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3573 return ReplacingStmt;
3576 // typedef struct objc_object Protocol;
3577 QualType RewriteModernObjC::getProtocolType() {
3578 if (!ProtocolTypeDecl) {
3579 TypeSourceInfo *TInfo
3580 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3581 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3582 SourceLocation(), SourceLocation(),
3583 &Context->Idents.get("Protocol"),
3586 return Context->getTypeDeclType(ProtocolTypeDecl);
3589 /// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3590 /// a synthesized/forward data reference (to the protocol's metadata).
3591 /// The forward references (and metadata) are generated in
3592 /// RewriteModernObjC::HandleTranslationUnit().
3593 Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
3594 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3595 Exp->getProtocol()->getNameAsString();
3596 IdentifierInfo *ID = &Context->Idents.get(Name);
3597 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3598 SourceLocation(), ID, getProtocolType(),
3599 nullptr, SC_Extern);
3600 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3601 VK_LValue, SourceLocation());
3602 CastExpr *castExpr =
3603 NoTypeInfoCStyleCastExpr(
3604 Context, Context->getPointerType(DRE->getType()), CK_BitCast, DRE);
3605 ReplaceStmt(Exp, castExpr);
3606 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3607 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3611 /// IsTagDefinedInsideClass - This routine checks that a named tagged type
3612 /// is defined inside an objective-c class. If so, it returns true.
3613 bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
3615 bool &IsNamedDefinition) {
3618 SourceLocation TagLocation;
3619 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3620 RD = RD->getDefinition();
3621 if (!RD || !RD->getDeclName().getAsIdentifierInfo())
3623 IsNamedDefinition = true;
3624 TagLocation = RD->getLocation();
3625 return Context->getSourceManager().isBeforeInTranslationUnit(
3626 IDecl->getLocation(), TagLocation);
3628 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3629 if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3631 IsNamedDefinition = true;
3632 TagLocation = ED->getLocation();
3633 return Context->getSourceManager().isBeforeInTranslationUnit(
3634 IDecl->getLocation(), TagLocation);
3639 /// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
3640 /// It handles elaborated types, as well as enum types in the process.
3641 bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3642 std::string &Result) {
3643 if (isa<TypedefType>(Type)) {
3648 if (Type->isArrayType()) {
3649 QualType ElemTy = Context->getBaseElementType(Type);
3650 return RewriteObjCFieldDeclType(ElemTy, Result);
3652 else if (Type->isRecordType()) {
3653 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3654 if (RD->isCompleteDefinition()) {
3656 Result += "\n\tstruct ";
3657 else if (RD->isUnion())
3658 Result += "\n\tunion ";
3660 assert(false && "class not allowed as an ivar type");
3662 Result += RD->getName();
3663 if (GlobalDefinedTags.count(RD)) {
3664 // struct/union is defined globally, use it.
3669 for (auto *FD : RD->fields())
3670 RewriteObjCFieldDecl(FD, Result);
3675 else if (Type->isEnumeralType()) {
3676 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3677 if (ED->isCompleteDefinition()) {
3678 Result += "\n\tenum ";
3679 Result += ED->getName();
3680 if (GlobalDefinedTags.count(ED)) {
3681 // Enum is globall defined, use it.
3687 for (const auto *EC : ED->enumerators()) {
3688 Result += "\t"; Result += EC->getName(); Result += " = ";
3689 llvm::APSInt Val = EC->getInitVal();
3690 Result += Val.toString(10);
3699 convertObjCTypeToCStyleType(Type);
3704 /// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3705 /// It handles elaborated types, as well as enum types in the process.
3706 void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3707 std::string &Result) {
3708 QualType Type = fieldDecl->getType();
3709 std::string Name = fieldDecl->getNameAsString();
3711 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3712 if (!EleboratedType)
3713 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
3715 if (fieldDecl->isBitField()) {
3716 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3718 else if (EleboratedType && Type->isArrayType()) {
3719 const ArrayType *AT = Context->getAsArrayType(Type);
3721 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
3723 llvm::APInt Dim = CAT->getSize();
3724 Result += utostr(Dim.getZExtValue());
3727 AT = Context->getAsArrayType(AT->getElementType());
3734 /// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3735 /// named aggregate types into the input buffer.
3736 void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3737 std::string &Result) {
3738 QualType Type = fieldDecl->getType();
3739 if (isa<TypedefType>(Type))
3741 if (Type->isArrayType())
3742 Type = Context->getBaseElementType(Type);
3743 ObjCContainerDecl *IDecl =
3744 dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
3746 TagDecl *TD = nullptr;
3747 if (Type->isRecordType()) {
3748 TD = Type->getAs<RecordType>()->getDecl();
3750 else if (Type->isEnumeralType()) {
3751 TD = Type->getAs<EnumType>()->getDecl();
3755 if (GlobalDefinedTags.count(TD))
3758 bool IsNamedDefinition = false;
3759 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3760 RewriteObjCFieldDeclType(Type, Result);
3763 if (IsNamedDefinition)
3764 GlobalDefinedTags.insert(TD);
3768 unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) {
3769 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3770 if (ObjCInterefaceHasBitfieldGroups.count(CDecl)) {
3771 return IvarGroupNumber[IV];
3773 unsigned GroupNo = 0;
3774 SmallVector<const ObjCIvarDecl *, 8> IVars;
3775 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3776 IVD; IVD = IVD->getNextIvar())
3777 IVars.push_back(IVD);
3779 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3780 if (IVars[i]->isBitField()) {
3781 IvarGroupNumber[IVars[i++]] = ++GroupNo;
3782 while (i < e && IVars[i]->isBitField())
3783 IvarGroupNumber[IVars[i++]] = GroupNo;
3788 ObjCInterefaceHasBitfieldGroups.insert(CDecl);
3789 return IvarGroupNumber[IV];
3792 QualType RewriteModernObjC::SynthesizeBitfieldGroupStructType(
3794 SmallVectorImpl<ObjCIvarDecl *> &IVars) {
3795 std::string StructTagName;
3796 ObjCIvarBitfieldGroupType(IV, StructTagName);
3797 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct,
3798 Context->getTranslationUnitDecl(),
3799 SourceLocation(), SourceLocation(),
3800 &Context->Idents.get(StructTagName));
3801 for (unsigned i=0, e = IVars.size(); i < e; i++) {
3802 ObjCIvarDecl *Ivar = IVars[i];
3803 RD->addDecl(FieldDecl::Create(*Context, RD, SourceLocation(), SourceLocation(),
3804 &Context->Idents.get(Ivar->getName()),
3806 nullptr, /*Expr *BW */Ivar->getBitWidth(),
3807 false, ICIS_NoInit));
3809 RD->completeDefinition();
3810 return Context->getTagDeclType(RD);
3813 QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV) {
3814 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3815 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3816 std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo);
3817 if (GroupRecordType.count(tuple))
3818 return GroupRecordType[tuple];
3820 SmallVector<ObjCIvarDecl *, 8> IVars;
3821 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3822 IVD; IVD = IVD->getNextIvar()) {
3823 if (IVD->isBitField())
3824 IVars.push_back(const_cast<ObjCIvarDecl *>(IVD));
3826 if (!IVars.empty()) {
3827 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3828 // Generate the struct type for this group of bitfield ivars.
3829 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3830 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3835 if (!IVars.empty()) {
3837 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3838 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3839 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3841 QualType RetQT = GroupRecordType[tuple];
3842 assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL");
3847 /// ObjCIvarBitfieldGroupDecl - Names field decl. for ivar bitfield group.
3848 /// Name would be: classname__GRBF_n where n is the group number for this ivar.
3849 void RewriteModernObjC::ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV,
3850 std::string &Result) {
3851 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3852 Result += CDecl->getName();
3853 Result += "__GRBF_";
3854 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3855 Result += utostr(GroupNo);
3858 /// ObjCIvarBitfieldGroupType - Names struct type for ivar bitfield group.
3859 /// Name of the struct would be: classname__T_n where n is the group number for
3861 void RewriteModernObjC::ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV,
3862 std::string &Result) {
3863 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3864 Result += CDecl->getName();
3866 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3867 Result += utostr(GroupNo);
3870 /// ObjCIvarBitfieldGroupOffset - Names symbol for ivar bitfield group field offset.
3871 /// Name would be: OBJC_IVAR_$_classname__GRBF_n where n is the group number for
3873 void RewriteModernObjC::ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV,
3874 std::string &Result) {
3875 Result += "OBJC_IVAR_$_";
3876 ObjCIvarBitfieldGroupDecl(IV, Result);
3879 #define SKIP_BITFIELDS(IX, ENDIX, VEC) { \
3880 while ((IX < ENDIX) && VEC[IX]->isBitField()) \
3886 /// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3887 /// an objective-c class with ivars.
3888 void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3889 std::string &Result) {
3890 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3891 assert(CDecl->getName() != "" &&
3892 "Name missing in SynthesizeObjCInternalStruct");
3893 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
3894 SmallVector<ObjCIvarDecl *, 8> IVars;
3895 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3896 IVD; IVD = IVD->getNextIvar())
3897 IVars.push_back(IVD);
3899 SourceLocation LocStart = CDecl->getLocStart();
3900 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
3902 const char *startBuf = SM->getCharacterData(LocStart);
3903 const char *endBuf = SM->getCharacterData(LocEnd);
3905 // If no ivars and no root or if its root, directly or indirectly,
3906 // have no ivars (thus not synthesized) then no need to synthesize this class.
3907 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
3908 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3909 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3910 ReplaceText(LocStart, endBuf-startBuf, Result);
3914 // Insert named struct/union definitions inside class to
3915 // outer scope. This follows semantics of locally defined
3916 // struct/unions in objective-c classes.
3917 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3918 RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
3920 // Insert named structs which are syntheized to group ivar bitfields
3921 // to outer scope as well.
3922 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3923 if (IVars[i]->isBitField()) {
3924 ObjCIvarDecl *IV = IVars[i];
3925 QualType QT = GetGroupRecordTypeForObjCIvarBitfield(IV);
3926 RewriteObjCFieldDeclType(QT, Result);
3928 // skip over ivar bitfields in this group.
3929 SKIP_BITFIELDS(i , e, IVars);
3932 Result += "\nstruct ";
3933 Result += CDecl->getNameAsString();
3934 Result += "_IMPL {\n";
3936 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
3937 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3938 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3939 Result += "_IVARS;\n";
3942 for (unsigned i = 0, e = IVars.size(); i < e; i++) {
3943 if (IVars[i]->isBitField()) {
3944 ObjCIvarDecl *IV = IVars[i];
3945 Result += "\tstruct ";
3946 ObjCIvarBitfieldGroupType(IV, Result); Result += " ";
3947 ObjCIvarBitfieldGroupDecl(IV, Result); Result += ";\n";
3948 // skip over ivar bitfields in this group.
3949 SKIP_BITFIELDS(i , e, IVars);
3952 RewriteObjCFieldDecl(IVars[i], Result);
3956 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3957 ReplaceText(LocStart, endBuf-startBuf, Result);
3958 // Mark this struct as having been generated.
3959 if (!ObjCSynthesizedStructs.insert(CDecl).second)
3960 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
3963 /// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3964 /// have been referenced in an ivar access expression.
3965 void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3966 std::string &Result) {
3967 // write out ivar offset symbols which have been referenced in an ivar
3968 // access expression.
3969 llvm::SmallSetVector<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3974 llvm::DenseSet<std::pair<const ObjCInterfaceDecl*, unsigned> > GroupSymbolOutput;
3975 for (ObjCIvarDecl *IvarDecl : Ivars) {
3976 const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface();
3977 unsigned GroupNo = 0;
3978 if (IvarDecl->isBitField()) {
3979 GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl);
3980 if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo)))
3984 if (LangOpts.MicrosoftExt)
3985 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
3986 Result += "extern \"C\" ";
3987 if (LangOpts.MicrosoftExt &&
3988 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
3989 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
3990 Result += "__declspec(dllimport) ";
3992 Result += "unsigned long ";
3993 if (IvarDecl->isBitField()) {
3994 ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
3995 GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo));
3998 WriteInternalIvarName(CDecl, IvarDecl, Result);
4003 //===----------------------------------------------------------------------===//
4004 // Meta Data Emission
4005 //===----------------------------------------------------------------------===//
4007 /// RewriteImplementations - This routine rewrites all method implementations
4008 /// and emits meta-data.
4010 void RewriteModernObjC::RewriteImplementations() {
4011 int ClsDefCount = ClassImplementation.size();
4012 int CatDefCount = CategoryImplementation.size();
4014 // Rewrite implemented methods
4015 for (int i = 0; i < ClsDefCount; i++) {
4016 ObjCImplementationDecl *OIMP = ClassImplementation[i];
4017 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
4018 if (CDecl->isImplicitInterfaceDecl())
4020 "Legacy implicit interface rewriting not supported in moder abi");
4021 RewriteImplementationDecl(OIMP);
4024 for (int i = 0; i < CatDefCount; i++) {
4025 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
4026 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
4027 if (CDecl->isImplicitInterfaceDecl())
4029 "Legacy implicit interface rewriting not supported in moder abi");
4030 RewriteImplementationDecl(CIMP);
4034 void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
4035 const std::string &Name,
4036 ValueDecl *VD, bool def) {
4037 assert(BlockByRefDeclNo.count(VD) &&
4038 "RewriteByRefString: ByRef decl missing");
4040 ResultStr += "struct ";
4041 ResultStr += "__Block_byref_" + Name +
4042 "_" + utostr(BlockByRefDeclNo[VD]) ;
4045 static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4046 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4047 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4051 std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4054 const FunctionType *AFT = CE->getFunctionType();
4055 QualType RT = AFT->getReturnType();
4056 std::string StructRef = "struct " + Tag;
4057 SourceLocation BlockLoc = CE->getExprLoc();
4059 ConvertSourceLocationToLineDirective(BlockLoc, S);
4061 S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
4062 funcName.str() + "_block_func_" + utostr(i);
4064 BlockDecl *BD = CE->getBlockDecl();
4066 if (isa<FunctionNoProtoType>(AFT)) {
4067 // No user-supplied arguments. Still need to pass in a pointer to the
4068 // block (to reference imported block decl refs).
4069 S += "(" + StructRef + " *__cself)";
4070 } else if (BD->param_empty()) {
4071 S += "(" + StructRef + " *__cself)";
4073 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4074 assert(FT && "SynthesizeBlockFunc: No function proto");
4076 // first add the implicit argument.
4077 S += StructRef + " *__cself, ";
4078 std::string ParamStr;
4079 for (BlockDecl::param_iterator AI = BD->param_begin(),
4080 E = BD->param_end(); AI != E; ++AI) {
4081 if (AI != BD->param_begin()) S += ", ";
4082 ParamStr = (*AI)->getNameAsString();
4083 QualType QT = (*AI)->getType();
4084 (void)convertBlockPointerToFunctionPointer(QT);
4085 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
4088 if (FT->isVariadic()) {
4089 if (!BD->param_empty()) S += ", ";
4096 // Create local declarations to avoid rewriting all closure decl ref exprs.
4097 // First, emit a declaration for all "by ref" decls.
4098 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
4099 E = BlockByRefDecls.end(); I != E; ++I) {
4101 std::string Name = (*I)->getNameAsString();
4102 std::string TypeString;
4103 RewriteByRefString(TypeString, Name, (*I));
4105 Name = TypeString + Name;
4106 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4108 // Next, emit a declaration for all "by copy" declarations.
4109 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
4110 E = BlockByCopyDecls.end(); I != E; ++I) {
4112 // Handle nested closure invocation. For example:
4114 // void (^myImportedClosure)(void);
4115 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
4117 // void (^anotherClosure)(void);
4118 // anotherClosure = ^(void) {
4119 // myImportedClosure(); // import and invoke the closure
4122 if (isTopLevelBlockPointerType((*I)->getType())) {
4123 RewriteBlockPointerTypeVariable(S, (*I));
4125 RewriteBlockPointerType(S, (*I)->getType());
4127 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4130 std::string Name = (*I)->getNameAsString();
4131 QualType QT = (*I)->getType();
4132 if (HasLocalVariableExternalStorage(*I))
4133 QT = Context->getPointerType(QT);
4134 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
4135 S += Name + " = __cself->" +
4136 (*I)->getNameAsString() + "; // bound by copy\n";
4139 std::string RewrittenStr = RewrittenBlockExprs[CE];
4140 const char *cstr = RewrittenStr.c_str();
4141 while (*cstr++ != '{') ;
4147 std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4150 std::string StructRef = "struct " + Tag;
4151 std::string S = "static void __";
4154 S += "_block_copy_" + utostr(i);
4155 S += "(" + StructRef;
4156 S += "*dst, " + StructRef;
4158 for (ValueDecl *VD : ImportedBlockDecls) {
4159 S += "_Block_object_assign((void*)&dst->";
4160 S += VD->getNameAsString();
4161 S += ", (void*)src->";
4162 S += VD->getNameAsString();
4163 if (BlockByRefDeclsPtrSet.count(VD))
4164 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4165 else if (VD->getType()->isBlockPointerType())
4166 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4168 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4172 S += "\nstatic void __";
4174 S += "_block_dispose_" + utostr(i);
4175 S += "(" + StructRef;
4177 for (ValueDecl *VD : ImportedBlockDecls) {
4178 S += "_Block_object_dispose((void*)src->";
4179 S += VD->getNameAsString();
4180 if (BlockByRefDeclsPtrSet.count(VD))
4181 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4182 else if (VD->getType()->isBlockPointerType())
4183 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4185 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4191 std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4193 std::string S = "\nstruct " + Tag;
4194 std::string Constructor = " " + Tag;
4196 S += " {\n struct __block_impl impl;\n";
4197 S += " struct " + Desc;
4200 Constructor += "(void *fp, "; // Invoke function pointer.
4201 Constructor += "struct " + Desc; // Descriptor pointer.
4202 Constructor += " *desc";
4204 if (BlockDeclRefs.size()) {
4205 // Output all "by copy" declarations.
4206 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
4207 E = BlockByCopyDecls.end(); I != E; ++I) {
4209 std::string FieldName = (*I)->getNameAsString();
4210 std::string ArgName = "_" + FieldName;
4211 // Handle nested closure invocation. For example:
4213 // void (^myImportedBlock)(void);
4214 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
4216 // void (^anotherBlock)(void);
4217 // anotherBlock = ^(void) {
4218 // myImportedBlock(); // import and invoke the closure
4221 if (isTopLevelBlockPointerType((*I)->getType())) {
4222 S += "struct __block_impl *";
4223 Constructor += ", void *" + ArgName;
4225 QualType QT = (*I)->getType();
4226 if (HasLocalVariableExternalStorage(*I))
4227 QT = Context->getPointerType(QT);
4228 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4229 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4230 Constructor += ", " + ArgName;
4232 S += FieldName + ";\n";
4234 // Output all "by ref" declarations.
4235 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
4236 E = BlockByRefDecls.end(); I != E; ++I) {
4238 std::string FieldName = (*I)->getNameAsString();
4239 std::string ArgName = "_" + FieldName;
4241 std::string TypeString;
4242 RewriteByRefString(TypeString, FieldName, (*I));
4244 FieldName = TypeString + FieldName;
4245 ArgName = TypeString + ArgName;
4246 Constructor += ", " + ArgName;
4248 S += FieldName + "; // by ref\n";
4250 // Finish writing the constructor.
4251 Constructor += ", int flags=0)";
4252 // Initialize all "by copy" arguments.
4253 bool firsTime = true;
4254 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
4255 E = BlockByCopyDecls.end(); I != E; ++I) {
4256 std::string Name = (*I)->getNameAsString();
4258 Constructor += " : ";
4262 Constructor += ", ";
4263 if (isTopLevelBlockPointerType((*I)->getType()))
4264 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4266 Constructor += Name + "(_" + Name + ")";
4268 // Initialize all "by ref" arguments.
4269 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
4270 E = BlockByRefDecls.end(); I != E; ++I) {
4271 std::string Name = (*I)->getNameAsString();
4273 Constructor += " : ";
4277 Constructor += ", ";
4278 Constructor += Name + "(_" + Name + "->__forwarding)";
4281 Constructor += " {\n";
4283 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4285 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4286 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4288 Constructor += " Desc = desc;\n";
4290 // Finish writing the constructor.
4291 Constructor += ", int flags=0) {\n";
4293 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4295 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4296 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4297 Constructor += " Desc = desc;\n";
4300 Constructor += "}\n";
4306 std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4307 std::string ImplTag, int i,
4310 std::string S = "\nstatic struct " + DescTag;
4312 S += " {\n size_t reserved;\n";
4313 S += " size_t Block_size;\n";
4315 S += " void (*copy)(struct ";
4316 S += ImplTag; S += "*, struct ";
4317 S += ImplTag; S += "*);\n";
4319 S += " void (*dispose)(struct ";
4320 S += ImplTag; S += "*);\n";
4324 S += DescTag + "_DATA = { 0, sizeof(struct ";
4327 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4328 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4334 void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4335 StringRef FunName) {
4336 bool RewriteSC = (GlobalVarDecl &&
4338 GlobalVarDecl->getStorageClass() == SC_Static &&
4339 GlobalVarDecl->getType().getCVRQualifiers());
4341 std::string SC(" void __");
4342 SC += GlobalVarDecl->getNameAsString();
4344 InsertText(FunLocStart, SC);
4347 // Insert closures that were part of the function.
4348 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4349 CollectBlockDeclRefInfo(Blocks[i]);
4350 // Need to copy-in the inner copied-in variables not actually used in this
4352 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4353 DeclRefExpr *Exp = InnerDeclRefs[count++];
4354 ValueDecl *VD = Exp->getDecl();
4355 BlockDeclRefs.push_back(Exp);
4356 if (!VD->hasAttr<BlocksAttr>()) {
4357 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4358 BlockByCopyDeclsPtrSet.insert(VD);
4359 BlockByCopyDecls.push_back(VD);
4364 if (!BlockByRefDeclsPtrSet.count(VD)) {
4365 BlockByRefDeclsPtrSet.insert(VD);
4366 BlockByRefDecls.push_back(VD);
4369 // imported objects in the inner blocks not used in the outer
4370 // blocks must be copied/disposed in the outer block as well.
4371 if (VD->getType()->isObjCObjectPointerType() ||
4372 VD->getType()->isBlockPointerType())
4373 ImportedBlockDecls.insert(VD);
4376 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4377 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4379 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4381 InsertText(FunLocStart, CI);
4383 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4385 InsertText(FunLocStart, CF);
4387 if (ImportedBlockDecls.size()) {
4388 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4389 InsertText(FunLocStart, HF);
4391 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4392 ImportedBlockDecls.size() > 0);
4393 InsertText(FunLocStart, BD);
4395 BlockDeclRefs.clear();
4396 BlockByRefDecls.clear();
4397 BlockByRefDeclsPtrSet.clear();
4398 BlockByCopyDecls.clear();
4399 BlockByCopyDeclsPtrSet.clear();
4400 ImportedBlockDecls.clear();
4403 // Must insert any 'const/volatile/static here. Since it has been
4404 // removed as result of rewriting of block literals.
4406 if (GlobalVarDecl->getStorageClass() == SC_Static)
4408 if (GlobalVarDecl->getType().isConstQualified())
4410 if (GlobalVarDecl->getType().isVolatileQualified())
4412 if (GlobalVarDecl->getType().isRestrictQualified())
4414 InsertText(FunLocStart, SC);
4416 if (GlobalConstructionExp) {
4417 // extra fancy dance for global literal expression.
4419 // Always the latest block expression on the block stack.
4420 std::string Tag = "__";
4422 Tag += "_block_impl_";
4423 Tag += utostr(Blocks.size()-1);
4424 std::string globalBuf = "static ";
4425 globalBuf += Tag; globalBuf += " ";
4428 llvm::raw_string_ostream constructorExprBuf(SStr);
4429 GlobalConstructionExp->printPretty(constructorExprBuf, nullptr,
4430 PrintingPolicy(LangOpts));
4431 globalBuf += constructorExprBuf.str();
4433 InsertText(FunLocStart, globalBuf);
4434 GlobalConstructionExp = nullptr;
4438 InnerDeclRefsCount.clear();
4439 InnerDeclRefs.clear();
4440 RewrittenBlockExprs.clear();
4443 void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4444 SourceLocation FunLocStart =
4445 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4446 : FD->getTypeSpecStartLoc();
4447 StringRef FuncName = FD->getName();
4449 SynthesizeBlockLiterals(FunLocStart, FuncName);
4452 static void BuildUniqueMethodName(std::string &Name,
4453 ObjCMethodDecl *MD) {
4454 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4455 Name = IFace->getName();
4456 Name += "__" + MD->getSelector().getAsString();
4457 // Convert colons to underscores.
4458 std::string::size_type loc = 0;
4459 while ((loc = Name.find(':', loc)) != std::string::npos)
4460 Name.replace(loc, 1, "_");
4463 void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4464 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4465 //SourceLocation FunLocStart = MD->getLocStart();
4466 SourceLocation FunLocStart = MD->getLocStart();
4467 std::string FuncName;
4468 BuildUniqueMethodName(FuncName, MD);
4469 SynthesizeBlockLiterals(FunLocStart, FuncName);
4472 void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4473 for (Stmt *SubStmt : S->children())
4475 if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt))
4476 GetBlockDeclRefExprs(CBE->getBody());
4478 GetBlockDeclRefExprs(SubStmt);
4480 // Handle specific things.
4481 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4482 if (DRE->refersToEnclosingVariableOrCapture() ||
4483 HasLocalVariableExternalStorage(DRE->getDecl()))
4484 // FIXME: Handle enums.
4485 BlockDeclRefs.push_back(DRE);
4488 void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4489 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
4490 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts) {
4491 for (Stmt *SubStmt : S->children())
4493 if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt)) {
4494 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4495 GetInnerBlockDeclRefExprs(CBE->getBody(),
4500 GetInnerBlockDeclRefExprs(SubStmt, InnerBlockDeclRefs, InnerContexts);
4502 // Handle specific things.
4503 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4504 if (DRE->refersToEnclosingVariableOrCapture() ||
4505 HasLocalVariableExternalStorage(DRE->getDecl())) {
4506 if (!InnerContexts.count(DRE->getDecl()->getDeclContext()))
4507 InnerBlockDeclRefs.push_back(DRE);
4508 if (VarDecl *Var = cast<VarDecl>(DRE->getDecl()))
4509 if (Var->isFunctionOrMethodVarDecl())
4510 ImportedLocalExternalDecls.insert(Var);
4515 /// convertObjCTypeToCStyleType - This routine converts such objc types
4516 /// as qualified objects, and blocks to their closest c/c++ types that
4517 /// it can. It returns true if input type was modified.
4518 bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4520 convertBlockPointerToFunctionPointer(T);
4521 if (T->isFunctionPointerType()) {
4523 if (const PointerType* PT = T->getAs<PointerType>()) {
4524 PointeeTy = PT->getPointeeType();
4525 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4526 T = convertFunctionTypeOfBlocks(FT);
4527 T = Context->getPointerType(T);
4532 convertToUnqualifiedObjCType(T);
4536 /// convertFunctionTypeOfBlocks - This routine converts a function type
4537 /// whose result type may be a block pointer or whose argument type(s)
4538 /// might be block pointers to an equivalent function type replacing
4539 /// all block pointers to function pointers.
4540 QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4541 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4542 // FTP will be null for closures that don't take arguments.
4543 // Generate a funky cast.
4544 SmallVector<QualType, 8> ArgTypes;
4545 QualType Res = FT->getReturnType();
4546 bool modified = convertObjCTypeToCStyleType(Res);
4549 for (auto &I : FTP->param_types()) {
4551 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4552 if (convertObjCTypeToCStyleType(t))
4554 ArgTypes.push_back(t);
4559 FuncType = getSimpleFunctionType(Res, ArgTypes);
4560 else FuncType = QualType(FT, 0);
4564 Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4565 // Navigate to relevant type information.
4566 const BlockPointerType *CPT = nullptr;
4568 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4569 CPT = DRE->getType()->getAs<BlockPointerType>();
4570 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4571 CPT = MExpr->getType()->getAs<BlockPointerType>();
4573 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4574 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4576 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4577 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4578 else if (const ConditionalOperator *CEXPR =
4579 dyn_cast<ConditionalOperator>(BlockExp)) {
4580 Expr *LHSExp = CEXPR->getLHS();
4581 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4582 Expr *RHSExp = CEXPR->getRHS();
4583 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4584 Expr *CONDExp = CEXPR->getCond();
4585 ConditionalOperator *CondExpr =
4586 new (Context) ConditionalOperator(CONDExp,
4587 SourceLocation(), cast<Expr>(LHSStmt),
4588 SourceLocation(), cast<Expr>(RHSStmt),
4589 Exp->getType(), VK_RValue, OK_Ordinary);
4591 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4592 CPT = IRE->getType()->getAs<BlockPointerType>();
4593 } else if (const PseudoObjectExpr *POE
4594 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4595 CPT = POE->getType()->castAs<BlockPointerType>();
4597 assert(false && "RewriteBlockClass: Bad type");
4599 assert(CPT && "RewriteBlockClass: Bad type");
4600 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4601 assert(FT && "RewriteBlockClass: Bad type");
4602 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4603 // FTP will be null for closures that don't take arguments.
4605 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4606 SourceLocation(), SourceLocation(),
4607 &Context->Idents.get("__block_impl"));
4608 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4610 // Generate a funky cast.
4611 SmallVector<QualType, 8> ArgTypes;
4613 // Push the block argument type.
4614 ArgTypes.push_back(PtrBlock);
4616 for (auto &I : FTP->param_types()) {
4618 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4619 if (!convertBlockPointerToFunctionPointer(t))
4620 convertToUnqualifiedObjCType(t);
4621 ArgTypes.push_back(t);
4624 // Now do the pointer to function cast.
4625 QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
4627 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4629 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4631 const_cast<Expr*>(BlockExp));
4632 // Don't forget the parens to enforce the proper binding.
4633 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4637 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
4639 &Context->Idents.get("FuncPtr"),
4640 Context->VoidPtrTy, nullptr,
4641 /*BitWidth=*/nullptr, /*Mutable=*/true,
4644 new (Context) MemberExpr(PE, true, SourceLocation(), FD, SourceLocation(),
4645 FD->getType(), VK_LValue, OK_Ordinary);
4647 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4649 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4651 SmallVector<Expr*, 8> BlkExprs;
4652 // Add the implicit argument.
4653 BlkExprs.push_back(BlkCast);
4654 // Add the user arguments.
4655 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4656 E = Exp->arg_end(); I != E; ++I) {
4657 BlkExprs.push_back(*I);
4659 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
4660 Exp->getType(), VK_RValue,
4665 // We need to return the rewritten expression to handle cases where the
4666 // DeclRefExpr is embedded in another expression being rewritten.
4673 // void (^myblock)() = ^() {
4674 // [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
4678 Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
4679 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4680 // for each DeclRefExp where BYREFVAR is name of the variable.
4681 ValueDecl *VD = DeclRefExp->getDecl();
4682 bool isArrow = DeclRefExp->refersToEnclosingVariableOrCapture() ||
4683 HasLocalVariableExternalStorage(DeclRefExp->getDecl());
4685 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
4687 &Context->Idents.get("__forwarding"),
4688 Context->VoidPtrTy, nullptr,
4689 /*BitWidth=*/nullptr, /*Mutable=*/true,
4691 MemberExpr *ME = new (Context)
4692 MemberExpr(DeclRefExp, isArrow, SourceLocation(), FD, SourceLocation(),
4693 FD->getType(), VK_LValue, OK_Ordinary);
4695 StringRef Name = VD->getName();
4696 FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(),
4697 &Context->Idents.get(Name),
4698 Context->VoidPtrTy, nullptr,
4699 /*BitWidth=*/nullptr, /*Mutable=*/true,
4702 new (Context) MemberExpr(ME, true, SourceLocation(), FD, SourceLocation(),
4703 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4705 // Need parens to enforce precedence.
4706 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4707 DeclRefExp->getExprLoc(),
4709 ReplaceStmt(DeclRefExp, PE);
4713 // Rewrites the imported local variable V with external storage
4714 // (static, extern, etc.) as *V
4716 Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4717 ValueDecl *VD = DRE->getDecl();
4718 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4719 if (!ImportedLocalExternalDecls.count(Var))
4721 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4722 VK_LValue, OK_Ordinary,
4723 DRE->getLocation());
4724 // Need parens to enforce precedence.
4725 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4727 ReplaceStmt(DRE, PE);
4731 void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4732 SourceLocation LocStart = CE->getLParenLoc();
4733 SourceLocation LocEnd = CE->getRParenLoc();
4735 // Need to avoid trying to rewrite synthesized casts.
4736 if (LocStart.isInvalid())
4738 // Need to avoid trying to rewrite casts contained in macros.
4739 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4742 const char *startBuf = SM->getCharacterData(LocStart);
4743 const char *endBuf = SM->getCharacterData(LocEnd);
4744 QualType QT = CE->getType();
4745 const Type* TypePtr = QT->getAs<Type>();
4746 if (isa<TypeOfExprType>(TypePtr)) {
4747 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4748 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4749 std::string TypeAsString = "(";
4750 RewriteBlockPointerType(TypeAsString, QT);
4751 TypeAsString += ")";
4752 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4755 // advance the location to startArgList.
4756 const char *argPtr = startBuf;
4758 while (*argPtr++ && (argPtr < endBuf)) {
4761 // Replace the '^' with '*'.
4762 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4763 ReplaceText(LocStart, 1, "*");
4769 void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4770 CastKind CastKind = IC->getCastKind();
4771 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4772 CastKind != CK_AnyPointerToBlockPointerCast)
4775 QualType QT = IC->getType();
4776 (void)convertBlockPointerToFunctionPointer(QT);
4777 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4778 std::string Str = "(";
4781 InsertText(IC->getSubExpr()->getLocStart(), Str);
4784 void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4785 SourceLocation DeclLoc = FD->getLocation();
4786 unsigned parenCount = 0;
4788 // We have 1 or more arguments that have closure pointers.
4789 const char *startBuf = SM->getCharacterData(DeclLoc);
4790 const char *startArgList = strchr(startBuf, '(');
4792 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4795 // advance the location to startArgList.
4796 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4797 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4799 const char *argPtr = startArgList;
4801 while (*argPtr++ && parenCount) {
4804 // Replace the '^' with '*'.
4805 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4806 ReplaceText(DeclLoc, 1, "*");
4818 bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4819 const FunctionProtoType *FTP;
4820 const PointerType *PT = QT->getAs<PointerType>();
4822 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4824 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4825 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4826 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4829 for (const auto &I : FTP->param_types())
4830 if (isTopLevelBlockPointerType(I))
4836 bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4837 const FunctionProtoType *FTP;
4838 const PointerType *PT = QT->getAs<PointerType>();
4840 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4842 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4843 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4844 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4847 for (const auto &I : FTP->param_types()) {
4848 if (I->isObjCQualifiedIdType())
4850 if (I->isObjCObjectPointerType() &&
4851 I->getPointeeType()->isObjCQualifiedInterfaceType())
4859 void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4860 const char *&RParen) {
4861 const char *argPtr = strchr(Name, '(');
4862 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4864 LParen = argPtr; // output the start.
4865 argPtr++; // skip past the left paren.
4866 unsigned parenCount = 1;
4868 while (*argPtr && parenCount) {
4870 case '(': parenCount++; break;
4871 case ')': parenCount--; break;
4874 if (parenCount) argPtr++;
4876 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4877 RParen = argPtr; // output the end
4880 void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4881 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4882 RewriteBlockPointerFunctionArgs(FD);
4885 // Handle Variables and Typedefs.
4886 SourceLocation DeclLoc = ND->getLocation();
4888 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4889 DeclT = VD->getType();
4890 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4891 DeclT = TDD->getUnderlyingType();
4892 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4893 DeclT = FD->getType();
4895 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4897 const char *startBuf = SM->getCharacterData(DeclLoc);
4898 const char *endBuf = startBuf;
4899 // scan backward (from the decl location) for the end of the previous decl.
4900 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4902 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4904 unsigned OrigLength=0;
4905 // *startBuf != '^' if we are dealing with a pointer to function that
4906 // may take block argument types (which will be handled below).
4907 if (*startBuf == '^') {
4908 // Replace the '^' with '*', computing a negative offset.
4913 while (*startBuf != ')') {
4921 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4922 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4923 // Replace the '^' with '*' for arguments.
4924 // Replace id<P> with id/*<>*/
4925 DeclLoc = ND->getLocation();
4926 startBuf = SM->getCharacterData(DeclLoc);
4927 const char *argListBegin, *argListEnd;
4928 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4929 while (argListBegin < argListEnd) {
4930 if (*argListBegin == '^')
4932 else if (*argListBegin == '<') {
4934 buf += *argListBegin++;
4936 while (*argListBegin != '>') {
4937 buf += *argListBegin++;
4940 buf += *argListBegin;
4944 buf += *argListBegin;
4951 ReplaceText(Start, OrigLength, buf);
4954 /// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4955 /// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4956 /// struct Block_byref_id_object *src) {
4957 /// _Block_object_assign (&_dest->object, _src->object,
4958 /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4959 /// [|BLOCK_FIELD_IS_WEAK]) // object
4960 /// _Block_object_assign(&_dest->object, _src->object,
4961 /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4962 /// [|BLOCK_FIELD_IS_WEAK]) // block
4965 /// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4966 /// _Block_object_dispose(_src->object,
4967 /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4968 /// [|BLOCK_FIELD_IS_WEAK]) // object
4969 /// _Block_object_dispose(_src->object,
4970 /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4971 /// [|BLOCK_FIELD_IS_WEAK]) // block
4974 std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4977 if (CopyDestroyCache.count(flag))
4979 CopyDestroyCache.insert(flag);
4980 S = "static void __Block_byref_id_object_copy_";
4982 S += "(void *dst, void *src) {\n";
4984 // offset into the object pointer is computed as:
4985 // void * + void* + int + int + void* + void *
4987 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4988 unsigned VoidPtrSize =
4989 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4991 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4992 S += " _Block_object_assign((char*)dst + ";
4993 S += utostr(offset);
4994 S += ", *(void * *) ((char*)src + ";
4995 S += utostr(offset);
5000 S += "static void __Block_byref_id_object_dispose_";
5002 S += "(void *src) {\n";
5003 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5004 S += utostr(offset);
5011 /// RewriteByRefVar - For each __block typex ND variable this routine transforms
5012 /// the declaration into:
5013 /// struct __Block_byref_ND {
5014 /// void *__isa; // NULL for everything except __weak pointers
5015 /// struct __Block_byref_ND *__forwarding;
5016 /// int32_t __flags;
5018 /// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5019 /// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
5023 /// It then replaces declaration of ND variable with:
5024 /// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5025 /// __size=sizeof(struct __Block_byref_ND),
5026 /// ND=initializer-if-any};
5029 void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
5033 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
5034 if (DeclLoc.isInvalid())
5035 // If type location is missing, it is because of missing type (a warning).
5036 // Use variable's location which is good for this case.
5037 DeclLoc = ND->getLocation();
5038 const char *startBuf = SM->getCharacterData(DeclLoc);
5039 SourceLocation X = ND->getLocEnd();
5040 X = SM->getExpansionLoc(X);
5041 const char *endBuf = SM->getCharacterData(X);
5042 std::string Name(ND->getNameAsString());
5043 std::string ByrefType;
5044 RewriteByRefString(ByrefType, Name, ND, true);
5045 ByrefType += " {\n";
5046 ByrefType += " void *__isa;\n";
5047 RewriteByRefString(ByrefType, Name, ND);
5048 ByrefType += " *__forwarding;\n";
5049 ByrefType += " int __flags;\n";
5050 ByrefType += " int __size;\n";
5051 // Add void *__Block_byref_id_object_copy;
5052 // void *__Block_byref_id_object_dispose; if needed.
5053 QualType Ty = ND->getType();
5054 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
5055 if (HasCopyAndDispose) {
5056 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5057 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5061 (void)convertBlockPointerToFunctionPointer(T);
5062 T.getAsStringInternal(Name, Context->getPrintingPolicy());
5064 ByrefType += " " + Name + ";\n";
5065 ByrefType += "};\n";
5066 // Insert this type in global scope. It is needed by helper function.
5067 SourceLocation FunLocStart;
5069 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
5071 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5072 FunLocStart = CurMethodDef->getLocStart();
5074 InsertText(FunLocStart, ByrefType);
5076 if (Ty.isObjCGCWeak()) {
5077 flag |= BLOCK_FIELD_IS_WEAK;
5080 if (HasCopyAndDispose) {
5081 flag = BLOCK_BYREF_CALLER;
5082 QualType Ty = ND->getType();
5083 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5084 if (Ty->isBlockPointerType())
5085 flag |= BLOCK_FIELD_IS_BLOCK;
5087 flag |= BLOCK_FIELD_IS_OBJECT;
5088 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5093 // struct __Block_byref_ND ND =
5094 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5095 // initializer-if-any};
5096 bool hasInit = (ND->getInit() != nullptr);
5097 // FIXME. rewriter does not support __block c++ objects which
5098 // require construction.
5100 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5101 CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5102 if (CXXDecl && CXXDecl->isDefaultConstructor())
5107 if (HasCopyAndDispose)
5108 flags |= BLOCK_HAS_COPY_DISPOSE;
5109 Name = ND->getNameAsString();
5111 RewriteByRefString(ByrefType, Name, ND);
5112 std::string ForwardingCastType("(");
5113 ForwardingCastType += ByrefType + " *)";
5114 ByrefType += " " + Name + " = {(void*)";
5115 ByrefType += utostr(isa);
5116 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
5117 ByrefType += utostr(flags);
5119 ByrefType += "sizeof(";
5120 RewriteByRefString(ByrefType, Name, ND);
5122 if (HasCopyAndDispose) {
5123 ByrefType += ", __Block_byref_id_object_copy_";
5124 ByrefType += utostr(flag);
5125 ByrefType += ", __Block_byref_id_object_dispose_";
5126 ByrefType += utostr(flag);
5130 // In multiple __block declarations, and for all but 1st declaration,
5131 // find location of the separating comma. This would be start location
5132 // where new text is to be inserted.
5133 DeclLoc = ND->getLocation();
5134 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5135 const char *commaBuf = startDeclBuf;
5136 while (*commaBuf != ',')
5138 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5139 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5140 startBuf = commaBuf;
5144 ByrefType += "};\n";
5145 unsigned nameSize = Name.size();
5146 // for block or function pointer declaration. Name is already
5147 // part of the declaration.
5148 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5150 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5154 SourceLocation startLoc;
5155 Expr *E = ND->getInit();
5156 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5157 startLoc = ECE->getLParenLoc();
5159 startLoc = E->getLocStart();
5160 startLoc = SM->getExpansionLoc(startLoc);
5161 endBuf = SM->getCharacterData(startLoc);
5162 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
5164 const char separator = lastDecl ? ';' : ',';
5165 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5166 const char *separatorBuf = strchr(startInitializerBuf, separator);
5167 assert((*separatorBuf == separator) &&
5168 "RewriteByRefVar: can't find ';' or ','");
5169 SourceLocation separatorLoc =
5170 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
5172 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
5176 void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5177 // Add initializers for any closure decl refs.
5178 GetBlockDeclRefExprs(Exp->getBody());
5179 if (BlockDeclRefs.size()) {
5180 // Unique all "by copy" declarations.
5181 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5182 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
5183 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5184 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5185 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5188 // Unique all "by ref" declarations.
5189 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5190 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
5191 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5192 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5193 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5196 // Find any imported blocks...they will need special attention.
5197 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5198 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
5199 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5200 BlockDeclRefs[i]->getType()->isBlockPointerType())
5201 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5205 FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5206 IdentifierInfo *ID = &Context->Idents.get(name);
5207 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5208 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5209 SourceLocation(), ID, FType, nullptr, SC_Extern,
5213 Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
5214 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
5215 const BlockDecl *block = Exp->getBlockDecl();
5217 Blocks.push_back(Exp);
5219 CollectBlockDeclRefInfo(Exp);
5221 // Add inner imported variables now used in current block.
5222 int countOfInnerDecls = 0;
5223 if (!InnerBlockDeclRefs.empty()) {
5224 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5225 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
5226 ValueDecl *VD = Exp->getDecl();
5227 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
5228 // We need to save the copied-in variables in nested
5229 // blocks because it is needed at the end for some of the API generations.
5230 // See SynthesizeBlockLiterals routine.
5231 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5232 BlockDeclRefs.push_back(Exp);
5233 BlockByCopyDeclsPtrSet.insert(VD);
5234 BlockByCopyDecls.push_back(VD);
5236 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
5237 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5238 BlockDeclRefs.push_back(Exp);
5239 BlockByRefDeclsPtrSet.insert(VD);
5240 BlockByRefDecls.push_back(VD);
5243 // Find any imported blocks...they will need special attention.
5244 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5245 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
5246 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5247 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5248 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5250 InnerDeclRefsCount.push_back(countOfInnerDecls);
5252 std::string FuncName;
5255 FuncName = CurFunctionDef->getNameAsString();
5256 else if (CurMethodDef)
5257 BuildUniqueMethodName(FuncName, CurMethodDef);
5258 else if (GlobalVarDecl)
5259 FuncName = std::string(GlobalVarDecl->getNameAsString());
5261 bool GlobalBlockExpr =
5262 block->getDeclContext()->getRedeclContext()->isFileContext();
5264 if (GlobalBlockExpr && !GlobalVarDecl) {
5265 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5266 GlobalBlockExpr = false;
5269 std::string BlockNumber = utostr(Blocks.size()-1);
5271 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5273 // Get a pointer to the function type so we can cast appropriately.
5274 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5275 QualType FType = Context->getPointerType(BFT);
5280 // Simulate a constructor call...
5283 if (GlobalBlockExpr)
5287 Tag += FuncName + "_block_impl_" + BlockNumber;
5289 FD = SynthBlockInitFunctionDecl(Tag);
5290 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
5293 SmallVector<Expr*, 4> InitExprs;
5295 // Initialize the block function.
5296 FD = SynthBlockInitFunctionDecl(Func);
5297 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5298 VK_LValue, SourceLocation());
5299 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5301 InitExprs.push_back(castExpr);
5303 // Initialize the block descriptor.
5304 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5306 VarDecl *NewVD = VarDecl::Create(
5307 *Context, TUDecl, SourceLocation(), SourceLocation(),
5308 &Context->Idents.get(DescData), Context->VoidPtrTy, nullptr, SC_Static);
5309 UnaryOperator *DescRefExpr =
5310 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
5315 Context->getPointerType(Context->VoidPtrTy),
5316 VK_RValue, OK_Ordinary,
5318 InitExprs.push_back(DescRefExpr);
5320 // Add initializers for any closure decl refs.
5321 if (BlockDeclRefs.size()) {
5323 // Output all "by copy" declarations.
5324 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
5325 E = BlockByCopyDecls.end(); I != E; ++I) {
5326 if (isObjCType((*I)->getType())) {
5327 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5328 FD = SynthBlockInitFunctionDecl((*I)->getName());
5329 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5330 VK_LValue, SourceLocation());
5331 if (HasLocalVariableExternalStorage(*I)) {
5332 QualType QT = (*I)->getType();
5333 QT = Context->getPointerType(QT);
5334 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5335 OK_Ordinary, SourceLocation());
5337 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5338 FD = SynthBlockInitFunctionDecl((*I)->getName());
5339 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5340 VK_LValue, SourceLocation());
5341 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5344 FD = SynthBlockInitFunctionDecl((*I)->getName());
5345 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5346 VK_LValue, SourceLocation());
5347 if (HasLocalVariableExternalStorage(*I)) {
5348 QualType QT = (*I)->getType();
5349 QT = Context->getPointerType(QT);
5350 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5351 OK_Ordinary, SourceLocation());
5355 InitExprs.push_back(Exp);
5357 // Output all "by ref" declarations.
5358 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
5359 E = BlockByRefDecls.end(); I != E; ++I) {
5360 ValueDecl *ND = (*I);
5361 std::string Name(ND->getNameAsString());
5362 std::string RecName;
5363 RewriteByRefString(RecName, Name, ND, true);
5364 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5365 + sizeof("struct"));
5366 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5367 SourceLocation(), SourceLocation(),
5369 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5370 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5372 FD = SynthBlockInitFunctionDecl((*I)->getName());
5373 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
5375 bool isNestedCapturedVar = false;
5377 for (const auto &CI : block->captures()) {
5378 const VarDecl *variable = CI.getVariable();
5379 if (variable == ND && CI.isNested()) {
5380 assert (CI.isByRef() &&
5381 "SynthBlockInitExpr - captured block variable is not byref");
5382 isNestedCapturedVar = true;
5386 // captured nested byref variable has its address passed. Do not take
5387 // its address again.
5388 if (!isNestedCapturedVar)
5389 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5390 Context->getPointerType(Exp->getType()),
5391 VK_RValue, OK_Ordinary, SourceLocation());
5392 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5393 InitExprs.push_back(Exp);
5396 if (ImportedBlockDecls.size()) {
5397 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5398 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5400 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5401 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5402 Context->IntTy, SourceLocation());
5403 InitExprs.push_back(FlagExp);
5405 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
5406 FType, VK_LValue, SourceLocation());
5408 if (GlobalBlockExpr) {
5409 assert (!GlobalConstructionExp &&
5410 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5411 GlobalConstructionExp = NewRep;
5415 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5416 Context->getPointerType(NewRep->getType()),
5417 VK_RValue, OK_Ordinary, SourceLocation());
5418 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5420 // Put Paren around the call.
5421 NewRep = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
5424 BlockDeclRefs.clear();
5425 BlockByRefDecls.clear();
5426 BlockByRefDeclsPtrSet.clear();
5427 BlockByCopyDecls.clear();
5428 BlockByCopyDeclsPtrSet.clear();
5429 ImportedBlockDecls.clear();
5433 bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5434 if (const ObjCForCollectionStmt * CS =
5435 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5436 return CS->getElement() == DS;
5440 //===----------------------------------------------------------------------===//
5441 // Function Body / Expression rewriting
5442 //===----------------------------------------------------------------------===//
5444 Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5445 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5446 isa<DoStmt>(S) || isa<ForStmt>(S))
5448 else if (isa<ObjCForCollectionStmt>(S)) {
5450 ObjCBcLabelNo.push_back(++BcLabelCount);
5453 // Pseudo-object operations and ivar references need special
5454 // treatment because we're going to recursively rewrite them.
5455 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5456 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5457 return RewritePropertyOrImplicitSetter(PseudoOp);
5459 return RewritePropertyOrImplicitGetter(PseudoOp);
5461 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5462 return RewriteObjCIvarRefExpr(IvarRefExpr);
5464 else if (isa<OpaqueValueExpr>(S))
5465 S = cast<OpaqueValueExpr>(S)->getSourceExpr();
5467 SourceRange OrigStmtRange = S->getSourceRange();
5469 // Perform a bottom up rewrite of all children.
5470 for (Stmt *&childStmt : S->children())
5472 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5474 childStmt = newStmt;
5478 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
5479 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
5480 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5481 InnerContexts.insert(BE->getBlockDecl());
5482 ImportedLocalExternalDecls.clear();
5483 GetInnerBlockDeclRefExprs(BE->getBody(),
5484 InnerBlockDeclRefs, InnerContexts);
5485 // Rewrite the block body in place.
5486 Stmt *SaveCurrentBody = CurrentBody;
5487 CurrentBody = BE->getBody();
5488 PropParentMap = nullptr;
5489 // block literal on rhs of a property-dot-sytax assignment
5490 // must be replaced by its synthesize ast so getRewrittenText
5491 // works as expected. In this case, what actually ends up on RHS
5492 // is the blockTranscribed which is the helper function for the
5493 // block literal; as in: self.c = ^() {[ace ARR];};
5494 bool saveDisableReplaceStmt = DisableReplaceStmt;
5495 DisableReplaceStmt = false;
5496 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5497 DisableReplaceStmt = saveDisableReplaceStmt;
5498 CurrentBody = SaveCurrentBody;
5499 PropParentMap = nullptr;
5500 ImportedLocalExternalDecls.clear();
5501 // Now we snarf the rewritten text and stash it away for later use.
5502 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5503 RewrittenBlockExprs[BE] = Str;
5505 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5507 //blockTranscribed->dump();
5508 ReplaceStmt(S, blockTranscribed);
5509 return blockTranscribed;
5511 // Handle specific things.
5512 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5513 return RewriteAtEncode(AtEncode);
5515 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5516 return RewriteAtSelector(AtSelector);
5518 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5519 return RewriteObjCStringLiteral(AtString);
5521 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5522 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
5524 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5525 return RewriteObjCBoxedExpr(BoxedExpr);
5527 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5528 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
5530 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5531 dyn_cast<ObjCDictionaryLiteral>(S))
5532 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
5534 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5536 // Before we rewrite it, put the original message expression in a comment.
5537 SourceLocation startLoc = MessExpr->getLocStart();
5538 SourceLocation endLoc = MessExpr->getLocEnd();
5540 const char *startBuf = SM->getCharacterData(startLoc);
5541 const char *endBuf = SM->getCharacterData(endLoc);
5543 std::string messString;
5544 messString += "// ";
5545 messString.append(startBuf, endBuf-startBuf+1);
5548 // FIXME: Missing definition of
5549 // InsertText(clang::SourceLocation, char const*, unsigned int).
5550 // InsertText(startLoc, messString);
5551 // Tried this, but it didn't work either...
5552 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5554 return RewriteMessageExpr(MessExpr);
5557 if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
5558 dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5559 return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5562 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5563 return RewriteObjCTryStmt(StmtTry);
5565 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5566 return RewriteObjCSynchronizedStmt(StmtTry);
5568 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5569 return RewriteObjCThrowStmt(StmtThrow);
5571 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5572 return RewriteObjCProtocolExpr(ProtocolExp);
5574 if (ObjCForCollectionStmt *StmtForCollection =
5575 dyn_cast<ObjCForCollectionStmt>(S))
5576 return RewriteObjCForCollectionStmt(StmtForCollection,
5577 OrigStmtRange.getEnd());
5578 if (BreakStmt *StmtBreakStmt =
5579 dyn_cast<BreakStmt>(S))
5580 return RewriteBreakStmt(StmtBreakStmt);
5581 if (ContinueStmt *StmtContinueStmt =
5582 dyn_cast<ContinueStmt>(S))
5583 return RewriteContinueStmt(StmtContinueStmt);
5585 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5587 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5588 // FIXME: What we're doing here is modifying the type-specifier that
5589 // precedes the first Decl. In the future the DeclGroup should have
5590 // a separate type-specifier that we can rewrite.
5591 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5592 // the context of an ObjCForCollectionStmt. For example:
5593 // NSArray *someArray;
5594 // for (id <FooProtocol> index in someArray) ;
5595 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5596 // and it depends on the original text locations/positions.
5597 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5598 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5600 // Blocks rewrite rules.
5601 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5604 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5605 if (isTopLevelBlockPointerType(ND->getType()))
5606 RewriteBlockPointerDecl(ND);
5607 else if (ND->getType()->isFunctionPointerType())
5608 CheckFunctionPointerDecl(ND->getType(), ND);
5609 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5610 if (VD->hasAttr<BlocksAttr>()) {
5611 static unsigned uniqueByrefDeclCount = 0;
5612 assert(!BlockByRefDeclNo.count(ND) &&
5613 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5614 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
5615 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
5618 RewriteTypeOfDecl(VD);
5621 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5622 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5623 RewriteBlockPointerDecl(TD);
5624 else if (TD->getUnderlyingType()->isFunctionPointerType())
5625 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5630 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5631 RewriteObjCQualifiedInterfaceTypes(CE);
5633 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5634 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5635 assert(!Stmts.empty() && "Statement stack is empty");
5636 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5637 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5638 && "Statement stack mismatch");
5641 // Handle blocks rewriting.
5642 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5643 ValueDecl *VD = DRE->getDecl();
5644 if (VD->hasAttr<BlocksAttr>())
5645 return RewriteBlockDeclRefExpr(DRE);
5646 if (HasLocalVariableExternalStorage(VD))
5647 return RewriteLocalVariableExternalStorage(DRE);
5650 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5651 if (CE->getCallee()->getType()->isBlockPointerType()) {
5652 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5653 ReplaceStmt(S, BlockCall);
5657 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5658 RewriteCastExpr(CE);
5660 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5661 RewriteImplicitCastObjCExpr(ICE);
5665 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5666 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5669 // Get the new text.
5671 llvm::raw_string_ostream Buf(SStr);
5672 Replacement->printPretty(Buf);
5673 const std::string &Str = Buf.str();
5675 printf("CAST = %s\n", &Str[0]);
5676 InsertText(ICE->getSubExpr()->getLocStart(), Str);
5681 // Return this stmt unmodified.
5685 void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5686 for (auto *FD : RD->fields()) {
5687 if (isTopLevelBlockPointerType(FD->getType()))
5688 RewriteBlockPointerDecl(FD);
5689 if (FD->getType()->isObjCQualifiedIdType() ||
5690 FD->getType()->isObjCQualifiedInterfaceType())
5691 RewriteObjCQualifiedInterfaceTypes(FD);
5695 /// HandleDeclInMainFile - This is called for each top-level decl defined in the
5696 /// main file of the input.
5697 void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5698 switch (D->getKind()) {
5699 case Decl::Function: {
5700 FunctionDecl *FD = cast<FunctionDecl>(D);
5701 if (FD->isOverloadedOperator())
5704 // Since function prototypes don't have ParmDecl's, we check the function
5705 // prototype. This enables us to rewrite function declarations and
5706 // definitions using the same code.
5707 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5709 if (!FD->isThisDeclarationADefinition())
5712 // FIXME: If this should support Obj-C++, support CXXTryStmt
5713 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5714 CurFunctionDef = FD;
5717 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5719 CurrentBody = nullptr;
5720 if (PropParentMap) {
5721 delete PropParentMap;
5722 PropParentMap = nullptr;
5724 // This synthesizes and inserts the block "impl" struct, invoke function,
5725 // and any copy/dispose helper functions.
5726 InsertBlockLiteralsWithinFunction(FD);
5727 RewriteLineDirective(D);
5728 CurFunctionDef = nullptr;
5732 case Decl::ObjCMethod: {
5733 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5734 if (CompoundStmt *Body = MD->getCompoundBody()) {
5738 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5740 CurrentBody = nullptr;
5741 if (PropParentMap) {
5742 delete PropParentMap;
5743 PropParentMap = nullptr;
5745 InsertBlockLiteralsWithinMethod(MD);
5746 RewriteLineDirective(D);
5747 CurMethodDef = nullptr;
5751 case Decl::ObjCImplementation: {
5752 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5753 ClassImplementation.push_back(CI);
5756 case Decl::ObjCCategoryImpl: {
5757 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5758 CategoryImplementation.push_back(CI);
5762 VarDecl *VD = cast<VarDecl>(D);
5763 RewriteObjCQualifiedInterfaceTypes(VD);
5764 if (isTopLevelBlockPointerType(VD->getType()))
5765 RewriteBlockPointerDecl(VD);
5766 else if (VD->getType()->isFunctionPointerType()) {
5767 CheckFunctionPointerDecl(VD->getType(), VD);
5768 if (VD->getInit()) {
5769 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5770 RewriteCastExpr(CE);
5773 } else if (VD->getType()->isRecordType()) {
5774 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5775 if (RD->isCompleteDefinition())
5776 RewriteRecordBody(RD);
5778 if (VD->getInit()) {
5780 CurrentBody = VD->getInit();
5781 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5782 CurrentBody = nullptr;
5783 if (PropParentMap) {
5784 delete PropParentMap;
5785 PropParentMap = nullptr;
5787 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5788 GlobalVarDecl = nullptr;
5790 // This is needed for blocks.
5791 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5792 RewriteCastExpr(CE);
5797 case Decl::TypeAlias:
5798 case Decl::Typedef: {
5799 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5800 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5801 RewriteBlockPointerDecl(TD);
5802 else if (TD->getUnderlyingType()->isFunctionPointerType())
5803 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5805 RewriteObjCQualifiedInterfaceTypes(TD);
5809 case Decl::CXXRecord:
5810 case Decl::Record: {
5811 RecordDecl *RD = cast<RecordDecl>(D);
5812 if (RD->isCompleteDefinition())
5813 RewriteRecordBody(RD);
5822 /// Write_ProtocolExprReferencedMetadata - This routine writer out the
5823 /// protocol reference symbols in the for of:
5824 /// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5825 static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5826 ObjCProtocolDecl *PDecl,
5827 std::string &Result) {
5828 // Also output .objc_protorefs$B section and its meta-data.
5829 if (Context->getLangOpts().MicrosoftExt)
5830 Result += "static ";
5831 Result += "struct _protocol_t *";
5832 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5833 Result += PDecl->getNameAsString();
5835 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5839 void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5840 if (Diags.hasErrorOccurred())
5845 for (unsigned i = 0, e = FunctionDefinitionsSeen.size(); i < e; i++) {
5846 // translation of function bodies were postponed until all class and
5847 // their extensions and implementations are seen. This is because, we
5848 // cannot build grouping structs for bitfields until they are all seen.
5849 FunctionDecl *FDecl = FunctionDefinitionsSeen[i];
5850 HandleTopLevelSingleDecl(FDecl);
5853 // Here's a great place to add any extra declarations that may be needed.
5854 // Write out meta data for each @protocol(<expr>).
5855 for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls) {
5856 RewriteObjCProtocolMetaData(ProtDecl, Preamble);
5857 Write_ProtocolExprReferencedMetadata(Context, ProtDecl, Preamble);
5860 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
5862 if (ClassImplementation.size() || CategoryImplementation.size())
5863 RewriteImplementations();
5865 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5866 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5867 // Write struct declaration for the class matching its ivar declarations.
5868 // Note that for modern abi, this is postponed until the end of TU
5869 // because class extensions and the implementation might declare their own
5871 RewriteInterfaceDecl(CDecl);
5874 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5876 if (const RewriteBuffer *RewriteBuf =
5877 Rewrite.getRewriteBufferFor(MainFileID)) {
5878 //printf("Changed:\n");
5879 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5881 llvm::errs() << "No changes\n";
5884 if (ClassImplementation.size() || CategoryImplementation.size() ||
5885 ProtocolExprDecls.size()) {
5886 // Rewrite Objective-c meta data*
5887 std::string ResultStr;
5888 RewriteMetaDataIntoBuffer(ResultStr);
5890 *OutFile << ResultStr;
5894 std::string ResultStr;
5895 WriteImageInfo(ResultStr);
5896 *OutFile << ResultStr;
5901 void RewriteModernObjC::Initialize(ASTContext &context) {
5902 InitializeCommon(context);
5904 Preamble += "#ifndef __OBJC2__\n";
5905 Preamble += "#define __OBJC2__\n";
5906 Preamble += "#endif\n";
5908 // declaring objc_selector outside the parameter list removes a silly
5909 // scope related warning...
5911 Preamble = "#pragma once\n";
5912 Preamble += "struct objc_selector; struct objc_class;\n";
5913 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
5914 Preamble += "\n\tstruct objc_object *superClass; ";
5915 // Add a constructor for creating temporary objects.
5916 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
5917 Preamble += ": object(o), superClass(s) {} ";
5918 Preamble += "\n};\n";
5920 if (LangOpts.MicrosoftExt) {
5921 // Define all sections using syntax that makes sense.
5922 // These are currently generated.
5923 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
5924 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
5925 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
5926 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5927 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
5928 // These are generated but not necessary for functionality.
5929 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
5930 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5931 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
5932 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
5934 // These need be generated for performance. Currently they are not,
5935 // using API calls instead.
5936 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5937 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5938 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5941 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5942 Preamble += "typedef struct objc_object Protocol;\n";
5943 Preamble += "#define _REWRITER_typedef_Protocol\n";
5944 Preamble += "#endif\n";
5945 if (LangOpts.MicrosoftExt) {
5946 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5947 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
5950 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
5952 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
5953 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
5954 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
5955 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
5956 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
5958 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
5959 Preamble += "(const char *);\n";
5960 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5961 Preamble += "(struct objc_class *);\n";
5962 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
5963 Preamble += "(const char *);\n";
5964 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
5965 // @synchronized hooks.
5966 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
5967 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
5968 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5969 Preamble += "#ifdef _WIN64\n";
5970 Preamble += "typedef unsigned long long _WIN_NSUInteger;\n";
5971 Preamble += "#else\n";
5972 Preamble += "typedef unsigned int _WIN_NSUInteger;\n";
5973 Preamble += "#endif\n";
5974 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5975 Preamble += "struct __objcFastEnumerationState {\n\t";
5976 Preamble += "unsigned long state;\n\t";
5977 Preamble += "void **itemsPtr;\n\t";
5978 Preamble += "unsigned long *mutationsPtr;\n\t";
5979 Preamble += "unsigned long extra[5];\n};\n";
5980 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5981 Preamble += "#define __FASTENUMERATIONSTATE\n";
5982 Preamble += "#endif\n";
5983 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5984 Preamble += "struct __NSConstantStringImpl {\n";
5985 Preamble += " int *isa;\n";
5986 Preamble += " int flags;\n";
5987 Preamble += " char *str;\n";
5988 Preamble += "#if _WIN64\n";
5989 Preamble += " long long length;\n";
5990 Preamble += "#else\n";
5991 Preamble += " long length;\n";
5992 Preamble += "#endif\n";
5994 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5995 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5996 Preamble += "#else\n";
5997 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5998 Preamble += "#endif\n";
5999 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
6000 Preamble += "#endif\n";
6002 Preamble += "#ifndef BLOCK_IMPL\n";
6003 Preamble += "#define BLOCK_IMPL\n";
6004 Preamble += "struct __block_impl {\n";
6005 Preamble += " void *isa;\n";
6006 Preamble += " int Flags;\n";
6007 Preamble += " int Reserved;\n";
6008 Preamble += " void *FuncPtr;\n";
6010 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
6011 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
6012 Preamble += "extern \"C\" __declspec(dllexport) "
6013 "void _Block_object_assign(void *, const void *, const int);\n";
6014 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
6015 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
6016 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
6017 Preamble += "#else\n";
6018 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
6019 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
6020 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
6021 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
6022 Preamble += "#endif\n";
6023 Preamble += "#endif\n";
6024 if (LangOpts.MicrosoftExt) {
6025 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
6026 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
6027 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
6028 Preamble += "#define __attribute__(X)\n";
6029 Preamble += "#endif\n";
6030 Preamble += "#ifndef __weak\n";
6031 Preamble += "#define __weak\n";
6032 Preamble += "#endif\n";
6033 Preamble += "#ifndef __block\n";
6034 Preamble += "#define __block\n";
6035 Preamble += "#endif\n";
6038 Preamble += "#define __block\n";
6039 Preamble += "#define __weak\n";
6042 // Declarations required for modern objective-c array and dictionary literals.
6043 Preamble += "\n#include <stdarg.h>\n";
6044 Preamble += "struct __NSContainer_literal {\n";
6045 Preamble += " void * *arr;\n";
6046 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
6047 Preamble += "\tva_list marker;\n";
6048 Preamble += "\tva_start(marker, count);\n";
6049 Preamble += "\tarr = new void *[count];\n";
6050 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
6051 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
6052 Preamble += "\tva_end( marker );\n";
6053 Preamble += " };\n";
6054 Preamble += " ~__NSContainer_literal() {\n";
6055 Preamble += "\tdelete[] arr;\n";
6059 // Declaration required for implementation of @autoreleasepool statement.
6060 Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
6061 Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
6062 Preamble += "struct __AtAutoreleasePool {\n";
6063 Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
6064 Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
6065 Preamble += " void * atautoreleasepoolobj;\n";
6068 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
6069 // as this avoids warning in any 64bit/32bit compilation model.
6070 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6073 /// RewriteIvarOffsetComputation - This routine synthesizes computation of
6075 void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
6076 std::string &Result) {
6077 Result += "__OFFSETOFIVAR__(struct ";
6078 Result += ivar->getContainingInterface()->getNameAsString();
6079 if (LangOpts.MicrosoftExt)
6082 if (ivar->isBitField())
6083 ObjCIvarBitfieldGroupDecl(ivar, Result);
6085 Result += ivar->getNameAsString();
6089 /// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6090 /// struct _prop_t {
6091 /// const char *name;
6092 /// char *attributes;
6095 /// struct _prop_list_t {
6096 /// uint32_t entsize; // sizeof(struct _prop_t)
6097 /// uint32_t count_of_properties;
6098 /// struct _prop_t prop_list[count_of_properties];
6101 /// struct _protocol_t;
6103 /// struct _protocol_list_t {
6104 /// long protocol_count; // Note, this is 32/64 bit
6105 /// struct _protocol_t * protocol_list[protocol_count];
6108 /// struct _objc_method {
6110 /// const char *method_type;
6114 /// struct _method_list_t {
6115 /// uint32_t entsize; // sizeof(struct _objc_method)
6116 /// uint32_t method_count;
6117 /// struct _objc_method method_list[method_count];
6120 /// struct _protocol_t {
6122 /// const char *protocol_name;
6123 /// const struct _protocol_list_t * protocol_list; // super protocols
6124 /// const struct method_list_t *instance_methods;
6125 /// const struct method_list_t *class_methods;
6126 /// const struct method_list_t *optionalInstanceMethods;
6127 /// const struct method_list_t *optionalClassMethods;
6128 /// const struct _prop_list_t * properties;
6129 /// const uint32_t size; // sizeof(struct _protocol_t)
6130 /// const uint32_t flags; // = 0
6131 /// const char ** extendedMethodTypes;
6134 /// struct _ivar_t {
6135 /// unsigned long int *offset; // pointer to ivar offset location
6136 /// const char *name;
6137 /// const char *type;
6138 /// uint32_t alignment;
6142 /// struct _ivar_list_t {
6143 /// uint32 entsize; // sizeof(struct _ivar_t)
6145 /// struct _ivar_t list[count];
6148 /// struct _class_ro_t {
6150 /// uint32_t instanceStart;
6151 /// uint32_t instanceSize;
6152 /// uint32_t reserved; // only when building for 64bit targets
6153 /// const uint8_t *ivarLayout;
6154 /// const char *name;
6155 /// const struct _method_list_t *baseMethods;
6156 /// const struct _protocol_list_t *baseProtocols;
6157 /// const struct _ivar_list_t *ivars;
6158 /// const uint8_t *weakIvarLayout;
6159 /// const struct _prop_list_t *properties;
6162 /// struct _class_t {
6163 /// struct _class_t *isa;
6164 /// struct _class_t *superclass;
6167 /// struct _class_ro_t *ro;
6170 /// struct _category_t {
6171 /// const char *name;
6172 /// struct _class_t *cls;
6173 /// const struct _method_list_t *instance_methods;
6174 /// const struct _method_list_t *class_methods;
6175 /// const struct _protocol_list_t *protocols;
6176 /// const struct _prop_list_t *properties;
6179 /// MessageRefTy - LLVM for:
6180 /// struct _message_ref_t {
6185 /// SuperMessageRefTy - LLVM for:
6186 /// struct _super_message_ref_t {
6187 /// SUPER_IMP messenger;
6191 static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
6192 static bool meta_data_declared = false;
6193 if (meta_data_declared)
6196 Result += "\nstruct _prop_t {\n";
6197 Result += "\tconst char *name;\n";
6198 Result += "\tconst char *attributes;\n";
6201 Result += "\nstruct _protocol_t;\n";
6203 Result += "\nstruct _objc_method {\n";
6204 Result += "\tstruct objc_selector * _cmd;\n";
6205 Result += "\tconst char *method_type;\n";
6206 Result += "\tvoid *_imp;\n";
6209 Result += "\nstruct _protocol_t {\n";
6210 Result += "\tvoid * isa; // NULL\n";
6211 Result += "\tconst char *protocol_name;\n";
6212 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
6213 Result += "\tconst struct method_list_t *instance_methods;\n";
6214 Result += "\tconst struct method_list_t *class_methods;\n";
6215 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6216 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6217 Result += "\tconst struct _prop_list_t * properties;\n";
6218 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
6219 Result += "\tconst unsigned int flags; // = 0\n";
6220 Result += "\tconst char ** extendedMethodTypes;\n";
6223 Result += "\nstruct _ivar_t {\n";
6224 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
6225 Result += "\tconst char *name;\n";
6226 Result += "\tconst char *type;\n";
6227 Result += "\tunsigned int alignment;\n";
6228 Result += "\tunsigned int size;\n";
6231 Result += "\nstruct _class_ro_t {\n";
6232 Result += "\tunsigned int flags;\n";
6233 Result += "\tunsigned int instanceStart;\n";
6234 Result += "\tunsigned int instanceSize;\n";
6235 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6236 if (Triple.getArch() == llvm::Triple::x86_64)
6237 Result += "\tunsigned int reserved;\n";
6238 Result += "\tconst unsigned char *ivarLayout;\n";
6239 Result += "\tconst char *name;\n";
6240 Result += "\tconst struct _method_list_t *baseMethods;\n";
6241 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6242 Result += "\tconst struct _ivar_list_t *ivars;\n";
6243 Result += "\tconst unsigned char *weakIvarLayout;\n";
6244 Result += "\tconst struct _prop_list_t *properties;\n";
6247 Result += "\nstruct _class_t {\n";
6248 Result += "\tstruct _class_t *isa;\n";
6249 Result += "\tstruct _class_t *superclass;\n";
6250 Result += "\tvoid *cache;\n";
6251 Result += "\tvoid *vtable;\n";
6252 Result += "\tstruct _class_ro_t *ro;\n";
6255 Result += "\nstruct _category_t {\n";
6256 Result += "\tconst char *name;\n";
6257 Result += "\tstruct _class_t *cls;\n";
6258 Result += "\tconst struct _method_list_t *instance_methods;\n";
6259 Result += "\tconst struct _method_list_t *class_methods;\n";
6260 Result += "\tconst struct _protocol_list_t *protocols;\n";
6261 Result += "\tconst struct _prop_list_t *properties;\n";
6264 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
6265 Result += "#pragma warning(disable:4273)\n";
6266 meta_data_declared = true;
6269 static void Write_protocol_list_t_TypeDecl(std::string &Result,
6270 long super_protocol_count) {
6271 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6272 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6273 Result += "\tstruct _protocol_t *super_protocols[";
6274 Result += utostr(super_protocol_count); Result += "];\n";
6278 static void Write_method_list_t_TypeDecl(std::string &Result,
6279 unsigned int method_count) {
6280 Result += "struct /*_method_list_t*/"; Result += " {\n";
6281 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6282 Result += "\tunsigned int method_count;\n";
6283 Result += "\tstruct _objc_method method_list[";
6284 Result += utostr(method_count); Result += "];\n";
6288 static void Write__prop_list_t_TypeDecl(std::string &Result,
6289 unsigned int property_count) {
6290 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6291 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6292 Result += "\tunsigned int count_of_properties;\n";
6293 Result += "\tstruct _prop_t prop_list[";
6294 Result += utostr(property_count); Result += "];\n";
6298 static void Write__ivar_list_t_TypeDecl(std::string &Result,
6299 unsigned int ivar_count) {
6300 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6301 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6302 Result += "\tunsigned int count;\n";
6303 Result += "\tstruct _ivar_t ivar_list[";
6304 Result += utostr(ivar_count); Result += "];\n";
6308 static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6309 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6311 StringRef ProtocolName) {
6312 if (SuperProtocols.size() > 0) {
6313 Result += "\nstatic ";
6314 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6315 Result += " "; Result += VarName;
6316 Result += ProtocolName;
6317 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6318 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6319 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6320 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6321 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6322 Result += SuperPD->getNameAsString();
6331 static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6332 ASTContext *Context, std::string &Result,
6333 ArrayRef<ObjCMethodDecl *> Methods,
6335 StringRef TopLevelDeclName,
6337 if (Methods.size() > 0) {
6338 Result += "\nstatic ";
6339 Write_method_list_t_TypeDecl(Result, Methods.size());
6340 Result += " "; Result += VarName;
6341 Result += TopLevelDeclName;
6342 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6343 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6344 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6345 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6346 ObjCMethodDecl *MD = Methods[i];
6348 Result += "\t{{(struct objc_selector *)\"";
6350 Result += "\t{(struct objc_selector *)\"";
6351 Result += (MD)->getSelector().getAsString(); Result += "\"";
6353 std::string MethodTypeString = Context->getObjCEncodingForMethodDecl(MD);
6354 Result += "\""; Result += MethodTypeString; Result += "\"";
6359 Result += "(void *)";
6360 Result += RewriteObj.MethodInternalNames[MD];
6371 static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
6372 ASTContext *Context, std::string &Result,
6373 ArrayRef<ObjCPropertyDecl *> Properties,
6374 const Decl *Container,
6376 StringRef ProtocolName) {
6377 if (Properties.size() > 0) {
6378 Result += "\nstatic ";
6379 Write__prop_list_t_TypeDecl(Result, Properties.size());
6380 Result += " "; Result += VarName;
6381 Result += ProtocolName;
6382 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6383 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6384 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6385 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6386 ObjCPropertyDecl *PropDecl = Properties[i];
6391 Result += PropDecl->getName(); Result += "\",";
6392 std::string PropertyTypeString =
6393 Context->getObjCEncodingForPropertyDecl(PropDecl, Container);
6394 std::string QuotePropertyTypeString;
6395 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6396 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6407 enum MetaDataDlags {
6411 OBJC2_CLS_HIDDEN = 0x10,
6412 CLS_EXCEPTION = 0x20,
6414 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6415 CLS_HAS_IVAR_RELEASER = 0x40,
6416 /// class was compiled with -fobjc-arr
6417 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6420 static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6422 const std::string &InstanceStart,
6423 const std::string &InstanceSize,
6424 ArrayRef<ObjCMethodDecl *>baseMethods,
6425 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6426 ArrayRef<ObjCIvarDecl *>ivars,
6427 ArrayRef<ObjCPropertyDecl *>Properties,
6429 StringRef ClassName) {
6430 Result += "\nstatic struct _class_ro_t ";
6431 Result += VarName; Result += ClassName;
6432 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6434 Result += llvm::utostr(flags); Result += ", ";
6435 Result += InstanceStart; Result += ", ";
6436 Result += InstanceSize; Result += ", \n";
6438 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6439 if (Triple.getArch() == llvm::Triple::x86_64)
6440 // uint32_t const reserved; // only when building for 64bit targets
6441 Result += "(unsigned int)0, \n\t";
6442 // const uint8_t * const ivarLayout;
6443 Result += "0, \n\t";
6444 Result += "\""; Result += ClassName; Result += "\",\n\t";
6445 bool metaclass = ((flags & CLS_META) != 0);
6446 if (baseMethods.size() > 0) {
6447 Result += "(const struct _method_list_t *)&";
6449 Result += "_OBJC_$_CLASS_METHODS_";
6451 Result += "_OBJC_$_INSTANCE_METHODS_";
6452 Result += ClassName;
6456 Result += "0, \n\t";
6458 if (!metaclass && baseProtocols.size() > 0) {
6459 Result += "(const struct _objc_protocol_list *)&";
6460 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6464 Result += "0, \n\t";
6466 if (!metaclass && ivars.size() > 0) {
6467 Result += "(const struct _ivar_list_t *)&";
6468 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6472 Result += "0, \n\t";
6475 Result += "0, \n\t";
6476 if (!metaclass && Properties.size() > 0) {
6477 Result += "(const struct _prop_list_t *)&";
6478 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
6487 static void Write_class_t(ASTContext *Context, std::string &Result,
6489 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6490 bool rootClass = (!CDecl->getSuperClass());
6491 const ObjCInterfaceDecl *RootClass = CDecl;
6494 // Find the Root class
6495 RootClass = CDecl->getSuperClass();
6496 while (RootClass->getSuperClass()) {
6497 RootClass = RootClass->getSuperClass();
6501 if (metaclass && rootClass) {
6502 // Need to handle a case of use of forward declaration.
6504 Result += "extern \"C\" ";
6505 if (CDecl->getImplementation())
6506 Result += "__declspec(dllexport) ";
6508 Result += "__declspec(dllimport) ";
6510 Result += "struct _class_t OBJC_CLASS_$_";
6511 Result += CDecl->getNameAsString();
6514 // Also, for possibility of 'super' metadata class not having been defined yet.
6516 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
6518 Result += "extern \"C\" ";
6519 if (SuperClass->getImplementation())
6520 Result += "__declspec(dllexport) ";
6522 Result += "__declspec(dllimport) ";
6524 Result += "struct _class_t ";
6526 Result += SuperClass->getNameAsString();
6529 if (metaclass && RootClass != SuperClass) {
6530 Result += "extern \"C\" ";
6531 if (RootClass->getImplementation())
6532 Result += "__declspec(dllexport) ";
6534 Result += "__declspec(dllimport) ";
6536 Result += "struct _class_t ";
6538 Result += RootClass->getNameAsString();
6543 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6544 Result += VarName; Result += CDecl->getNameAsString();
6545 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6549 Result += "0, // &"; Result += VarName;
6550 Result += RootClass->getNameAsString();
6552 Result += "0, // &"; Result += VarName;
6553 Result += CDecl->getSuperClass()->getNameAsString();
6557 Result += "0, // &"; Result += VarName;
6558 Result += CDecl->getNameAsString();
6560 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6565 Result += "0, // &OBJC_METACLASS_$_";
6566 Result += CDecl->getNameAsString();
6569 Result += "0, // &"; Result += VarName;
6570 Result += CDecl->getSuperClass()->getNameAsString();
6576 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6577 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6579 Result += "&_OBJC_METACLASS_RO_$_";
6581 Result += "&_OBJC_CLASS_RO_$_";
6582 Result += CDecl->getNameAsString();
6583 Result += ",\n};\n";
6585 // Add static function to initialize some of the meta-data fields.
6586 // avoid doing it twice.
6590 const ObjCInterfaceDecl *SuperClass =
6591 rootClass ? CDecl : CDecl->getSuperClass();
6593 Result += "static void OBJC_CLASS_SETUP_$_";
6594 Result += CDecl->getNameAsString();
6595 Result += "(void ) {\n";
6596 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6597 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6598 Result += RootClass->getNameAsString(); Result += ";\n";
6600 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6601 Result += ".superclass = ";
6603 Result += "&OBJC_CLASS_$_";
6605 Result += "&OBJC_METACLASS_$_";
6607 Result += SuperClass->getNameAsString(); Result += ";\n";
6609 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6610 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6612 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6613 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6614 Result += CDecl->getNameAsString(); Result += ";\n";
6617 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6618 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6619 Result += SuperClass->getNameAsString(); Result += ";\n";
6622 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6623 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6627 static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6628 std::string &Result,
6629 ObjCCategoryDecl *CatDecl,
6630 ObjCInterfaceDecl *ClassDecl,
6631 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6632 ArrayRef<ObjCMethodDecl *> ClassMethods,
6633 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6634 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
6635 StringRef CatName = CatDecl->getName();
6636 StringRef ClassName = ClassDecl->getName();
6637 // must declare an extern class object in case this class is not implemented
6640 Result += "extern \"C\" ";
6641 if (ClassDecl->getImplementation())
6642 Result += "__declspec(dllexport) ";
6644 Result += "__declspec(dllimport) ";
6646 Result += "struct _class_t ";
6647 Result += "OBJC_CLASS_$_"; Result += ClassName;
6650 Result += "\nstatic struct _category_t ";
6651 Result += "_OBJC_$_CATEGORY_";
6652 Result += ClassName; Result += "_$_"; Result += CatName;
6653 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6655 Result += "\t\""; Result += ClassName; Result += "\",\n";
6656 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
6658 if (InstanceMethods.size() > 0) {
6659 Result += "\t(const struct _method_list_t *)&";
6660 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6661 Result += ClassName; Result += "_$_"; Result += CatName;
6667 if (ClassMethods.size() > 0) {
6668 Result += "\t(const struct _method_list_t *)&";
6669 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6670 Result += ClassName; Result += "_$_"; Result += CatName;
6676 if (RefedProtocols.size() > 0) {
6677 Result += "\t(const struct _protocol_list_t *)&";
6678 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6679 Result += ClassName; Result += "_$_"; Result += CatName;
6685 if (ClassProperties.size() > 0) {
6686 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6687 Result += ClassName; Result += "_$_"; Result += CatName;
6695 // Add static function to initialize the class pointer in the category structure.
6696 Result += "static void OBJC_CATEGORY_SETUP_$_";
6697 Result += ClassDecl->getNameAsString();
6700 Result += "(void ) {\n";
6701 Result += "\t_OBJC_$_CATEGORY_";
6702 Result += ClassDecl->getNameAsString();
6705 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6709 static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6710 ASTContext *Context, std::string &Result,
6711 ArrayRef<ObjCMethodDecl *> Methods,
6713 StringRef ProtocolName) {
6714 if (Methods.size() == 0)
6717 Result += "\nstatic const char *";
6718 Result += VarName; Result += ProtocolName;
6719 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6721 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6722 ObjCMethodDecl *MD = Methods[i];
6723 std::string MethodTypeString =
6724 Context->getObjCEncodingForMethodDecl(MD, true);
6725 std::string QuoteMethodTypeString;
6726 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6727 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6736 static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6737 ASTContext *Context,
6738 std::string &Result,
6739 ArrayRef<ObjCIvarDecl *> Ivars,
6740 ObjCInterfaceDecl *CDecl) {
6741 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6742 // this is what happens:
6744 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6745 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6746 Class->getVisibility() == HiddenVisibility)
6747 Visibility shoud be: HiddenVisibility;
6749 Visibility shoud be: DefaultVisibility;
6753 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6754 ObjCIvarDecl *IvarDecl = Ivars[i];
6755 if (Context->getLangOpts().MicrosoftExt)
6756 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6758 if (!Context->getLangOpts().MicrosoftExt ||
6759 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
6760 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
6761 Result += "extern \"C\" unsigned long int ";
6763 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
6764 if (Ivars[i]->isBitField())
6765 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6767 WriteInternalIvarName(CDecl, IvarDecl, Result);
6768 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6770 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6772 if (Ivars[i]->isBitField()) {
6773 // skip over rest of the ivar bitfields.
6774 SKIP_BITFIELDS(i , e, Ivars);
6779 static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6780 ASTContext *Context, std::string &Result,
6781 ArrayRef<ObjCIvarDecl *> OriginalIvars,
6783 ObjCInterfaceDecl *CDecl) {
6784 if (OriginalIvars.size() > 0) {
6785 Write_IvarOffsetVar(RewriteObj, Context, Result, OriginalIvars, CDecl);
6786 SmallVector<ObjCIvarDecl *, 8> Ivars;
6787 // strip off all but the first ivar bitfield from each group of ivars.
6788 // Such ivars in the ivar list table will be replaced by their grouping struct
6790 for (unsigned i = 0, e = OriginalIvars.size(); i < e; i++) {
6791 if (OriginalIvars[i]->isBitField()) {
6792 Ivars.push_back(OriginalIvars[i]);
6793 // skip over rest of the ivar bitfields.
6794 SKIP_BITFIELDS(i , e, OriginalIvars);
6797 Ivars.push_back(OriginalIvars[i]);
6800 Result += "\nstatic ";
6801 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6802 Result += " "; Result += VarName;
6803 Result += CDecl->getNameAsString();
6804 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6805 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6806 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6807 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6808 ObjCIvarDecl *IvarDecl = Ivars[i];
6813 Result += "(unsigned long int *)&";
6814 if (Ivars[i]->isBitField())
6815 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6817 WriteInternalIvarName(CDecl, IvarDecl, Result);
6821 if (Ivars[i]->isBitField())
6822 RewriteObj.ObjCIvarBitfieldGroupDecl(Ivars[i], Result);
6824 Result += IvarDecl->getName();
6827 QualType IVQT = IvarDecl->getType();
6828 if (IvarDecl->isBitField())
6829 IVQT = RewriteObj.GetGroupRecordTypeForObjCIvarBitfield(IvarDecl);
6831 std::string IvarTypeString, QuoteIvarTypeString;
6832 Context->getObjCEncodingForType(IVQT, IvarTypeString,
6834 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6835 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6837 // FIXME. this alignment represents the host alignment and need be changed to
6838 // represent the target alignment.
6839 unsigned Align = Context->getTypeAlign(IVQT)/8;
6840 Align = llvm::Log2_32(Align);
6841 Result += llvm::utostr(Align); Result += ", ";
6842 CharUnits Size = Context->getTypeSizeInChars(IVQT);
6843 Result += llvm::utostr(Size.getQuantity());
6853 /// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
6854 void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
6855 std::string &Result) {
6857 // Do not synthesize the protocol more than once.
6858 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6860 WriteModernMetadataDeclarations(Context, Result);
6862 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6864 // Must write out all protocol definitions in current qualifier list,
6865 // and in their nested qualifiers before writing out current definition.
6866 for (auto *I : PDecl->protocols())
6867 RewriteObjCProtocolMetaData(I, Result);
6869 // Construct method lists.
6870 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6871 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
6872 for (auto *MD : PDecl->instance_methods()) {
6873 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6874 OptInstanceMethods.push_back(MD);
6876 InstanceMethods.push_back(MD);
6880 for (auto *MD : PDecl->class_methods()) {
6881 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6882 OptClassMethods.push_back(MD);
6884 ClassMethods.push_back(MD);
6887 std::vector<ObjCMethodDecl *> AllMethods;
6888 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6889 AllMethods.push_back(InstanceMethods[i]);
6890 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6891 AllMethods.push_back(ClassMethods[i]);
6892 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6893 AllMethods.push_back(OptInstanceMethods[i]);
6894 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6895 AllMethods.push_back(OptClassMethods[i]);
6897 Write__extendedMethodTypes_initializer(*this, Context, Result,
6899 "_OBJC_PROTOCOL_METHOD_TYPES_",
6900 PDecl->getNameAsString());
6901 // Protocol's super protocol list
6902 SmallVector<ObjCProtocolDecl *, 8> SuperProtocols(PDecl->protocols());
6903 Write_protocol_list_initializer(Context, Result, SuperProtocols,
6904 "_OBJC_PROTOCOL_REFS_",
6905 PDecl->getNameAsString());
6907 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6908 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
6909 PDecl->getNameAsString(), false);
6911 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6912 "_OBJC_PROTOCOL_CLASS_METHODS_",
6913 PDecl->getNameAsString(), false);
6915 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
6916 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
6917 PDecl->getNameAsString(), false);
6919 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
6920 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
6921 PDecl->getNameAsString(), false);
6923 // Protocol's property metadata.
6924 SmallVector<ObjCPropertyDecl *, 8> ProtocolProperties(
6925 PDecl->instance_properties());
6926 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
6927 /* Container */nullptr,
6928 "_OBJC_PROTOCOL_PROPERTIES_",
6929 PDecl->getNameAsString());
6931 // Writer out root metadata for current protocol: struct _protocol_t
6933 if (LangOpts.MicrosoftExt)
6934 Result += "static ";
6935 Result += "struct _protocol_t _OBJC_PROTOCOL_";
6936 Result += PDecl->getNameAsString();
6937 Result += " __attribute__ ((used)) = {\n";
6938 Result += "\t0,\n"; // id is; is null
6939 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
6940 if (SuperProtocols.size() > 0) {
6941 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6942 Result += PDecl->getNameAsString(); Result += ",\n";
6946 if (InstanceMethods.size() > 0) {
6947 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
6948 Result += PDecl->getNameAsString(); Result += ",\n";
6953 if (ClassMethods.size() > 0) {
6954 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
6955 Result += PDecl->getNameAsString(); Result += ",\n";
6960 if (OptInstanceMethods.size() > 0) {
6961 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
6962 Result += PDecl->getNameAsString(); Result += ",\n";
6967 if (OptClassMethods.size() > 0) {
6968 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
6969 Result += PDecl->getNameAsString(); Result += ",\n";
6974 if (ProtocolProperties.size() > 0) {
6975 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
6976 Result += PDecl->getNameAsString(); Result += ",\n";
6981 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6984 if (AllMethods.size() > 0) {
6985 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6986 Result += PDecl->getNameAsString();
6990 Result += "\t0\n};\n";
6992 if (LangOpts.MicrosoftExt)
6993 Result += "static ";
6994 Result += "struct _protocol_t *";
6995 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6996 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6999 // Mark this protocol as having been generated.
7000 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()).second)
7001 llvm_unreachable("protocol already synthesized");
7004 /// hasObjCExceptionAttribute - Return true if this class or any super
7005 /// class has the __objc_exception__ attribute.
7006 /// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
7007 static bool hasObjCExceptionAttribute(ASTContext &Context,
7008 const ObjCInterfaceDecl *OID) {
7009 if (OID->hasAttr<ObjCExceptionAttr>())
7011 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
7012 return hasObjCExceptionAttribute(Context, Super);
7016 void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
7017 std::string &Result) {
7018 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7020 // Explicitly declared @interface's are already synthesized.
7021 if (CDecl->isImplicitInterfaceDecl())
7023 "Legacy implicit interface rewriting not supported in moder abi");
7025 WriteModernMetadataDeclarations(Context, Result);
7026 SmallVector<ObjCIvarDecl *, 8> IVars;
7028 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7029 IVD; IVD = IVD->getNextIvar()) {
7030 // Ignore unnamed bit-fields.
7031 if (!IVD->getDeclName())
7033 IVars.push_back(IVD);
7036 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
7037 "_OBJC_$_INSTANCE_VARIABLES_",
7040 // Build _objc_method_list for class's instance methods if needed
7041 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
7043 // If any of our property implementations have associated getters or
7044 // setters, produce metadata for them as well.
7045 for (const auto *Prop : IDecl->property_impls()) {
7046 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
7048 if (!Prop->getPropertyIvarDecl())
7050 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
7053 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7054 if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
7055 InstanceMethods.push_back(Getter);
7056 if (PD->isReadOnly())
7058 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7059 if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
7060 InstanceMethods.push_back(Setter);
7063 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7064 "_OBJC_$_INSTANCE_METHODS_",
7065 IDecl->getNameAsString(), true);
7067 SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
7069 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7070 "_OBJC_$_CLASS_METHODS_",
7071 IDecl->getNameAsString(), true);
7073 // Protocols referenced in class declaration?
7074 // Protocol's super protocol list
7075 std::vector<ObjCProtocolDecl *> RefedProtocols;
7076 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7077 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7078 E = Protocols.end();
7080 RefedProtocols.push_back(*I);
7081 // Must write out all protocol definitions in current qualifier list,
7082 // and in their nested qualifiers before writing out current definition.
7083 RewriteObjCProtocolMetaData(*I, Result);
7086 Write_protocol_list_initializer(Context, Result,
7088 "_OBJC_CLASS_PROTOCOLS_$_",
7089 IDecl->getNameAsString());
7091 // Protocol's property metadata.
7092 SmallVector<ObjCPropertyDecl *, 8> ClassProperties(
7093 CDecl->instance_properties());
7094 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
7095 /* Container */IDecl,
7096 "_OBJC_$_PROP_LIST_",
7097 CDecl->getNameAsString());
7099 // Data for initializing _class_ro_t metaclass meta-data
7100 uint32_t flags = CLS_META;
7101 std::string InstanceSize;
7102 std::string InstanceStart;
7104 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7106 flags |= OBJC2_CLS_HIDDEN;
7108 if (!CDecl->getSuperClass())
7111 InstanceSize = "sizeof(struct _class_t)";
7112 InstanceStart = InstanceSize;
7113 Write__class_ro_t_initializer(Context, Result, flags,
7114 InstanceStart, InstanceSize,
7119 "_OBJC_METACLASS_RO_$_",
7120 CDecl->getNameAsString());
7122 // Data for initializing _class_ro_t meta-data
7125 flags |= OBJC2_CLS_HIDDEN;
7127 if (hasObjCExceptionAttribute(*Context, CDecl))
7128 flags |= CLS_EXCEPTION;
7130 if (!CDecl->getSuperClass())
7134 InstanceSize.clear();
7135 InstanceStart.clear();
7136 if (!ObjCSynthesizedStructs.count(CDecl)) {
7138 InstanceStart = "0";
7141 InstanceSize = "sizeof(struct ";
7142 InstanceSize += CDecl->getNameAsString();
7143 InstanceSize += "_IMPL)";
7145 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7147 RewriteIvarOffsetComputation(IVD, InstanceStart);
7150 InstanceStart = InstanceSize;
7152 Write__class_ro_t_initializer(Context, Result, flags,
7153 InstanceStart, InstanceSize,
7158 "_OBJC_CLASS_RO_$_",
7159 CDecl->getNameAsString());
7161 Write_class_t(Context, Result,
7162 "OBJC_METACLASS_$_",
7163 CDecl, /*metaclass*/true);
7165 Write_class_t(Context, Result,
7167 CDecl, /*metaclass*/false);
7169 if (ImplementationIsNonLazy(IDecl))
7170 DefinedNonLazyClasses.push_back(CDecl);
7173 void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7174 int ClsDefCount = ClassImplementation.size();
7177 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7178 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7179 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7180 for (int i = 0; i < ClsDefCount; i++) {
7181 ObjCImplementationDecl *IDecl = ClassImplementation[i];
7182 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7183 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7184 Result += CDecl->getName(); Result += ",\n";
7189 void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7190 int ClsDefCount = ClassImplementation.size();
7191 int CatDefCount = CategoryImplementation.size();
7193 // For each implemented class, write out all its meta data.
7194 for (int i = 0; i < ClsDefCount; i++)
7195 RewriteObjCClassMetaData(ClassImplementation[i], Result);
7197 RewriteClassSetupInitHook(Result);
7199 // For each implemented category, write out all its meta data.
7200 for (int i = 0; i < CatDefCount; i++)
7201 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7203 RewriteCategorySetupInitHook(Result);
7205 if (ClsDefCount > 0) {
7206 if (LangOpts.MicrosoftExt)
7207 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
7208 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7209 Result += llvm::utostr(ClsDefCount); Result += "]";
7211 " __attribute__((used, section (\"__DATA, __objc_classlist,"
7212 "regular,no_dead_strip\")))= {\n";
7213 for (int i = 0; i < ClsDefCount; i++) {
7214 Result += "\t&OBJC_CLASS_$_";
7215 Result += ClassImplementation[i]->getNameAsString();
7220 if (!DefinedNonLazyClasses.empty()) {
7221 if (LangOpts.MicrosoftExt)
7222 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7223 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7224 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7225 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7232 if (CatDefCount > 0) {
7233 if (LangOpts.MicrosoftExt)
7234 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
7235 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7236 Result += llvm::utostr(CatDefCount); Result += "]";
7238 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7239 "regular,no_dead_strip\")))= {\n";
7240 for (int i = 0; i < CatDefCount; i++) {
7241 Result += "\t&_OBJC_$_CATEGORY_";
7243 CategoryImplementation[i]->getClassInterface()->getNameAsString();
7245 Result += CategoryImplementation[i]->getNameAsString();
7251 if (!DefinedNonLazyCategories.empty()) {
7252 if (LangOpts.MicrosoftExt)
7253 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7254 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7255 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7256 Result += "\t&_OBJC_$_CATEGORY_";
7258 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7260 Result += DefinedNonLazyCategories[i]->getNameAsString();
7267 void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7268 if (LangOpts.MicrosoftExt)
7269 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7271 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7272 // version 0, ObjCABI is 2
7273 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
7276 /// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7278 void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7279 std::string &Result) {
7280 WriteModernMetadataDeclarations(Context, Result);
7281 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7282 // Find category declaration for this implementation.
7283 ObjCCategoryDecl *CDecl
7284 = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
7286 std::string FullCategoryName = ClassDecl->getNameAsString();
7287 FullCategoryName += "_$_";
7288 FullCategoryName += CDecl->getNameAsString();
7290 // Build _objc_method_list for class's instance methods if needed
7291 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
7293 // If any of our property implementations have associated getters or
7294 // setters, produce metadata for them as well.
7295 for (const auto *Prop : IDecl->property_impls()) {
7296 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
7298 if (!Prop->getPropertyIvarDecl())
7300 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
7303 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7304 InstanceMethods.push_back(Getter);
7305 if (PD->isReadOnly())
7307 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7308 InstanceMethods.push_back(Setter);
7311 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7312 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7313 FullCategoryName, true);
7315 SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
7317 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7318 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7319 FullCategoryName, true);
7321 // Protocols referenced in class declaration?
7322 // Protocol's super protocol list
7323 SmallVector<ObjCProtocolDecl *, 8> RefedProtocols(CDecl->protocols());
7324 for (auto *I : CDecl->protocols())
7325 // Must write out all protocol definitions in current qualifier list,
7326 // and in their nested qualifiers before writing out current definition.
7327 RewriteObjCProtocolMetaData(I, Result);
7329 Write_protocol_list_initializer(Context, Result,
7331 "_OBJC_CATEGORY_PROTOCOLS_$_",
7334 // Protocol's property metadata.
7335 SmallVector<ObjCPropertyDecl *, 8> ClassProperties(
7336 CDecl->instance_properties());
7337 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
7338 /* Container */IDecl,
7339 "_OBJC_$_PROP_LIST_",
7342 Write_category_t(*this, Context, Result,
7350 // Determine if this category is also "non-lazy".
7351 if (ImplementationIsNonLazy(IDecl))
7352 DefinedNonLazyCategories.push_back(CDecl);
7355 void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7356 int CatDefCount = CategoryImplementation.size();
7359 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7360 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7361 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7362 for (int i = 0; i < CatDefCount; i++) {
7363 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7364 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7365 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7366 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7367 Result += ClassDecl->getName();
7369 Result += CatDecl->getName();
7375 // RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7377 template<typename MethodIterator>
7378 void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7379 MethodIterator MethodEnd,
7380 bool IsInstanceMethod,
7382 StringRef ClassName,
7383 std::string &Result) {
7384 if (MethodBegin == MethodEnd) return;
7386 if (!objc_impl_method) {
7387 /* struct _objc_method {
7393 Result += "\nstruct _objc_method {\n";
7394 Result += "\tSEL _cmd;\n";
7395 Result += "\tchar *method_types;\n";
7396 Result += "\tvoid *_imp;\n";
7399 objc_impl_method = true;
7402 // Build _objc_method_list for class's methods if needed
7405 struct _objc_method_list *next_method;
7407 struct _objc_method method_list[];
7410 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
7412 if (LangOpts.MicrosoftExt) {
7413 if (IsInstanceMethod)
7414 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7416 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7418 Result += "static struct {\n";
7419 Result += "\tstruct _objc_method_list *next_method;\n";
7420 Result += "\tint method_count;\n";
7421 Result += "\tstruct _objc_method method_list[";
7422 Result += utostr(NumMethods);
7423 Result += "];\n} _OBJC_";
7425 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7426 Result += "_METHODS_";
7427 Result += ClassName;
7428 Result += " __attribute__ ((used, section (\"__OBJC, __";
7429 Result += IsInstanceMethod ? "inst" : "cls";
7430 Result += "_meth\")))= ";
7431 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7433 Result += "\t,{{(SEL)\"";
7434 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7435 std::string MethodTypeString;
7436 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7438 Result += MethodTypeString;
7439 Result += "\", (void *)";
7440 Result += MethodInternalNames[*MethodBegin];
7442 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7443 Result += "\t ,{(SEL)\"";
7444 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7445 std::string MethodTypeString;
7446 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7448 Result += MethodTypeString;
7449 Result += "\", (void *)";
7450 Result += MethodInternalNames[*MethodBegin];
7453 Result += "\t }\n};\n";
7456 Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7457 SourceRange OldRange = IV->getSourceRange();
7458 Expr *BaseExpr = IV->getBase();
7460 // Rewrite the base, but without actually doing replaces.
7462 DisableReplaceStmtScope S(*this);
7463 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7464 IV->setBase(BaseExpr);
7467 ObjCIvarDecl *D = IV->getDecl();
7469 Expr *Replacement = IV;
7471 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7472 const ObjCInterfaceType *iFaceDecl =
7473 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
7474 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7475 // lookup which class implements the instance variable.
7476 ObjCInterfaceDecl *clsDeclared = nullptr;
7477 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7479 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7481 // Build name of symbol holding ivar offset.
7482 std::string IvarOffsetName;
7483 if (D->isBitField())
7484 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
7486 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
7488 ReferencedIvars[clsDeclared].insert(D);
7490 // cast offset to "char *".
7491 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7492 Context->getPointerType(Context->CharTy),
7495 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7496 SourceLocation(), &Context->Idents.get(IvarOffsetName),
7497 Context->UnsignedLongTy, nullptr,
7499 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7500 Context->UnsignedLongTy, VK_LValue,
7502 BinaryOperator *addExpr =
7503 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7504 Context->getPointerType(Context->CharTy),
7505 VK_RValue, OK_Ordinary, SourceLocation(), FPOptions());
7506 // Don't forget the parens to enforce the proper binding.
7507 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7510 QualType IvarT = D->getType();
7511 if (D->isBitField())
7512 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
7514 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
7515 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
7516 RD = RD->getDefinition();
7517 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
7518 // decltype(((Foo_IMPL*)0)->bar) *
7519 ObjCContainerDecl *CDecl =
7520 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7521 // ivar in class extensions requires special treatment.
7522 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7523 CDecl = CatDecl->getClassInterface();
7524 std::string RecName = CDecl->getName();
7526 RecordDecl *RD = RecordDecl::Create(
7527 *Context, TTK_Struct, TUDecl, SourceLocation(), SourceLocation(),
7528 &Context->Idents.get(RecName));
7529 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7530 unsigned UnsignedIntSize =
7531 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7532 Expr *Zero = IntegerLiteral::Create(*Context,
7533 llvm::APInt(UnsignedIntSize, 0),
7534 Context->UnsignedIntTy, SourceLocation());
7535 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7536 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7538 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
7540 &Context->Idents.get(D->getNameAsString()),
7542 /*BitWidth=*/nullptr,
7543 /*Mutable=*/true, ICIS_NoInit);
7544 MemberExpr *ME = new (Context)
7545 MemberExpr(PE, true, SourceLocation(), FD, SourceLocation(),
7546 FD->getType(), VK_LValue, OK_Ordinary);
7547 IvarT = Context->getDecltypeType(ME, ME->getType());
7550 convertObjCTypeToCStyleType(IvarT);
7551 QualType castT = Context->getPointerType(IvarT);
7553 castExpr = NoTypeInfoCStyleCastExpr(Context,
7559 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
7560 VK_LValue, OK_Ordinary,
7562 PE = new (Context) ParenExpr(OldRange.getBegin(),
7566 if (D->isBitField()) {
7567 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
7569 &Context->Idents.get(D->getNameAsString()),
7570 D->getType(), nullptr,
7571 /*BitWidth=*/D->getBitWidth(),
7572 /*Mutable=*/true, ICIS_NoInit);
7573 MemberExpr *ME = new (Context)
7574 MemberExpr(PE, /*isArrow*/ false, SourceLocation(), FD,
7575 SourceLocation(), FD->getType(), VK_LValue, OK_Ordinary);
7583 ReplaceStmtWithRange(IV, Replacement, OldRange);
7587 #endif // CLANG_ENABLE_OBJC_REWRITER