Coverage Report

Created: 2020-02-25 14:32

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp
Line
Count
Source (jump to first uncovered line)
1
//===-- RewriteModernObjC.cpp - Playground for the code rewriter ----------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// Hacks and fun related to the code rewriter.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/Rewrite/Frontend/ASTConsumers.h"
14
#include "clang/AST/AST.h"
15
#include "clang/AST/ASTConsumer.h"
16
#include "clang/AST/Attr.h"
17
#include "clang/AST/ParentMap.h"
18
#include "clang/Basic/CharInfo.h"
19
#include "clang/Basic/Diagnostic.h"
20
#include "clang/Basic/IdentifierTable.h"
21
#include "clang/Basic/SourceManager.h"
22
#include "clang/Basic/TargetInfo.h"
23
#include "clang/Config/config.h"
24
#include "clang/Lex/Lexer.h"
25
#include "clang/Rewrite/Core/Rewriter.h"
26
#include "llvm/ADT/DenseSet.h"
27
#include "llvm/ADT/SmallPtrSet.h"
28
#include "llvm/ADT/StringExtras.h"
29
#include "llvm/Support/MemoryBuffer.h"
30
#include "llvm/Support/raw_ostream.h"
31
#include <memory>
32
33
#if CLANG_ENABLE_OBJC_REWRITER
34
35
using namespace clang;
36
using llvm::utostr;
37
38
namespace {
39
  class RewriteModernObjC : public ASTConsumer {
40
  protected:
41
42
    enum {
43
      BLOCK_FIELD_IS_OBJECT   =  3,  /* id, NSObject, __attribute__((NSObject)),
44
                                        block, ... */
45
      BLOCK_FIELD_IS_BLOCK    =  7,  /* a block variable */
46
      BLOCK_FIELD_IS_BYREF    =  8,  /* the on stack structure holding the
47
                                        __block variable */
48
      BLOCK_FIELD_IS_WEAK     = 16,  /* declared __weak, only used in byref copy
49
                                        helpers */
50
      BLOCK_BYREF_CALLER      = 128, /* called from __block (byref) copy/dispose
51
                                        support routines */
52
      BLOCK_BYREF_CURRENT_MAX = 256
53
    };
54
55
    enum {
56
      BLOCK_NEEDS_FREE =        (1 << 24),
57
      BLOCK_HAS_COPY_DISPOSE =  (1 << 25),
58
      BLOCK_HAS_CXX_OBJ =       (1 << 26),
59
      BLOCK_IS_GC =             (1 << 27),
60
      BLOCK_IS_GLOBAL =         (1 << 28),
61
      BLOCK_HAS_DESCRIPTOR =    (1 << 29)
62
    };
63
64
    Rewriter Rewrite;
65
    DiagnosticsEngine &Diags;
66
    const LangOptions &LangOpts;
67
    ASTContext *Context;
68
    SourceManager *SM;
69
    TranslationUnitDecl *TUDecl;
70
    FileID MainFileID;
71
    const char *MainFileStart, *MainFileEnd;
72
    Stmt *CurrentBody;
73
    ParentMap *PropParentMap; // created lazily.
74
    std::string InFileName;
75
    std::unique_ptr<raw_ostream> OutFile;
76
    std::string Preamble;
77
78
    TypeDecl *ProtocolTypeDecl;
79
    VarDecl *GlobalVarDecl;
80
    Expr *GlobalConstructionExp;
81
    unsigned RewriteFailedDiag;
82
    unsigned GlobalBlockRewriteFailedDiag;
83
    // ObjC string constant support.
84
    unsigned NumObjCStringLiterals;
85
    VarDecl *ConstantStringClassReference;
86
    RecordDecl *NSStringRecord;
87
88
    // ObjC foreach break/continue generation support.
89
    int BcLabelCount;
90
91
    unsigned TryFinallyContainsReturnDiag;
92
    // Needed for super.
93
    ObjCMethodDecl *CurMethodDef;
94
    RecordDecl *SuperStructDecl;
95
    RecordDecl *ConstantStringDecl;
96
97
    FunctionDecl *MsgSendFunctionDecl;
98
    FunctionDecl *MsgSendSuperFunctionDecl;
99
    FunctionDecl *MsgSendStretFunctionDecl;
100
    FunctionDecl *MsgSendSuperStretFunctionDecl;
101
    FunctionDecl *MsgSendFpretFunctionDecl;
102
    FunctionDecl *GetClassFunctionDecl;
103
    FunctionDecl *GetMetaClassFunctionDecl;
104
    FunctionDecl *GetSuperClassFunctionDecl;
105
    FunctionDecl *SelGetUidFunctionDecl;
106
    FunctionDecl *CFStringFunctionDecl;
107
    FunctionDecl *SuperConstructorFunctionDecl;
108
    FunctionDecl *CurFunctionDef;
109
110
    /* Misc. containers needed for meta-data rewrite. */
111
    SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
112
    SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
113
    llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
114
    llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
115
    llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
116
    llvm::SmallPtrSet<TagDecl*, 32> GlobalDefinedTags;
117
    SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
118
    /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
119
    SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
120
121
    /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
122
    SmallVector<ObjCCategoryDecl *, 8> DefinedNonLazyCategories;
123
124
    SmallVector<Stmt *, 32> Stmts;
125
    SmallVector<int, 8> ObjCBcLabelNo;
126
    // Remember all the @protocol(<expr>) expressions.
127
    llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
128
129
    llvm::DenseSet<uint64_t> CopyDestroyCache;
130
131
    // Block expressions.
132
    SmallVector<BlockExpr *, 32> Blocks;
133
    SmallVector<int, 32> InnerDeclRefsCount;
134
    SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
135
136
    SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
137
138
    // Block related declarations.
139
    SmallVector<ValueDecl *, 8> BlockByCopyDecls;
140
    llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
141
    SmallVector<ValueDecl *, 8> BlockByRefDecls;
142
    llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
143
    llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
144
    llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
145
    llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
146
147
    llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
148
    llvm::DenseMap<ObjCInterfaceDecl *,
149
                    llvm::SmallSetVector<ObjCIvarDecl *, 8> > ReferencedIvars;
150
151
    // ivar bitfield grouping containers
152
    llvm::DenseSet<const ObjCInterfaceDecl *> ObjCInterefaceHasBitfieldGroups;
153
    llvm::DenseMap<const ObjCIvarDecl* , unsigned> IvarGroupNumber;
154
    // This container maps an <class, group number for ivar> tuple to the type
155
    // of the struct where the bitfield belongs.
156
    llvm::DenseMap<std::pair<const ObjCInterfaceDecl*, unsigned>, QualType> GroupRecordType;
157
    SmallVector<FunctionDecl*, 32> FunctionDefinitionsSeen;
158
159
    // This maps an original source AST to it's rewritten form. This allows
160
    // us to avoid rewriting the same node twice (which is very uncommon).
161
    // This is needed to support some of the exotic property rewriting.
162
    llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
163
164
    // Needed for header files being rewritten
165
    bool IsHeader;
166
    bool SilenceRewriteMacroWarning;
167
    bool GenerateLineInfo;
168
    bool objc_impl_method;
169
170
    bool DisableReplaceStmt;
171
    class DisableReplaceStmtScope {
172
      RewriteModernObjC &R;
173
      bool SavedValue;
174
175
    public:
176
      DisableReplaceStmtScope(RewriteModernObjC &R)
177
130
        : R(R), SavedValue(R.DisableReplaceStmt) {
178
130
        R.DisableReplaceStmt = true;
179
130
      }
180
130
      ~DisableReplaceStmtScope() {
181
130
        R.DisableReplaceStmt = SavedValue;
182
130
      }
183
    };
184
    void InitializeCommon(ASTContext &context);
185
186
  public:
187
    llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
188
189
    // Top Level Driver code.
190
584
    bool HandleTopLevelDecl(DeclGroupRef D) override {
191
998
      for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; 
++I414
) {
192
667
        if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
193
157
          if (!Class->isThisDeclarationADefinition()) {
194
11
            RewriteForwardClassDecl(D);
195
11
            break;
196
146
          } else {
197
146
            // Keep track of all interface declarations seen.
198
146
            ObjCInterfacesSeen.push_back(Class);
199
146
            break;
200
146
          }
201
510
        }
202
510
203
510
        if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
204
18
          if (!Proto->isThisDeclarationADefinition()) {
205
2
            RewriteForwardProtocolDecl(D);
206
2
            break;
207
2
          }
208
508
        }
209
508
210
508
        if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*I)) {
211
172
          // Under modern abi, we cannot translate body of the function
212
172
          // yet until all class extensions and its implementation is seen.
213
172
          // This is because they may introduce new bitfields which must go
214
172
          // into their grouping struct.
215
172
          if (FDecl->isThisDeclarationADefinition() &&
216
172
              // Not c functions defined inside an objc container.
217
172
              
!FDecl->isTopLevelDeclInObjCContainer()96
) {
218
94
            FunctionDefinitionsSeen.push_back(FDecl);
219
94
            break;
220
94
          }
221
414
        }
222
414
        HandleTopLevelSingleDecl(*I);
223
414
      }
224
584
      return true;
225
584
    }
226
227
1
    void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
228
2
      for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; 
++I1
) {
229
1
        if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(*I)) {
230
1
          if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
231
1
            RewriteBlockPointerDecl(TD);
232
0
          else if (TD->getUnderlyingType()->isFunctionPointerType())
233
0
            CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
234
0
          else
235
0
            RewriteObjCQualifiedInterfaceTypes(TD);
236
1
        }
237
1
      }
238
1
    }
239
240
    void HandleTopLevelSingleDecl(Decl *D);
241
    void HandleDeclInMainFile(Decl *D);
242
    RewriteModernObjC(std::string inFile, std::unique_ptr<raw_ostream> OS,
243
                      DiagnosticsEngine &D, const LangOptions &LOpts,
244
                      bool silenceMacroWarn, bool LineInfo);
245
246
78
    ~RewriteModernObjC() override {}
247
248
    void HandleTranslationUnit(ASTContext &C) override;
249
250
278
    void ReplaceStmt(Stmt *Old, Stmt *New) {
251
278
      ReplaceStmtWithRange(Old, New, Old->getSourceRange());
252
278
    }
253
254
408
    void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
255
408
      assert(Old != nullptr && New != nullptr && "Expected non-null Stmt's");
256
408
257
408
      Stmt *ReplacingStmt = ReplacedNodes[Old];
258
408
      if (ReplacingStmt)
259
0
        return; // We can't rewrite the same node twice.
260
408
261
408
      if (DisableReplaceStmt)
262
16
        return;
263
392
264
392
      // Measure the old text.
265
392
      int Size = Rewrite.getRangeSize(SrcRange);
266
392
      if (Size == -1) {
267
0
        Diags.Report(Context->getFullLoc(Old->getBeginLoc()), RewriteFailedDiag)
268
0
            << Old->getSourceRange();
269
0
        return;
270
0
      }
271
392
      // Get the new text.
272
392
      std::string SStr;
273
392
      llvm::raw_string_ostream S(SStr);
274
392
      New->printPretty(S, nullptr, PrintingPolicy(LangOpts));
275
392
      const std::string &Str = S.str();
276
392
277
392
      // If replacement succeeded or warning disabled return with no warning.
278
392
      if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
279
392
        ReplacedNodes[Old] = New;
280
392
        return;
281
392
      }
282
0
      if (SilenceRewriteMacroWarning)
283
0
        return;
284
0
      Diags.Report(Context->getFullLoc(Old->getBeginLoc()), RewriteFailedDiag)
285
0
          << Old->getSourceRange();
286
0
    }
287
288
    void InsertText(SourceLocation Loc, StringRef Str,
289
870
                    bool InsertAfter = true) {
290
870
      // If insertion succeeded or warning disabled return with no warning.
291
870
      if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
292
870
          
SilenceRewriteMacroWarning0
)
293
870
        return;
294
0
295
0
      Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
296
0
    }
297
298
    void ReplaceText(SourceLocation Start, unsigned OrigLength,
299
714
                     StringRef Str) {
300
714
      // If removal succeeded or warning disabled return with no warning.
301
714
      if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
302
714
          
SilenceRewriteMacroWarning0
)
303
714
        return;
304
0
305
0
      Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
306
0
    }
307
308
    // Syntactic Rewriting.
309
    void RewriteRecordBody(RecordDecl *RD);
310
    void RewriteInclude();
311
    void RewriteLineDirective(const Decl *D);
312
    void ConvertSourceLocationToLineDirective(SourceLocation Loc,
313
                                              std::string &LineString);
314
    void RewriteForwardClassDecl(DeclGroupRef D);
315
    void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG);
316
    void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
317
                                     const std::string &typedefString);
318
    void RewriteImplementations();
319
    void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
320
                                 ObjCImplementationDecl *IMD,
321
                                 ObjCCategoryImplDecl *CID);
322
    void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
323
    void RewriteImplementationDecl(Decl *Dcl);
324
    void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
325
                               ObjCMethodDecl *MDecl, std::string &ResultStr);
326
    void RewriteTypeIntoString(QualType T, std::string &ResultStr,
327
                               const FunctionType *&FPRetType);
328
    void RewriteByRefString(std::string &ResultStr, const std::string &Name,
329
                            ValueDecl *VD, bool def=false);
330
    void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
331
    void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
332
    void RewriteForwardProtocolDecl(DeclGroupRef D);
333
    void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG);
334
    void RewriteMethodDeclaration(ObjCMethodDecl *Method);
335
    void RewriteProperty(ObjCPropertyDecl *prop);
336
    void RewriteFunctionDecl(FunctionDecl *FD);
337
    void RewriteBlockPointerType(std::string& Str, QualType Type);
338
    void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
339
    void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
340
    void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
341
    void RewriteTypeOfDecl(VarDecl *VD);
342
    void RewriteObjCQualifiedInterfaceTypes(Expr *E);
343
344
    std::string getIvarAccessString(ObjCIvarDecl *D);
345
346
    // Expression Rewriting.
347
    Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
348
    Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
349
    Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
350
    Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
351
    Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
352
    Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
353
    Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
354
    Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
355
    Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
356
    Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
357
    Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
358
    Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
359
    Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
360
    Stmt *RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt  *S);
361
    Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
362
    Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
363
    Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
364
                                       SourceLocation OrigEnd);
365
    Stmt *RewriteBreakStmt(BreakStmt *S);
366
    Stmt *RewriteContinueStmt(ContinueStmt *S);
367
    void RewriteCastExpr(CStyleCastExpr *CE);
368
    void RewriteImplicitCastObjCExpr(CastExpr *IE);
369
370
    // Computes ivar bitfield group no.
371
    unsigned ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV);
372
    // Names field decl. for ivar bitfield group.
373
    void ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV, std::string &Result);
374
    // Names struct type for ivar bitfield group.
375
    void ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV, std::string &Result);
376
    // Names symbol for ivar bitfield group field offset.
377
    void ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV, std::string &Result);
378
    // Given an ivar bitfield, it builds (or finds) its group record type.
379
    QualType GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV);
380
    QualType SynthesizeBitfieldGroupStructType(
381
                                    ObjCIvarDecl *IV,
382
                                    SmallVectorImpl<ObjCIvarDecl *> &IVars);
383
384
    // Block rewriting.
385
    void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
386
387
    // Block specific rewrite rules.
388
    void RewriteBlockPointerDecl(NamedDecl *VD);
389
    void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
390
    Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
391
    Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
392
    void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
393
394
    void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
395
                                      std::string &Result);
396
397
    void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
398
    bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
399
                                 bool &IsNamedDefinition);
400
    void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
401
                                              std::string &Result);
402
403
    bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
404
405
    void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
406
                                  std::string &Result);
407
408
    void Initialize(ASTContext &context) override;
409
410
    // Misc. AST transformation routines. Sometimes they end up calling
411
    // rewriting routines on the new ASTs.
412
    CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
413
                                           ArrayRef<Expr *> Args,
414
                                           SourceLocation StartLoc=SourceLocation(),
415
                                           SourceLocation EndLoc=SourceLocation());
416
417
    Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
418
                                        QualType returnType,
419
                                        SmallVectorImpl<QualType> &ArgTypes,
420
                                        SmallVectorImpl<Expr*> &MsgExprs,
421
                                        ObjCMethodDecl *Method);
422
423
    Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
424
                           SourceLocation StartLoc=SourceLocation(),
425
                           SourceLocation EndLoc=SourceLocation());
426
427
    void SynthCountByEnumWithState(std::string &buf);
428
    void SynthMsgSendFunctionDecl();
429
    void SynthMsgSendSuperFunctionDecl();
430
    void SynthMsgSendStretFunctionDecl();
431
    void SynthMsgSendFpretFunctionDecl();
432
    void SynthMsgSendSuperStretFunctionDecl();
433
    void SynthGetClassFunctionDecl();
434
    void SynthGetMetaClassFunctionDecl();
435
    void SynthGetSuperClassFunctionDecl();
436
    void SynthSelGetUidFunctionDecl();
437
    void SynthSuperConstructorFunctionDecl();
438
439
    // Rewriting metadata
440
    template<typename MethodIterator>
441
    void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
442
                                    MethodIterator MethodEnd,
443
                                    bool IsInstanceMethod,
444
                                    StringRef prefix,
445
                                    StringRef ClassName,
446
                                    std::string &Result);
447
    void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
448
                                     std::string &Result);
449
    void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
450
                                          std::string &Result);
451
    void RewriteClassSetupInitHook(std::string &Result);
452
453
    void RewriteMetaDataIntoBuffer(std::string &Result);
454
    void WriteImageInfo(std::string &Result);
455
    void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
456
                                             std::string &Result);
457
    void RewriteCategorySetupInitHook(std::string &Result);
458
459
    // Rewriting ivar
460
    void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
461
                                              std::string &Result);
462
    Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
463
464
465
    std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
466
    std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
467
                                      StringRef funcName, std::string Tag);
468
    std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
469
                                      StringRef funcName, std::string Tag);
470
    std::string SynthesizeBlockImpl(BlockExpr *CE,
471
                                    std::string Tag, std::string Desc);
472
    std::string SynthesizeBlockDescriptor(std::string DescTag,
473
                                          std::string ImplTag,
474
                                          int i, StringRef funcName,
475
                                          unsigned hasCopy);
476
    Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
477
    void SynthesizeBlockLiterals(SourceLocation FunLocStart,
478
                                 StringRef FunName);
479
    FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
480
    Stmt *SynthBlockInitExpr(BlockExpr *Exp,
481
                      const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
482
483
    // Misc. helper routines.
484
    QualType getProtocolType();
485
    void WarnAboutReturnGotoStmts(Stmt *S);
486
    void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
487
    void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
488
    void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
489
490
    bool IsDeclStmtInForeachHeader(DeclStmt *DS);
491
    void CollectBlockDeclRefInfo(BlockExpr *Exp);
492
    void GetBlockDeclRefExprs(Stmt *S);
493
    void GetInnerBlockDeclRefExprs(Stmt *S,
494
                SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
495
                llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts);
496
497
    // We avoid calling Type::isBlockPointerType(), since it operates on the
498
    // canonical type. We only care if the top-level type is a closure pointer.
499
1.32k
    bool isTopLevelBlockPointerType(QualType T) {
500
1.32k
      return isa<BlockPointerType>(T);
501
1.32k
    }
502
503
    /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
504
    /// to a function pointer type and upon success, returns true; false
505
    /// otherwise.
506
709
    bool convertBlockPointerToFunctionPointer(QualType &T) {
507
709
      if (isTopLevelBlockPointerType(T)) {
508
22
        const auto *BPT = T->castAs<BlockPointerType>();
509
22
        T = Context->getPointerType(BPT->getPointeeType());
510
22
        return true;
511
22
      }
512
687
      return false;
513
687
    }
514
515
    bool convertObjCTypeToCStyleType(QualType &T);
516
517
    bool needToScanForQualifiers(QualType T);
518
    QualType getSuperStructType();
519
    QualType getConstantStringStructType();
520
    QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
521
522
529
    void convertToUnqualifiedObjCType(QualType &T) {
523
529
      if (T->isObjCQualifiedIdType()) {
524
15
        bool isConst = T.isConstQualified();
525
15
        T = isConst ? 
Context->getObjCIdType().withConst()2
526
15
                    : 
Context->getObjCIdType()13
;
527
15
      }
528
514
      else if (T->isObjCQualifiedClassType())
529
0
        T = Context->getObjCClassType();
530
514
      else if (T->isObjCObjectPointerType() &&
531
514
               
T->getPointeeType()->isObjCQualifiedInterfaceType()136
) {
532
18
        if (const ObjCObjectPointerType * OBJPT =
533
18
              T->getAsObjCInterfacePointerType()) {
534
18
          const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
535
18
          T = QualType(IFaceT, 0);
536
18
          T = Context->getPointerType(T);
537
18
        }
538
18
     }
539
529
    }
540
541
    // FIXME: This predicate seems like it would be useful to add to ASTContext.
542
36
    bool isObjCType(QualType T) {
543
36
      if (!LangOpts.ObjC)
544
0
        return false;
545
36
546
36
      QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
547
36
548
36
      if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
549
36
          
OCT == Context->getCanonicalType(Context->getObjCClassType())33
)
550
3
        return true;
551
33
552
33
      if (const PointerType *PT = OCT->getAs<PointerType>()) {
553
2
        if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
554
2
            PT->getPointeeType()->isObjCQualifiedIdType())
555
0
          return true;
556
33
      }
557
33
      return false;
558
33
    }
559
560
    bool PointerTypeTakesAnyBlockArguments(QualType QT);
561
    bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
562
    void GetExtentOfArgList(const char *Name, const char *&LParen,
563
                            const char *&RParen);
564
565
180
    void QuoteDoublequotes(std::string &From, std::string &To) {
566
2.41k
      for (unsigned i = 0; i < From.length(); 
i++2.23k
) {
567
2.23k
        if (From[i] == '"')
568
260
          To += "\\\"";
569
1.97k
        else
570
1.97k
          To += From[i];
571
2.23k
      }
572
180
    }
573
574
    QualType getSimpleFunctionType(QualType result,
575
                                   ArrayRef<QualType> args,
576
404
                                   bool variadic = false) {
577
404
      if (result == Context->getObjCInstanceType())
578
0
        result =  Context->getObjCIdType();
579
404
      FunctionProtoType::ExtProtoInfo fpi;
580
404
      fpi.Variadic = variadic;
581
404
      return Context->getFunctionType(result, args, fpi);
582
404
    }
583
584
    // Helper function: create a CStyleCastExpr with trivial type source info.
585
    CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
586
909
                                             CastKind Kind, Expr *E) {
587
909
      TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
588
909
      return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, nullptr,
589
909
                                    TInfo, SourceLocation(), SourceLocation());
590
909
    }
591
592
93
    bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
593
93
      IdentifierInfo* II = &Context->Idents.get("load");
594
93
      Selector LoadSel = Context->Selectors.getSelector(0, &II);
595
93
      return OD->getClassMethod(LoadSel) != nullptr;
596
93
    }
597
598
217
    StringLiteral *getStringLiteral(StringRef Str) {
599
217
      QualType StrType = Context->getConstantArrayType(
600
217
          Context->CharTy, llvm::APInt(32, Str.size() + 1), nullptr,
601
217
          ArrayType::Normal, 0);
602
217
      return StringLiteral::Create(*Context, Str, StringLiteral::Ascii,
603
217
                                   /*Pascal=*/false, StrType, SourceLocation());
604
217
    }
605
  };
606
} // end anonymous namespace
607
608
void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
609
192
                                                   NamedDecl *D) {
610
192
  if (const FunctionProtoType *fproto
611
169
      = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
612
169
    for (const auto &I : fproto->param_types())
613
114
      if (isTopLevelBlockPointerType(I)) {
614
26
        // All the args are checked/rewritten. Don't call twice!
615
26
        RewriteBlockPointerDecl(D);
616
26
        break;
617
26
      }
618
169
  }
619
192
}
620
621
2
void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
622
2
  const PointerType *PT = funcType->getAs<PointerType>();
623
2
  if (PT && PointerTypeTakesAnyBlockArguments(funcType))
624
0
    RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
625
2
}
626
627
78
static bool IsHeaderFile(const std::string &Filename) {
628
78
  std::string::size_type DotPos = Filename.rfind('.');
629
78
630
78
  if (DotPos == std::string::npos) {
631
0
    // no file extension
632
0
    return false;
633
0
  }
634
78
635
78
  std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
636
78
  // C header: .h
637
78
  // C++ header: .hh or .H;
638
78
  return Ext == "h" || Ext == "hh" || Ext == "H";
639
78
}
640
641
RewriteModernObjC::RewriteModernObjC(std::string inFile,
642
                                     std::unique_ptr<raw_ostream> OS,
643
                                     DiagnosticsEngine &D,
644
                                     const LangOptions &LOpts,
645
                                     bool silenceMacroWarn, bool LineInfo)
646
    : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(std::move(OS)),
647
78
      SilenceRewriteMacroWarning(silenceMacroWarn), GenerateLineInfo(LineInfo) {
648
78
  IsHeader = IsHeaderFile(inFile);
649
78
  RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
650
78
               "rewriting sub-expression within a macro (may not be correct)");
651
78
  // FIXME. This should be an error. But if block is not called, it is OK. And it
652
78
  // may break including some headers.
653
78
  GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
654
78
    "rewriting block literal declared in global scope is not implemented");
655
78
656
78
  TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
657
78
               DiagnosticsEngine::Warning,
658
78
               "rewriter doesn't support user-specified control flow semantics "
659
78
               "for @try/@finally (code may not execute properly)");
660
78
}
661
662
std::unique_ptr<ASTConsumer> clang::CreateModernObjCRewriter(
663
    const std::string &InFile, std::unique_ptr<raw_ostream> OS,
664
    DiagnosticsEngine &Diags, const LangOptions &LOpts,
665
78
    bool SilenceRewriteMacroWarning, bool LineInfo) {
666
78
  return std::make_unique<RewriteModernObjC>(InFile, std::move(OS), Diags,
667
78
                                              LOpts, SilenceRewriteMacroWarning,
668
78
                                              LineInfo);
669
78
}
670
671
78
void RewriteModernObjC::InitializeCommon(ASTContext &context) {
672
78
  Context = &context;
673
78
  SM = &Context->getSourceManager();
674
78
  TUDecl = Context->getTranslationUnitDecl();
675
78
  MsgSendFunctionDecl = nullptr;
676
78
  MsgSendSuperFunctionDecl = nullptr;
677
78
  MsgSendStretFunctionDecl = nullptr;
678
78
  MsgSendSuperStretFunctionDecl = nullptr;
679
78
  MsgSendFpretFunctionDecl = nullptr;
680
78
  GetClassFunctionDecl = nullptr;
681
78
  GetMetaClassFunctionDecl = nullptr;
682
78
  GetSuperClassFunctionDecl = nullptr;
683
78
  SelGetUidFunctionDecl = nullptr;
684
78
  CFStringFunctionDecl = nullptr;
685
78
  ConstantStringClassReference = nullptr;
686
78
  NSStringRecord = nullptr;
687
78
  CurMethodDef = nullptr;
688
78
  CurFunctionDef = nullptr;
689
78
  GlobalVarDecl = nullptr;
690
78
  GlobalConstructionExp = nullptr;
691
78
  SuperStructDecl = nullptr;
692
78
  ProtocolTypeDecl = nullptr;
693
78
  ConstantStringDecl = nullptr;
694
78
  BcLabelCount = 0;
695
78
  SuperConstructorFunctionDecl = nullptr;
696
78
  NumObjCStringLiterals = 0;
697
78
  PropParentMap = nullptr;
698
78
  CurrentBody = nullptr;
699
78
  DisableReplaceStmt = false;
700
78
  objc_impl_method = false;
701
78
702
78
  // Get the ID and start/end of the main file.
703
78
  MainFileID = SM->getMainFileID();
704
78
  const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
705
78
  MainFileStart = MainBuf->getBufferStart();
706
78
  MainFileEnd = MainBuf->getBufferEnd();
707
78
708
78
  Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
709
78
}
710
711
//===----------------------------------------------------------------------===//
712
// Top Level Driver Code
713
//===----------------------------------------------------------------------===//
714
715
541
void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
716
541
  if (Diags.hasErrorOccurred())
717
0
    return;
718
541
719
541
  // Two cases: either the decl could be in the main file, or it could be in a
720
541
  // #included file.  If the former, rewrite it now.  If the later, check to see
721
541
  // if we rewrote the #include/#import.
722
541
  SourceLocation Loc = D->getLocation();
723
541
  Loc = SM->getExpansionLoc(Loc);
724
541
725
541
  // If this is for a builtin, ignore it.
726
541
  if (Loc.isInvalid()) 
return0
;
727
541
728
541
  // Look for built-in declarations that we need to refer during the rewrite.
729
541
  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
730
192
    RewriteFunctionDecl(FD);
731
349
  } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
732
21
    // declared in <Foundation/NSString.h>
733
21
    if (FVD->getName() == "_NSConstantStringClassReference") {
734
0
      ConstantStringClassReference = FVD;
735
0
      return;
736
0
    }
737
328
  } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
738
14
    RewriteCategoryDecl(CD);
739
314
  } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
740
16
    if (PD->isThisDeclarationADefinition())
741
16
      RewriteProtocolDecl(PD);
742
298
  } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
743
25
    // Recurse into linkage specifications
744
25
    for (DeclContext::decl_iterator DI = LSD->decls_begin(),
745
25
                                 DIEnd = LSD->decls_end();
746
67
         DI != DIEnd; ) {
747
42
      if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
748
11
        if (!IFace->isThisDeclarationADefinition()) {
749
5
          SmallVector<Decl *, 8> DG;
750
5
          SourceLocation StartLoc = IFace->getBeginLoc();
751
21
          do {
752
21
            if (isa<ObjCInterfaceDecl>(*DI) &&
753
21
                
!cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition()20
&&
754
21
                
StartLoc == (*DI)->getBeginLoc()19
)
755
16
              DG.push_back(*DI);
756
5
            else
757
5
              break;
758
16
759
16
            ++DI;
760
16
          } while (DI != DIEnd);
761
5
          RewriteForwardClassDecl(DG);
762
5
          continue;
763
5
        }
764
6
        else {
765
6
          // Keep track of all interface declarations seen.
766
6
          ObjCInterfacesSeen.push_back(IFace);
767
6
          ++DI;
768
6
          continue;
769
6
        }
770
31
      }
771
31
772
31
      if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
773
0
        if (!Proto->isThisDeclarationADefinition()) {
774
0
          SmallVector<Decl *, 8> DG;
775
0
          SourceLocation StartLoc = Proto->getBeginLoc();
776
0
          do {
777
0
            if (isa<ObjCProtocolDecl>(*DI) &&
778
0
                !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
779
0
                StartLoc == (*DI)->getBeginLoc())
780
0
              DG.push_back(*DI);
781
0
            else
782
0
              break;
783
0
784
0
            ++DI;
785
0
          } while (DI != DIEnd);
786
0
          RewriteForwardProtocolDecl(DG);
787
0
          continue;
788
0
        }
789
31
      }
790
31
791
31
      HandleTopLevelSingleDecl(*DI);
792
31
      ++DI;
793
31
    }
794
25
  }
795
541
  // If we have a decl in the main file, see if we should rewrite it.
796
541
  if (SM->isWrittenInMainFile(Loc))
797
541
    return HandleDeclInMainFile(D);
798
541
}
799
800
//===----------------------------------------------------------------------===//
801
// Syntactic (non-AST) Rewriting Code
802
//===----------------------------------------------------------------------===//
803
804
78
void RewriteModernObjC::RewriteInclude() {
805
78
  SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
806
78
  StringRef MainBuf = SM->getBufferData(MainFileID);
807
78
  const char *MainBufStart = MainBuf.begin();
808
78
  const char *MainBufEnd = MainBuf.end();
809
78
  size_t ImportLen = strlen("import");
810
78
811
78
  // Loop over the whole file, looking for includes.
812
80.3k
  for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; 
++BufPtr80.3k
) {
813
80.3k
    if (*BufPtr == '#') {
814
182
      if (++BufPtr == MainBufEnd)
815
0
        return;
816
354
      
while (182
*BufPtr == ' ' ||
*BufPtr == '\t'182
)
817
172
        if (++BufPtr == MainBufEnd)
818
0
          return;
819
182
      if (!strncmp(BufPtr, "import", ImportLen)) {
820
0
        // replace import with include
821
0
        SourceLocation ImportLoc =
822
0
          LocStart.getLocWithOffset(BufPtr-MainBufStart);
823
0
        ReplaceText(ImportLoc, ImportLen, "include");
824
0
        BufPtr += ImportLen;
825
0
      }
826
182
    }
827
80.3k
  }
828
78
}
829
830
static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
831
438
                                  ObjCIvarDecl *IvarDecl, std::string &Result) {
832
438
  Result += "OBJC_IVAR_$_";
833
438
  Result += IDecl->getName();
834
438
  Result += "$";
835
438
  Result += IvarDecl->getName();
836
438
}
837
838
std::string
839
30
RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
840
30
  const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
841
30
842
30
  // Build name of symbol holding ivar offset.
843
30
  std::string IvarOffsetName;
844
30
  if (D->isBitField())
845
4
    ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
846
26
  else
847
26
    WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
848
30
849
30
  std::string S = "(*(";
850
30
  QualType IvarT = D->getType();
851
30
  if (D->isBitField())
852
4
    IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
853
30
854
30
  if (!isa<TypedefType>(IvarT) && 
IvarT->isRecordType()23
) {
855
4
    RecordDecl *RD = IvarT->castAs<RecordType>()->getDecl();
856
4
    RD = RD->getDefinition();
857
4
    if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
858
0
      // decltype(((Foo_IMPL*)0)->bar) *
859
0
      auto *CDecl = cast<ObjCContainerDecl>(D->getDeclContext());
860
0
      // ivar in class extensions requires special treatment.
861
0
      if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
862
0
        CDecl = CatDecl->getClassInterface();
863
0
      std::string RecName = std::string(CDecl->getName());
864
0
      RecName += "_IMPL";
865
0
      RecordDecl *RD =
866
0
          RecordDecl::Create(*Context, TTK_Struct, TUDecl, SourceLocation(),
867
0
                             SourceLocation(), &Context->Idents.get(RecName));
868
0
      QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
869
0
      unsigned UnsignedIntSize =
870
0
      static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
871
0
      Expr *Zero = IntegerLiteral::Create(*Context,
872
0
                                          llvm::APInt(UnsignedIntSize, 0),
873
0
                                          Context->UnsignedIntTy, SourceLocation());
874
0
      Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
875
0
      ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
876
0
                                              Zero);
877
0
      FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
878
0
                                        SourceLocation(),
879
0
                                        &Context->Idents.get(D->getNameAsString()),
880
0
                                        IvarT, nullptr,
881
0
                                        /*BitWidth=*/nullptr, /*Mutable=*/true,
882
0
                                        ICIS_NoInit);
883
0
      MemberExpr *ME = MemberExpr::CreateImplicit(
884
0
          *Context, PE, true, FD, FD->getType(), VK_LValue, OK_Ordinary);
885
0
      IvarT = Context->getDecltypeType(ME, ME->getType());
886
0
    }
887
4
  }
888
30
  convertObjCTypeToCStyleType(IvarT);
889
30
  QualType castT = Context->getPointerType(IvarT);
890
30
  std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
891
30
  S += TypeString;
892
30
  S += ")";
893
30
894
30
  // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
895
30
  S += "((char *)self + ";
896
30
  S += IvarOffsetName;
897
30
  S += "))";
898
30
  if (D->isBitField()) {
899
4
    S += ".";
900
4
    S += D->getNameAsString();
901
4
  }
902
30
  ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
903
30
  return S;
904
30
}
905
906
/// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
907
/// been found in the class implementation. In this case, it must be synthesized.
908
static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
909
                                             ObjCPropertyDecl *PD,
910
104
                                             bool getter) {
911
104
  auto *OMD = IMP->getInstanceMethod(getter ? 
PD->getGetterName()56
912
104
                                            : 
PD->getSetterName()48
);
913
104
  return !OMD || OMD->isSynthesizedAccessorStub();
914
104
}
915
916
void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
917
                                          ObjCImplementationDecl *IMD,
918
31
                                          ObjCCategoryImplDecl *CID) {
919
31
  static bool objcGetPropertyDefined = false;
920
31
  static bool objcSetPropertyDefined = false;
921
31
  SourceLocation startGetterSetterLoc;
922
31
923
31
  if (PID->getBeginLoc().isValid()) {
924
23
    SourceLocation startLoc = PID->getBeginLoc();
925
23
    InsertText(startLoc, "// ");
926
23
    const char *startBuf = SM->getCharacterData(startLoc);
927
23
    assert((*startBuf == '@') && "bogus @synthesize location");
928
23
    const char *semiBuf = strchr(startBuf, ';');
929
23
    assert((*semiBuf == ';') && "@synthesize: can't find ';'");
930
23
    startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
931
23
  } else
932
8
    startGetterSetterLoc = IMD ? IMD->getEndLoc() : 
CID->getEndLoc()0
;
933
31
934
31
  if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
935
3
    return; // FIXME: is this correct?
936
28
937
28
  // Generate the 'getter' function.
938
28
  ObjCPropertyDecl *PD = PID->getPropertyDecl();
939
28
  ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
940
28
  assert(IMD && OID && "Synthesized ivars must be attached to @implementation");
941
28
942
28
  unsigned Attributes = PD->getPropertyAttributes();
943
28
  if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
944
26
    bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
945
26
                          (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
946
22
                                         ObjCPropertyDecl::OBJC_PR_copy));
947
26
    std::string Getr;
948
26
    if (GenGetProperty && 
!objcGetPropertyDefined9
) {
949
5
      objcGetPropertyDefined = true;
950
5
      // FIXME. Is this attribute correct in all cases?
951
5
      Getr = "\nextern \"C\" __declspec(dllimport) "
952
5
            "id objc_getProperty(id, SEL, long, bool);\n";
953
5
    }
954
26
    RewriteObjCMethodDecl(OID->getContainingInterface(),
955
26
                          PID->getGetterMethodDecl(), Getr);
956
26
    Getr += "{ ";
957
26
    // Synthesize an explicit cast to gain access to the ivar.
958
26
    // See objc-act.c:objc_synthesize_new_getter() for details.
959
26
    if (GenGetProperty) {
960
9
      // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
961
9
      Getr += "typedef ";
962
9
      const FunctionType *FPRetType = nullptr;
963
9
      RewriteTypeIntoString(PID->getGetterMethodDecl()->getReturnType(), Getr,
964
9
                            FPRetType);
965
9
      Getr += " _TYPE";
966
9
      if (FPRetType) {
967
1
        Getr += ")"; // close the precedence "scope" for "*".
968
1
969
1
        // Now, emit the argument types (if any).
970
1
        if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
971
1
          Getr += "(";
972
1
          for (unsigned i = 0, e = FT->getNumParams(); i != e; 
++i0
) {
973
0
            if (i) Getr += ", ";
974
0
            std::string ParamStr =
975
0
                FT->getParamType(i).getAsString(Context->getPrintingPolicy());
976
0
            Getr += ParamStr;
977
0
          }
978
1
          if (FT->isVariadic()) {
979
0
            if (FT->getNumParams())
980
0
              Getr += ", ";
981
0
            Getr += "...";
982
0
          }
983
1
          Getr += ")";
984
1
        } else
985
0
          Getr += "()";
986
1
      }
987
9
      Getr += ";\n";
988
9
      Getr += "return (_TYPE)";
989
9
      Getr += "objc_getProperty(self, _cmd, ";
990
9
      RewriteIvarOffsetComputation(OID, Getr);
991
9
      Getr += ", 1)";
992
9
    }
993
17
    else
994
17
      Getr += "return " + getIvarAccessString(OID);
995
26
    Getr += "; }";
996
26
    InsertText(startGetterSetterLoc, Getr);
997
26
  }
998
28
999
28
  if (PD->isReadOnly() ||
1000
28
      
!mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/)24
)
1001
6
    return;
1002
22
1003
22
  // Generate the 'setter' function.
1004
22
  std::string Setr;
1005
22
  bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
1006
22
                                      ObjCPropertyDecl::OBJC_PR_copy);
1007
22
  if (GenSetProperty && 
!objcSetPropertyDefined9
) {
1008
6
    objcSetPropertyDefined = true;
1009
6
    // FIXME. Is this attribute correct in all cases?
1010
6
    Setr = "\nextern \"C\" __declspec(dllimport) "
1011
6
    "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
1012
6
  }
1013
22
1014
22
  RewriteObjCMethodDecl(OID->getContainingInterface(),
1015
22
                        PID->getSetterMethodDecl(), Setr);
1016
22
  Setr += "{ ";
1017
22
  // Synthesize an explicit cast to initialize the ivar.
1018
22
  // See objc-act.c:objc_synthesize_new_setter() for details.
1019
22
  if (GenSetProperty) {
1020
9
    Setr += "objc_setProperty (self, _cmd, ";
1021
9
    RewriteIvarOffsetComputation(OID, Setr);
1022
9
    Setr += ", (id)";
1023
9
    Setr += PD->getName();
1024
9
    Setr += ", ";
1025
9
    if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
1026
2
      Setr += "0, ";
1027
7
    else
1028
7
      Setr += "1, ";
1029
9
    if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
1030
4
      Setr += "1)";
1031
5
    else
1032
5
      Setr += "0)";
1033
9
  }
1034
13
  else {
1035
13
    Setr += getIvarAccessString(OID) + " = ";
1036
13
    Setr += PD->getName();
1037
13
  }
1038
22
  Setr += "; }\n";
1039
22
  InsertText(startGetterSetterLoc, Setr);
1040
22
}
1041
1042
static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
1043
181
                                       std::string &typedefString) {
1044
181
  typedefString += "\n#ifndef _REWRITER_typedef_";
1045
181
  typedefString += ForwardDecl->getNameAsString();
1046
181
  typedefString += "\n";
1047
181
  typedefString += "#define _REWRITER_typedef_";
1048
181
  typedefString += ForwardDecl->getNameAsString();
1049
181
  typedefString += "\n";
1050
181
  typedefString += "typedef struct objc_object ";
1051
181
  typedefString += ForwardDecl->getNameAsString();
1052
181
  // typedef struct { } _objc_exc_Classname;
1053
181
  typedefString += ";\ntypedef struct {} _objc_exc_";
1054
181
  typedefString += ForwardDecl->getNameAsString();
1055
181
  typedefString += ";\n#endif\n";
1056
181
}
1057
1058
void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
1059
16
                                              const std::string &typedefString) {
1060
16
  SourceLocation startLoc = ClassDecl->getBeginLoc();
1061
16
  const char *startBuf = SM->getCharacterData(startLoc);
1062
16
  const char *semiPtr = strchr(startBuf, ';');
1063
16
  // Replace the @class with typedefs corresponding to the classes.
1064
16
  ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
1065
16
}
1066
1067
11
void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
1068
11
  std::string typedefString;
1069
26
  for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; 
++I15
) {
1070
15
    if (ObjCInterfaceDecl *ForwardDecl = dyn_cast<ObjCInterfaceDecl>(*I)) {
1071
13
      if (I == D.begin()) {
1072
11
        // Translate to typedef's that forward reference structs with the same name
1073
11
        // as the class. As a convenience, we include the original declaration
1074
11
        // as a comment.
1075
11
        typedefString += "// @class ";
1076
11
        typedefString += ForwardDecl->getNameAsString();
1077
11
        typedefString += ";";
1078
11
      }
1079
13
      RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1080
13
    }
1081
2
    else
1082
2
      HandleTopLevelSingleDecl(*I);
1083
15
  }
1084
11
  DeclGroupRef::iterator I = D.begin();
1085
11
  RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
1086
11
}
1087
1088
void RewriteModernObjC::RewriteForwardClassDecl(
1089
5
                                const SmallVectorImpl<Decl *> &D) {
1090
5
  std::string typedefString;
1091
21
  for (unsigned i = 0; i < D.size(); 
i++16
) {
1092
16
    ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
1093
16
    if (i == 0) {
1094
5
      typedefString += "// @class ";
1095
5
      typedefString += ForwardDecl->getNameAsString();
1096
5
      typedefString += ";";
1097
5
    }
1098
16
    RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1099
16
  }
1100
5
  RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
1101
5
}
1102
1103
210
void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
1104
210
  // When method is a synthesized one, such as a getter/setter there is
1105
210
  // nothing to rewrite.
1106
210
  if (Method->isImplicit())
1107
68
    return;
1108
142
  SourceLocation LocStart = Method->getBeginLoc();
1109
142
  SourceLocation LocEnd = Method->getEndLoc();
1110
142
1111
142
  if (SM->getExpansionLineNumber(LocEnd) >
1112
142
      SM->getExpansionLineNumber(LocStart)) {
1113
0
    InsertText(LocStart, "#if 0\n");
1114
0
    ReplaceText(LocEnd, 1, ";\n#endif\n");
1115
142
  } else {
1116
142
    InsertText(LocStart, "// ");
1117
142
  }
1118
142
}
1119
1120
37
void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
1121
37
  SourceLocation Loc = prop->getAtLoc();
1122
37
1123
37
  ReplaceText(Loc, 0, "// ");
1124
37
  // FIXME: handle properties that are declared across multiple lines.
1125
37
}
1126
1127
14
void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
1128
14
  SourceLocation LocStart = CatDecl->getBeginLoc();
1129
14
1130
14
  // FIXME: handle category headers that are declared across multiple lines.
1131
14
  if (CatDecl->getIvarRBraceLoc().isValid()) {
1132
8
    ReplaceText(LocStart, 1, "/** ");
1133
8
    ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1134
8
  }
1135
6
  else {
1136
6
    ReplaceText(LocStart, 0, "// ");
1137
6
  }
1138
14
1139
14
  for (auto *I : CatDecl->instance_properties())
1140
4
    RewriteProperty(I);
1141
14
1142
14
  for (auto *I : CatDecl->instance_methods())
1143
8
    RewriteMethodDeclaration(I);
1144
14
  for (auto *I : CatDecl->class_methods())
1145
0
    RewriteMethodDeclaration(I);
1146
14
1147
14
  // Lastly, comment out the @end.
1148
14
  ReplaceText(CatDecl->getAtEndRange().getBegin(),
1149
14
              strlen("@end"), "/* @end */\n");
1150
14
}
1151
1152
16
void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1153
16
  SourceLocation LocStart = PDecl->getBeginLoc();
1154
16
  assert(PDecl->isThisDeclarationADefinition());
1155
16
1156
16
  // FIXME: handle protocol headers that are declared across multiple lines.
1157
16
  ReplaceText(LocStart, 0, "// ");
1158
16
1159
16
  for (auto *I : PDecl->instance_methods())
1160
11
    RewriteMethodDeclaration(I);
1161
16
  for (auto *I : PDecl->class_methods())
1162
3
    RewriteMethodDeclaration(I);
1163
16
  for (auto *I : PDecl->instance_properties())
1164
2
    RewriteProperty(I);
1165
16
1166
16
  // Lastly, comment out the @end.
1167
16
  SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1168
16
  ReplaceText(LocEnd, strlen("@end"), "/* @end */\n");
1169
16
1170
16
  // Must comment out @optional/@required
1171
16
  const char *startBuf = SM->getCharacterData(LocStart);
1172
16
  const char *endBuf = SM->getCharacterData(LocEnd);
1173
933
  for (const char *p = startBuf; p < endBuf; 
p++917
) {
1174
917
    if (*p == '@' && 
!strncmp(p+1, "optional", strlen("optional"))23
) {
1175
4
      SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1176
4
      ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1177
4
1178
4
    }
1179
913
    else if (*p == '@' && 
!strncmp(p+1, "required", strlen("required"))19
) {
1180
1
      SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1181
1
      ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1182
1
1183
1
    }
1184
917
  }
1185
16
}
1186
1187
2
void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1188
2
  SourceLocation LocStart = (*D.begin())->getBeginLoc();
1189
2
  if (LocStart.isInvalid())
1190
2
    
llvm_unreachable0
("Invalid SourceLocation");
1191
2
  // FIXME: handle forward protocol that are declared across multiple lines.
1192
2
  ReplaceText(LocStart, 0, "// ");
1193
2
}
1194
1195
void
1196
0
RewriteModernObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
1197
0
  SourceLocation LocStart = DG[0]->getBeginLoc();
1198
0
  if (LocStart.isInvalid())
1199
0
    llvm_unreachable("Invalid SourceLocation");
1200
0
  // FIXME: handle forward protocol that are declared across multiple lines.
1201
0
  ReplaceText(LocStart, 0, "// ");
1202
0
}
1203
1204
void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1205
122
                                        const FunctionType *&FPRetType) {
1206
122
  if (T->isObjCQualifiedIdType())
1207
0
    ResultStr += "id";
1208
122
  else if (T->isFunctionPointerType() ||
1209
122
           T->isBlockPointerType()) {
1210
4
    // needs special handling, since pointer-to-functions have special
1211
4
    // syntax (where a decaration models use).
1212
4
    QualType retType = T;
1213
4
    QualType PointeeTy;
1214
4
    if (const PointerType* PT = retType->getAs<PointerType>())
1215
0
      PointeeTy = PT->getPointeeType();
1216
4
    else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1217
4
      PointeeTy = BPT->getPointeeType();
1218
4
    if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1219
4
      ResultStr +=
1220
4
          FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
1221
4
      ResultStr += "(*";
1222
4
    }
1223
4
  } else
1224
118
    ResultStr += T.getAsString(Context->getPrintingPolicy());
1225
122
}
1226
1227
void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1228
                                        ObjCMethodDecl *OMD,
1229
113
                                        std::string &ResultStr) {
1230
113
  //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1231
113
  const FunctionType *FPRetType = nullptr;
1232
113
  ResultStr += "\nstatic ";
1233
113
  RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
1234
113
  ResultStr += " ";
1235
113
1236
113
  // Unique method name
1237
113
  std::string NameStr;
1238
113
1239
113
  if (OMD->isInstanceMethod())
1240
104
    NameStr += "_I_";
1241
9
  else
1242
9
    NameStr += "_C_";
1243
113
1244
113
  NameStr += IDecl->getNameAsString();
1245
113
  NameStr += "_";
1246
113
1247
113
  if (ObjCCategoryImplDecl *CID =
1248
0
      dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1249
0
    NameStr += CID->getNameAsString();
1250
0
    NameStr += "_";
1251
0
  }
1252
113
  // Append selector names, replacing ':' with '_'
1253
113
  {
1254
113
    std::string selString = OMD->getSelector().getAsString();
1255
113
    int len = selString.size();
1256
1.00k
    for (int i = 0; i < len; 
i++894
)
1257
894
      if (selString[i] == ':')
1258
48
        selString[i] = '_';
1259
113
    NameStr += selString;
1260
113
  }
1261
113
  // Remember this name for metadata emission
1262
113
  MethodInternalNames[OMD] = NameStr;
1263
113
  ResultStr += NameStr;
1264
113
1265
113
  // Rewrite arguments
1266
113
  ResultStr += "(";
1267
113
1268
113
  // invisible arguments
1269
113
  if (OMD->isInstanceMethod()) {
1270
104
    QualType selfTy = Context->getObjCInterfaceType(IDecl);
1271
104
    selfTy = Context->getPointerType(selfTy);
1272
104
    if (!LangOpts.MicrosoftExt) {
1273
0
      if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1274
0
        ResultStr += "struct ";
1275
0
    }
1276
104
    // When rewriting for Microsoft, explicitly omit the structure name.
1277
104
    ResultStr += IDecl->getNameAsString();
1278
104
    ResultStr += " *";
1279
104
  }
1280
9
  else
1281
9
    ResultStr += Context->getObjCClassType().getAsString(
1282
9
      Context->getPrintingPolicy());
1283
113
1284
113
  ResultStr += " self, ";
1285
113
  ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1286
113
  ResultStr += " _cmd";
1287
113
1288
113
  // Method arguments.
1289
113
  for (const auto *PDecl : OMD->parameters()) {
1290
48
    ResultStr += ", ";
1291
48
    if (PDecl->getType()->isObjCQualifiedIdType()) {
1292
0
      ResultStr += "id ";
1293
0
      ResultStr += PDecl->getNameAsString();
1294
48
    } else {
1295
48
      std::string Name = PDecl->getNameAsString();
1296
48
      QualType QT = PDecl->getType();
1297
48
      // Make sure we convert "t (^)(...)" to "t (*)(...)".
1298
48
      (void)convertBlockPointerToFunctionPointer(QT);
1299
48
      QT.getAsStringInternal(Name, Context->getPrintingPolicy());
1300
48
      ResultStr += Name;
1301
48
    }
1302
48
  }
1303
113
  if (OMD->isVariadic())
1304
0
    ResultStr += ", ...";
1305
113
  ResultStr += ") ";
1306
113
1307
113
  if (FPRetType) {
1308
3
    ResultStr += ")"; // close the precedence "scope" for "*".
1309
3
1310
3
    // Now, emit the argument types (if any).
1311
3
    if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1312
3
      ResultStr += "(";
1313
3
      for (unsigned i = 0, e = FT->getNumParams(); i != e; 
++i0
) {
1314
0
        if (i) ResultStr += ", ";
1315
0
        std::string ParamStr =
1316
0
            FT->getParamType(i).getAsString(Context->getPrintingPolicy());
1317
0
        ResultStr += ParamStr;
1318
0
      }
1319
3
      if (FT->isVariadic()) {
1320
0
        if (FT->getNumParams())
1321
0
          ResultStr += ", ";
1322
0
        ResultStr += "...";
1323
0
      }
1324
3
      ResultStr += ")";
1325
3
    } else {
1326
0
      ResultStr += "()";
1327
0
    }
1328
3
  }
1329
113
}
1330
1331
93
void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1332
93
  ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1333
93
  ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1334
93
  assert((IMD || CID) && "Unknown implementation type");
1335
93
1336
93
  if (IMD) {
1337
88
    if (IMD->getIvarRBraceLoc().isValid()) {
1338
3
      ReplaceText(IMD->getBeginLoc(), 1, "/** ");
1339
3
      ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
1340
3
    }
1341
85
    else {
1342
85
      InsertText(IMD->getBeginLoc(), "// ");
1343
85
    }
1344
88
  }
1345
5
  else
1346
5
    InsertText(CID->getBeginLoc(), "// ");
1347
93
1348
104
  for (auto *OMD : IMD ? 
IMD->instance_methods()88
:
CID->instance_methods()5
) {
1349
104
    if (!OMD->getBody())
1350
48
      continue;
1351
56
    std::string ResultStr;
1352
56
    RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1353
56
    SourceLocation LocStart = OMD->getBeginLoc();
1354
56
    SourceLocation LocEnd = OMD->getCompoundBody()->getBeginLoc();
1355
56
1356
56
    const char *startBuf = SM->getCharacterData(LocStart);
1357
56
    const char *endBuf = SM->getCharacterData(LocEnd);
1358
56
    ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1359
56
  }
1360
93
1361
93
  for (auto *OMD : IMD ? 
IMD->class_methods()88
:
CID->class_methods()5
) {
1362
9
    if (!OMD->getBody())
1363
0
      continue;
1364
9
    std::string ResultStr;
1365
9
    RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1366
9
    SourceLocation LocStart = OMD->getBeginLoc();
1367
9
    SourceLocation LocEnd = OMD->getCompoundBody()->getBeginLoc();
1368
9
1369
9
    const char *startBuf = SM->getCharacterData(LocStart);
1370
9
    const char *endBuf = SM->getCharacterData(LocEnd);
1371
9
    ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1372
9
  }
1373
93
  for (auto *I : IMD ? 
IMD->property_impls()88
:
CID->property_impls()5
)
1374
31
    RewritePropertyImplDecl(I, IMD, CID);
1375
93
1376
93
  InsertText(IMD ? 
IMD->getEndLoc()88
:
CID->getEndLoc()5
, "// ");
1377
93
}
1378
1379
183
void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
1380
183
  // Do not synthesize more than once.
1381
183
  if (ObjCSynthesizedStructs.count(ClassDecl))
1382
9
    return;
1383
174
  // Make sure super class's are written before current class is written.
1384
174
  ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1385
205
  while (SuperClass) {
1386
31
    RewriteInterfaceDecl(SuperClass);
1387
31
    SuperClass = SuperClass->getSuperClass();
1388
31
  }
1389
174
  std::string ResultStr;
1390
174
  if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
1391
152
    // we haven't seen a forward decl - generate a typedef.
1392
152
    RewriteOneForwardClassDecl(ClassDecl, ResultStr);
1393
152
    RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1394
152
1395
152
    RewriteObjCInternalStruct(ClassDecl, ResultStr);
1396
152
    // Mark this typedef as having been written into its c++ equivalent.
1397
152
    ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
1398
152
1399
152
    for (auto *I : ClassDecl->instance_properties())
1400
31
      RewriteProperty(I);
1401
152
    for (auto *I : ClassDecl->instance_methods())
1402
108
      RewriteMethodDeclaration(I);
1403
152
    for (auto *I : ClassDecl->class_methods())
1404
80
      RewriteMethodDeclaration(I);
1405
152
1406
152
    // Lastly, comment out the @end.
1407
152
    ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1408
152
                "/* @end */\n");
1409
152
  }
1410
174
}
1411
1412
13
Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1413
13
  SourceRange OldRange = PseudoOp->getSourceRange();
1414
13
1415
13
  // We just magically know some things about the structure of this
1416
13
  // expression.
1417
13
  ObjCMessageExpr *OldMsg =
1418
13
    cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1419
13
                            PseudoOp->getNumSemanticExprs() - 1));
1420
13
1421
13
  // Because the rewriter doesn't allow us to rewrite rewritten code,
1422
13
  // we need to suppress rewriting the sub-statements.
1423
13
  Expr *Base;
1424
13
  SmallVector<Expr*, 2> Args;
1425
13
  {
1426
13
    DisableReplaceStmtScope S(*this);
1427
13
1428
13
    // Rebuild the base expression if we have one.
1429
13
    Base = nullptr;
1430
13
    if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1431
13
      Base = OldMsg->getInstanceReceiver();
1432
13
      Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1433
13
      Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1434
13
    }
1435
13
1436
13
    unsigned numArgs = OldMsg->getNumArgs();
1437
29
    for (unsigned i = 0; i < numArgs; 
i++16
) {
1438
16
      Expr *Arg = OldMsg->getArg(i);
1439
16
      if (isa<OpaqueValueExpr>(Arg))
1440
13
        Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1441
16
      Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1442
16
      Args.push_back(Arg);
1443
16
    }
1444
13
  }
1445
13
1446
13
  // TODO: avoid this copy.
1447
13
  SmallVector<SourceLocation, 1> SelLocs;
1448
13
  OldMsg->getSelectorLocs(SelLocs);
1449
13
1450
13
  ObjCMessageExpr *NewMsg = nullptr;
1451
13
  switch (OldMsg->getReceiverKind()) {
1452
0
  case ObjCMessageExpr::Class:
1453
0
    NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1454
0
                                     OldMsg->getValueKind(),
1455
0
                                     OldMsg->getLeftLoc(),
1456
0
                                     OldMsg->getClassReceiverTypeInfo(),
1457
0
                                     OldMsg->getSelector(),
1458
0
                                     SelLocs,
1459
0
                                     OldMsg->getMethodDecl(),
1460
0
                                     Args,
1461
0
                                     OldMsg->getRightLoc(),
1462
0
                                     OldMsg->isImplicit());
1463
0
    break;
1464
0
1465
13
  case ObjCMessageExpr::Instance:
1466
13
    NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1467
13
                                     OldMsg->getValueKind(),
1468
13
                                     OldMsg->getLeftLoc(),
1469
13
                                     Base,
1470
13
                                     OldMsg->getSelector(),
1471
13
                                     SelLocs,
1472
13
                                     OldMsg->getMethodDecl(),
1473
13
                                     Args,
1474
13
                                     OldMsg->getRightLoc(),
1475
13
                                     OldMsg->isImplicit());
1476
13
    break;
1477
0
1478
0
  case ObjCMessageExpr::SuperClass:
1479
0
  case ObjCMessageExpr::SuperInstance:
1480
0
    NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1481
0
                                     OldMsg->getValueKind(),
1482
0
                                     OldMsg->getLeftLoc(),
1483
0
                                     OldMsg->getSuperLoc(),
1484
0
                 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1485
0
                                     OldMsg->getSuperType(),
1486
0
                                     OldMsg->getSelector(),
1487
0
                                     SelLocs,
1488
0
                                     OldMsg->getMethodDecl(),
1489
0
                                     Args,
1490
0
                                     OldMsg->getRightLoc(),
1491
0
                                     OldMsg->isImplicit());
1492
0
    break;
1493
13
  }
1494
13
1495
13
  Stmt *Replacement = SynthMessageExpr(NewMsg);
1496
13
  ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1497
13
  return Replacement;
1498
13
}
1499
1500
20
Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1501
20
  SourceRange OldRange = PseudoOp->getSourceRange();
1502
20
1503
20
  // We just magically know some things about the structure of this
1504
20
  // expression.
1505
20
  ObjCMessageExpr *OldMsg =
1506
20
    cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1507
20
1508
20
  // Because the rewriter doesn't allow us to rewrite rewritten code,
1509
20
  // we need to suppress rewriting the sub-statements.
1510
20
  Expr *Base = nullptr;
1511
20
  SmallVector<Expr*, 1> Args;
1512
20
  {
1513
20
    DisableReplaceStmtScope S(*this);
1514
20
    // Rebuild the base expression if we have one.
1515
20
    if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1516
20
      Base = OldMsg->getInstanceReceiver();
1517
20
      Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1518
20
      Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1519
20
    }
1520
20
    unsigned numArgs = OldMsg->getNumArgs();
1521
23
    for (unsigned i = 0; i < numArgs; 
i++3
) {
1522
3
      Expr *Arg = OldMsg->getArg(i);
1523
3
      if (isa<OpaqueValueExpr>(Arg))
1524
0
        Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1525
3
      Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1526
3
      Args.push_back(Arg);
1527
3
    }
1528
20
  }
1529
20
1530
20
  // Intentionally empty.
1531
20
  SmallVector<SourceLocation, 1> SelLocs;
1532
20
1533
20
  ObjCMessageExpr *NewMsg = nullptr;
1534
20
  switch (OldMsg->getReceiverKind()) {
1535
0
  case ObjCMessageExpr::Class:
1536
0
    NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1537
0
                                     OldMsg->getValueKind(),
1538
0
                                     OldMsg->getLeftLoc(),
1539
0
                                     OldMsg->getClassReceiverTypeInfo(),
1540
0
                                     OldMsg->getSelector(),
1541
0
                                     SelLocs,
1542
0
                                     OldMsg->getMethodDecl(),
1543
0
                                     Args,
1544
0
                                     OldMsg->getRightLoc(),
1545
0
                                     OldMsg->isImplicit());
1546
0
    break;
1547
0
1548
20
  case ObjCMessageExpr::Instance:
1549
20
    NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1550
20
                                     OldMsg->getValueKind(),
1551
20
                                     OldMsg->getLeftLoc(),
1552
20
                                     Base,
1553
20
                                     OldMsg->getSelector(),
1554
20
                                     SelLocs,
1555
20
                                     OldMsg->getMethodDecl(),
1556
20
                                     Args,
1557
20
                                     OldMsg->getRightLoc(),
1558
20
                                     OldMsg->isImplicit());
1559
20
    break;
1560
0
1561
0
  case ObjCMessageExpr::SuperClass:
1562
0
  case ObjCMessageExpr::SuperInstance:
1563
0
    NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1564
0
                                     OldMsg->getValueKind(),
1565
0
                                     OldMsg->getLeftLoc(),
1566
0
                                     OldMsg->getSuperLoc(),
1567
0
                 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1568
0
                                     OldMsg->getSuperType(),
1569
0
                                     OldMsg->getSelector(),
1570
0
                                     SelLocs,
1571
0
                                     OldMsg->getMethodDecl(),
1572
0
                                     Args,
1573
0
                                     OldMsg->getRightLoc(),
1574
0
                                     OldMsg->isImplicit());
1575
0
    break;
1576
20
  }
1577
20
1578
20
  Stmt *Replacement = SynthMessageExpr(NewMsg);
1579
20
  ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1580
20
  return Replacement;
1581
20
}
1582
1583
/// SynthCountByEnumWithState - To print:
1584
/// ((NSUInteger (*)
1585
///  (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
1586
///  (void *)objc_msgSend)((id)l_collection,
1587
///                        sel_registerName(
1588
///                          "countByEnumeratingWithState:objects:count:"),
1589
///                        &enumState,
1590
///                        (id *)__rw_items, (NSUInteger)16)
1591
///
1592
10
void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1593
10
  buf += "((_WIN_NSUInteger (*) (id, SEL, struct __objcFastEnumerationState *, "
1594
10
  "id *, _WIN_NSUInteger))(void *)objc_msgSend)";
1595
10
  buf += "\n\t\t";
1596
10
  buf += "((id)l_collection,\n\t\t";
1597
10
  buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1598
10
  buf += "\n\t\t";
1599
10
  buf += "&enumState, "
1600
10
         "(id *)__rw_items, (_WIN_NSUInteger)16)";
1601
10
}
1602
1603
/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1604
/// statement to exit to its outer synthesized loop.
1605
///
1606
5
Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1607
5
  if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1608
5
    return S;
1609
0
  // replace break with goto __break_label
1610
0
  std::string buf;
1611
0
1612
0
  SourceLocation startLoc = S->getBeginLoc();
1613
0
  buf = "goto __break_label_";
1614
0
  buf += utostr(ObjCBcLabelNo.back());
1615
0
  ReplaceText(startLoc, strlen("break"), buf);
1616
0
1617
0
  return nullptr;
1618
0
}
1619
1620
void RewriteModernObjC::ConvertSourceLocationToLineDirective(
1621
                                          SourceLocation Loc,
1622
117
                                          std::string &LineString) {
1623
117
  if (Loc.isFileID() && GenerateLineInfo) {
1624
1
    LineString += "\n#line ";
1625
1
    PresumedLoc PLoc = SM->getPresumedLoc(Loc);
1626
1
    LineString += utostr(PLoc.getLine());
1627
1
    LineString += " \"";
1628
1
    LineString += Lexer::Stringify(PLoc.getFilename());
1629
1
    LineString += "\"\n";
1630
1
  }
1631
117
}
1632
1633
/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1634
/// statement to continue with its inner synthesized loop.
1635
///
1636
0
Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1637
0
  if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1638
0
    return S;
1639
0
  // replace continue with goto __continue_label
1640
0
  std::string buf;
1641
0
1642
0
  SourceLocation startLoc = S->getBeginLoc();
1643
0
  buf = "goto __continue_label_";
1644
0
  buf += utostr(ObjCBcLabelNo.back());
1645
0
  ReplaceText(startLoc, strlen("continue"), buf);
1646
0
1647
0
  return nullptr;
1648
0
}
1649
1650
/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1651
///  It rewrites:
1652
/// for ( type elem in collection) { stmts; }
1653
1654
/// Into:
1655
/// {
1656
///   type elem;
1657
///   struct __objcFastEnumerationState enumState = { 0 };
1658
///   id __rw_items[16];
1659
///   id l_collection = (id)collection;
1660
///   NSUInteger limit = [l_collection countByEnumeratingWithState:&enumState
1661
///                                       objects:__rw_items count:16];
1662
/// if (limit) {
1663
///   unsigned long startMutations = *enumState.mutationsPtr;
1664
///   do {
1665
///        unsigned long counter = 0;
1666
///        do {
1667
///             if (startMutations != *enumState.mutationsPtr)
1668
///               objc_enumerationMutation(l_collection);
1669
///             elem = (type)enumState.itemsPtr[counter++];
1670
///             stmts;
1671
///             __continue_label: ;
1672
///        } while (counter < limit);
1673
///   } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1674
///                                  objects:__rw_items count:16]));
1675
///   elem = nil;
1676
///   __break_label: ;
1677
///  }
1678
///  else
1679
///       elem = nil;
1680
///  }
1681
///
1682
Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1683
5
                                                SourceLocation OrigEnd) {
1684
5
  assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1685
5
  assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1686
5
         "ObjCForCollectionStmt Statement stack mismatch");
1687
5
  assert(!ObjCBcLabelNo.empty() &&
1688
5
         "ObjCForCollectionStmt - Label No stack empty");
1689
5
1690
5
  SourceLocation startLoc = S->getBeginLoc();
1691
5
  const char *startBuf = SM->getCharacterData(startLoc);
1692
5
  StringRef elementName;
1693
5
  std::string elementTypeAsString;
1694
5
  std::string buf;
1695
5
  // line directive first.
1696
5
  SourceLocation ForEachLoc = S->getForLoc();
1697
5
  ConvertSourceLocationToLineDirective(ForEachLoc, buf);
1698
5
  buf += "{\n\t";
1699
5
  if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1700
5
    // type elem;
1701
5
    NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1702
5
    QualType ElementType = cast<ValueDecl>(D)->getType();
1703
5
    if (ElementType->isObjCQualifiedIdType() ||
1704
5
        ElementType->isObjCQualifiedInterfaceType())
1705
0
      // Simply use 'id' for all qualified types.
1706
0
      elementTypeAsString = "id";
1707
5
    else
1708
5
      elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1709
5
    buf += elementTypeAsString;
1710
5
    buf += " ";
1711
5
    elementName = D->getName();
1712
5
    buf += elementName;
1713
5
    buf += ";\n\t";
1714
5
  }
1715
0
  else {
1716
0
    DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1717
0
    elementName = DR->getDecl()->getName();
1718
0
    ValueDecl *VD = DR->getDecl();
1719
0
    if (VD->getType()->isObjCQualifiedIdType() ||
1720
0
        VD->getType()->isObjCQualifiedInterfaceType())
1721
0
      // Simply use 'id' for all qualified types.
1722
0
      elementTypeAsString = "id";
1723
0
    else
1724
0
      elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1725
0
  }
1726
5
1727
5
  // struct __objcFastEnumerationState enumState = { 0 };
1728
5
  buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1729
5
  // id __rw_items[16];
1730
5
  buf += "id __rw_items[16];\n\t";
1731
5
  // id l_collection = (id)
1732
5
  buf += "id l_collection = (id)";
1733
5
  // Find start location of 'collection' the hard way!
1734
5
  const char *startCollectionBuf = startBuf;
1735
5
  startCollectionBuf += 3;  // skip 'for'
1736
5
  startCollectionBuf = strchr(startCollectionBuf, '(');
1737
5
  startCollectionBuf++; // skip '('
1738
5
  // find 'in' and skip it.
1739
33
  while (*startCollectionBuf != ' ' ||
1740
33
         
*(startCollectionBuf+1) != 'i'10
||
*(startCollectionBuf+2) != 'n'5
||
1741
33
         
(5
*(startCollectionBuf+3) != ' '5
&&
1742
5
          
*(startCollectionBuf+3) != '['0
&&
*(startCollectionBuf+3) != '('0
))
1743
28
    startCollectionBuf++;
1744
5
  startCollectionBuf += 3;
1745
5
1746
5
  // Replace: "for (type element in" with string constructed thus far.
1747
5
  ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1748
5
  // Replace ')' in for '(' type elem in collection ')' with ';'
1749
5
  SourceLocation rightParenLoc = S->getRParenLoc();
1750
5
  const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1751
5
  SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1752
5
  buf = ";\n\t";
1753
5
1754
5
  // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1755
5
  //                                   objects:__rw_items count:16];
1756
5
  // which is synthesized into:
1757
5
  // NSUInteger limit =
1758
5
  // ((NSUInteger (*)
1759
5
  //  (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
1760
5
  //  (void *)objc_msgSend)((id)l_collection,
1761
5
  //                        sel_registerName(
1762
5
  //                          "countByEnumeratingWithState:objects:count:"),
1763
5
  //                        (struct __objcFastEnumerationState *)&state,
1764
5
  //                        (id *)__rw_items, (NSUInteger)16);
1765
5
  buf += "_WIN_NSUInteger limit =\n\t\t";
1766
5
  SynthCountByEnumWithState(buf);
1767
5
  buf += ";\n\t";
1768
5
  /// if (limit) {
1769
5
  ///   unsigned long startMutations = *enumState.mutationsPtr;
1770
5
  ///   do {
1771
5
  ///        unsigned long counter = 0;
1772
5
  ///        do {
1773
5
  ///             if (startMutations != *enumState.mutationsPtr)
1774
5
  ///               objc_enumerationMutation(l_collection);
1775
5
  ///             elem = (type)enumState.itemsPtr[counter++];
1776
5
  buf += "if (limit) {\n\t";
1777
5
  buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1778
5
  buf += "do {\n\t\t";
1779
5
  buf += "unsigned long counter = 0;\n\t\t";
1780
5
  buf += "do {\n\t\t\t";
1781
5
  buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1782
5
  buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1783
5
  buf += elementName;
1784
5
  buf += " = (";
1785
5
  buf += elementTypeAsString;
1786
5
  buf += ")enumState.itemsPtr[counter++];";
1787
5
  // Replace ')' in for '(' type elem in collection ')' with all of these.
1788
5
  ReplaceText(lparenLoc, 1, buf);
1789
5
1790
5
  ///            __continue_label: ;
1791
5
  ///        } while (counter < limit);
1792
5
  ///   } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1793
5
  ///                                  objects:__rw_items count:16]));
1794
5
  ///   elem = nil;
1795
5
  ///   __break_label: ;
1796
5
  ///  }
1797
5
  ///  else
1798
5
  ///       elem = nil;
1799
5
  ///  }
1800
5
  ///
1801
5
  buf = ";\n\t";
1802
5
  buf += "__continue_label_";
1803
5
  buf += utostr(ObjCBcLabelNo.back());
1804
5
  buf += ": ;";
1805
5
  buf += "\n\t\t";
1806
5
  buf += "} while (counter < limit);\n\t";
1807
5
  buf += "} while ((limit = ";
1808
5
  SynthCountByEnumWithState(buf);
1809
5
  buf += "));\n\t";
1810
5
  buf += elementName;
1811
5
  buf += " = ((";
1812
5
  buf += elementTypeAsString;
1813
5
  buf += ")0);\n\t";
1814
5
  buf += "__break_label_";
1815
5
  buf += utostr(ObjCBcLabelNo.back());
1816
5
  buf += ": ;\n\t";
1817
5
  buf += "}\n\t";
1818
5
  buf += "else\n\t\t";
1819
5
  buf += elementName;
1820
5
  buf += " = ((";
1821
5
  buf += elementTypeAsString;
1822
5
  buf += ")0);\n\t";
1823
5
  buf += "}\n";
1824
5
1825
5
  // Insert all these *after* the statement body.
1826
5
  // FIXME: If this should support Obj-C++, support CXXTryStmt
1827
5
  if (isa<CompoundStmt>(S->getBody())) {
1828
5
    SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1829
5
    InsertText(endBodyLoc, buf);
1830
5
  } else {
1831
0
    /* Need to treat single statements specially. For example:
1832
0
     *
1833
0
     *     for (A *a in b) if (stuff()) break;
1834
0
     *     for (A *a in b) xxxyy;
1835
0
     *
1836
0
     * The following code simply scans ahead to the semi to find the actual end.
1837
0
     */
1838
0
    const char *stmtBuf = SM->getCharacterData(OrigEnd);
1839
0
    const char *semiBuf = strchr(stmtBuf, ';');
1840
0
    assert(semiBuf && "Can't find ';'");
1841
0
    SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1842
0
    InsertText(endBodyLoc, buf);
1843
0
  }
1844
5
  Stmts.pop_back();
1845
5
  ObjCBcLabelNo.pop_back();
1846
5
  return nullptr;
1847
5
}
1848
1849
12
static void Write_RethrowObject(std::string &buf) {
1850
12
  buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1851
12
  buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1852
12
  buf += "\tid rethrow;\n";
1853
12
  buf += "\t} _fin_force_rethow(_rethrow);";
1854
12
}
1855
1856
/// RewriteObjCSynchronizedStmt -
1857
/// This routine rewrites @synchronized(expr) stmt;
1858
/// into:
1859
/// objc_sync_enter(expr);
1860
/// @try stmt @finally { objc_sync_exit(expr); }
1861
///
1862
4
Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1863
4
  // Get the start location and compute the semi location.
1864
4
  SourceLocation startLoc = S->getBeginLoc();
1865
4
  const char *startBuf = SM->getCharacterData(startLoc);
1866
4
1867
4
  assert((*startBuf == '@') && "bogus @synchronized location");
1868
4
1869
4
  std::string buf;
1870
4
  SourceLocation SynchLoc = S->getAtSynchronizedLoc();
1871
4
  ConvertSourceLocationToLineDirective(SynchLoc, buf);
1872
4
  buf += "{ id _rethrow = 0; id _sync_obj = (id)";
1873
4
1874
4
  const char *lparenBuf = startBuf;
1875
59
  while (*lparenBuf != '(') 
lparenBuf++55
;
1876
4
  ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
1877
4
1878
4
  buf = "; objc_sync_enter(_sync_obj);\n";
1879
4
  buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1880
4
  buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1881
4
  buf += "\n\tid sync_exit;";
1882
4
  buf += "\n\t} _sync_exit(_sync_obj);\n";
1883
4
1884
4
  // We can't use S->getSynchExpr()->getEndLoc() to find the end location, since
1885
4
  // the sync expression is typically a message expression that's already
1886
4
  // been rewritten! (which implies the SourceLocation's are invalid).
1887
4
  SourceLocation RParenExprLoc = S->getSynchBody()->getBeginLoc();
1888
4
  const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1889
12
  while (*RParenExprLocBuf != ')') 
RParenExprLocBuf--8
;
1890
4
  RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1891
4
1892
4
  SourceLocation LBranceLoc = S->getSynchBody()->getBeginLoc();
1893
4
  const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1894
4
  assert (*LBraceLocBuf == '{');
1895
4
  ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
1896
4
1897
4
  SourceLocation startRBraceLoc = S->getSynchBody()->getEndLoc();
1898
4
  assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1899
4
         "bogus @synchronized block");
1900
4
1901
4
  buf = "} catch (id e) {_rethrow = e;}\n";
1902
4
  Write_RethrowObject(buf);
1903
4
  buf += "}\n";
1904
4
  buf += "}\n";
1905
4
1906
4
  ReplaceText(startRBraceLoc, 1, buf);
1907
4
1908
4
  return nullptr;
1909
4
}
1910
1911
void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1912
33
{
1913
33
  // Perform a bottom up traversal of all children.
1914
33
  for (Stmt *SubStmt : S->children())
1915
25
    if (SubStmt)
1916
25
      WarnAboutReturnGotoStmts(SubStmt);
1917
33
1918
33
  if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1919
0
    Diags.Report(Context->getFullLoc(S->getBeginLoc()),
1920
0
                 TryFinallyContainsReturnDiag);
1921
0
  }
1922
33
}
1923
1924
1
Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt  *S) {
1925
1
  SourceLocation startLoc = S->getAtLoc();
1926
1
  ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
1927
1
  ReplaceText(S->getSubStmt()->getBeginLoc(), 1,
1928
1
              "{ __AtAutoreleasePool __autoreleasepool; ");
1929
1
1930
1
  return nullptr;
1931
1
}
1932
1933
14
Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
1934
14
  ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
1935
14
  bool noCatch = S->getNumCatchStmts() == 0;
1936
14
  std::string buf;
1937
14
  SourceLocation TryLocation = S->getAtTryLoc();
1938
14
  ConvertSourceLocationToLineDirective(TryLocation, buf);
1939
14
1940
14
  if (finalStmt) {
1941
8
    if (noCatch)
1942
7
      buf += "{ id volatile _rethrow = 0;\n";
1943
1
    else {
1944
1
      buf += "{ id volatile _rethrow = 0;\ntry {\n";
1945
1
    }
1946
8
  }
1947
14
  // Get the start location and compute the semi location.
1948
14
  SourceLocation startLoc = S->getBeginLoc();
1949
14
  const char *startBuf = SM->getCharacterData(startLoc);
1950
14
1951
14
  assert((*startBuf == '@') && "bogus @try location");
1952
14
  if (finalStmt)
1953
8
    ReplaceText(startLoc, 1, buf);
1954
6
  else
1955
6
    // @try -> try
1956
6
    ReplaceText(startLoc, 1, "");
1957
14
1958
25
  for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; 
++I11
) {
1959
11
    ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
1960
11
    VarDecl *catchDecl = Catch->getCatchParamDecl();
1961
11
1962
11
    startLoc = Catch->getBeginLoc();
1963
11
    bool AtRemoved = false;
1964
11
    if (catchDecl) {
1965
8
      QualType t = catchDecl->getType();
1966
8
      if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1967
8
        // Should be a pointer to a class.
1968
8
        ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1969
8
        if (IDecl) {
1970
6
          std::string Result;
1971
6
          ConvertSourceLocationToLineDirective(Catch->getBeginLoc(), Result);
1972
6
1973
6
          startBuf = SM->getCharacterData(startLoc);
1974
6
          assert((*startBuf == '@') && "bogus @catch location");
1975
6
          SourceLocation rParenLoc = Catch->getRParenLoc();
1976
6
          const char *rParenBuf = SM->getCharacterData(rParenLoc);
1977
6
1978
6
          // _objc_exc_Foo *_e as argument to catch.
1979
6
          Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString();
1980
6
          Result += " *_"; Result += catchDecl->getNameAsString();
1981
6
          Result += ")";
1982
6
          ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1983
6
          // Foo *e = (Foo *)_e;
1984
6
          Result.clear();
1985
6
          Result = "{ ";
1986
6
          Result += IDecl->getNameAsString();
1987
6
          Result += " *"; Result += catchDecl->getNameAsString();
1988
6
          Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1989
6
          Result += "_"; Result += catchDecl->getNameAsString();
1990
6
1991
6
          Result += "; ";
1992
6
          SourceLocation lBraceLoc = Catch->getCatchBody()->getBeginLoc();
1993
6
          ReplaceText(lBraceLoc, 1, Result);
1994
6
          AtRemoved = true;
1995
6
        }
1996
8
      }
1997
8
    }
1998
11
    if (!AtRemoved)
1999
5
      // @catch -> catch
2000
5
      ReplaceText(startLoc, 1, "");
2001
11
2002
11
  }
2003
14
  if (finalStmt) {
2004
8
    buf.clear();
2005
8
    SourceLocation FinallyLoc = finalStmt->getBeginLoc();
2006
8
2007
8
    if (noCatch) {
2008
7
      ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2009
7
      buf += "catch (id e) {_rethrow = e;}\n";
2010
7
    }
2011
1
    else {
2012
1
      buf += "}\n";
2013
1
      ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2014
1
      buf += "catch (id e) {_rethrow = e;}\n";
2015
1
    }
2016
8
2017
8
    SourceLocation startFinalLoc = finalStmt->getBeginLoc();
2018
8
    ReplaceText(startFinalLoc, 8, buf);
2019
8
    Stmt *body = finalStmt->getFinallyBody();
2020
8
    SourceLocation startFinalBodyLoc = body->getBeginLoc();
2021
8
    buf.clear();
2022
8
    Write_RethrowObject(buf);
2023
8
    ReplaceText(startFinalBodyLoc, 1, buf);
2024
8
2025
8
    SourceLocation endFinalBodyLoc = body->getEndLoc();
2026
8
    ReplaceText(endFinalBodyLoc, 1, "}\n}");
2027
8
    // Now check for any return/continue/go statements within the @try.
2028
8
    WarnAboutReturnGotoStmts(S->getTryBody());
2029
8
  }
2030
14
2031
14
  return nullptr;
2032
14
}
2033
2034
// This can't be done with ReplaceStmt(S, ThrowExpr), since
2035
// the throw expression is typically a message expression that's already
2036
// been rewritten! (which implies the SourceLocation's are invalid).
2037
5
Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
2038
5
  // Get the start location and compute the semi location.
2039
5
  SourceLocation startLoc = S->getBeginLoc();
2040
5
  const char *startBuf = SM->getCharacterData(startLoc);
2041
5
2042
5
  assert((*startBuf == '@') && "bogus @throw location");
2043
5
2044
5
  std::string buf;
2045
5
  /* void objc_exception_throw(id) __attribute__((noreturn)); */
2046
5
  if (S->getThrowExpr())
2047
4
    buf = "objc_exception_throw(";
2048
1
  else
2049
1
    buf = "throw";
2050
5
2051
5
  // handle "@  throw" correctly.
2052
5
  const char *wBuf = strchr(startBuf, 'w');
2053
5
  assert((*wBuf == 'w') && "@throw: can't find 'w'");
2054
5
  ReplaceText(startLoc, wBuf-startBuf+1, buf);
2055
5
2056
5
  SourceLocation endLoc = S->getEndLoc();
2057
5
  const char *endBuf = SM->getCharacterData(endLoc);
2058
5
  const char *semiBuf = strchr(endBuf, ';');
2059
5
  assert((*semiBuf == ';') && "@throw: can't find ';'");
2060
5
  SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
2061
5
  if (S->getThrowExpr())
2062
4
    ReplaceText(semiLoc, 1, ");");
2063
5
  return nullptr;
2064
5
}
2065
2066
3
Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2067
3
  // Create a new string expression.
2068
3
  std::string StrEncoding;
2069
3
  Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
2070
3
  Expr *Replacement = getStringLiteral(StrEncoding);
2071
3
  ReplaceStmt(Exp, Replacement);
2072
3
2073
3
  // Replace this subexpr in the parent.
2074
3
  // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2075
3
  return Replacement;
2076
3
}
2077
2078
0
Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2079
0
  if (!SelGetUidFunctionDecl)
2080
0
    SynthSelGetUidFunctionDecl();
2081
0
  assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2082
0
  // Create a call to sel_registerName("selName").
2083
0
  SmallVector<Expr*, 8> SelExprs;
2084
0
  SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
2085
0
  CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2086
0
                                                  SelExprs);
2087
0
  ReplaceStmt(Exp, SelExp);
2088
0
  // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2089
0
  return SelExp;
2090
0
}
2091
2092
CallExpr *
2093
RewriteModernObjC::SynthesizeCallToFunctionDecl(FunctionDecl *FD,
2094
                                                ArrayRef<Expr *> Args,
2095
                                                SourceLocation StartLoc,
2096
215
                                                SourceLocation EndLoc) {
2097
215
  // Get the type, we will need to reference it in a couple spots.
2098
215
  QualType msgSendType = FD->getType();
2099
215
2100
215
  // Create a reference to the objc_msgSend() declaration.
2101
215
  DeclRefExpr *DRE = new (Context) DeclRefExpr(*Context, FD, false, msgSendType,
2102
215
                                               VK_LValue, SourceLocation());
2103
215
2104
215
  // Now, we cast the reference to a pointer to the objc_msgSend type.
2105
215
  QualType pToFunc = Context->getPointerType(msgSendType);
2106
215
  ImplicitCastExpr *ICE =
2107
215
    ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2108
215
                             DRE, nullptr, VK_RValue);
2109
215
2110
215
  const auto *FT = msgSendType->castAs<FunctionType>();
2111
215
  CallExpr *Exp = CallExpr::Create(
2112
215
      *Context, ICE, Args, FT->getCallResultType(*Context), VK_RValue, EndLoc);
2113
215
  return Exp;
2114
215
}
2115
2116
static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2117
6
                                const char *&startRef, const char *&endRef) {
2118
70
  while (startBuf < endBuf) {
2119
70
    if (*startBuf == '<')
2120
6
      startRef = startBuf; // mark the start.
2121
70
    if (*startBuf == '>') {
2122
6
      if (startRef && *startRef == '<') {
2123
6
        endRef = startBuf; // mark the end.
2124
6
        return true;
2125
6
      }
2126
0
      return false;
2127
0
    }
2128
64
    startBuf++;
2129
64
  }
2130
6
  
return false0
;
2131
6
}
2132
2133
0
static void scanToNextArgument(const char *&argRef) {
2134
0
  int angle = 0;
2135
0
  while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2136
0
    if (*argRef == '<')
2137
0
      angle++;
2138
0
    else if (*argRef == '>')
2139
0
      angle--;
2140
0
    argRef++;
2141
0
  }
2142
0
  assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2143
0
}
2144
2145
545
bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2146
545
  if (T->isObjCQualifiedIdType())
2147
2
    return true;
2148
543
  if (const PointerType *PT = T->getAs<PointerType>()) {
2149
70
    if (PT->getPointeeType()->isObjCQualifiedIdType())
2150
0
      return true;
2151
543
  }
2152
543
  if (T->isObjCObjectPointerType()) {
2153
131
    T = T->getPointeeType();
2154
131
    return T->isObjCQualifiedInterfaceType();
2155
131
  }
2156
412
  if (T->isArrayType()) {
2157
0
    QualType ElemTy = Context->getBaseElementType(T);
2158
0
    return needToScanForQualifiers(ElemTy);
2159
0
  }
2160
412
  return false;
2161
412
}
2162
2163
30
void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2164
30
  QualType Type = E->getType();
2165
30
  if (needToScanForQualifiers(Type)) {
2166
1
    SourceLocation Loc, EndLoc;
2167
1
2168
1
    if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2169
1
      Loc = ECE->getLParenLoc();
2170
1
      EndLoc = ECE->getRParenLoc();
2171
1
    } else {
2172
0
      Loc = E->getBeginLoc();
2173
0
      EndLoc = E->getEndLoc();
2174
0
    }
2175
1
    // This will defend against trying to rewrite synthesized expressions.
2176
1
    if (Loc.isInvalid() || EndLoc.isInvalid())
2177
0
      return;
2178
1
2179
1
    const char *startBuf = SM->getCharacterData(Loc);
2180
1
    const char *endBuf = SM->getCharacterData(EndLoc);
2181
1
    const char *startRef = nullptr, *endRef = nullptr;
2182
1
    if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2183
1
      // Get the locations of the startRef, endRef.
2184
1
      SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2185
1
      SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2186
1
      // Comment out the protocol references.
2187
1
      InsertText(LessLoc, "/*");
2188
1
      InsertText(GreaterLoc, "*/");
2189
1
    }
2190
1
  }
2191
30
}
2192
2193
425
void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2194
425
  SourceLocation Loc;
2195
425
  QualType Type;
2196
425
  const FunctionProtoType *proto = nullptr;
2197
425
  if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2198
193
    Loc = VD->getLocation();
2199
193
    Type = VD->getType();
2200
193
  }
2201
232
  else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2202
163
    Loc = FD->getLocation();
2203
163
    // Check for ObjC 'id' and class types that have been adorned with protocol
2204
163
    // information (id<p>, C<p>*). The protocol references need to be rewritten!
2205
163
    const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2206
163
    assert(funcType && "missing function type");
2207
163
    proto = dyn_cast<FunctionProtoType>(funcType);
2208
163
    if (!proto)
2209
23
      return;
2210
140
    Type = proto->getReturnType();
2211
140
  }
2212
69
  else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2213
0
    Loc = FD->getLocation();
2214
0
    Type = FD->getType();
2215
0
  }
2216
69
  else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Dcl)) {
2217
69
    Loc = TD->getLocation();
2218
69
    Type = TD->getUnderlyingType();
2219
69
  }
2220
0
  else
2221
0
    return;
2222
402
2223
402
  if (needToScanForQualifiers(Type)) {
2224
5
    // Since types are unique, we need to scan the buffer.
2225
5
2226
5
    const char *endBuf = SM->getCharacterData(Loc);
2227
5
    const char *startBuf = endBuf;
2228
72
    while (*startBuf != ';' && *startBuf != '<' && 
startBuf != MainFileStart67
)
2229
67
      startBuf--; // scan backward (from the decl location) for return type.
2230
5
    const char *startRef = nullptr, *endRef = nullptr;
2231
5
    if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2232
5
      // Get the locations of the startRef, endRef.
2233
5
      SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2234
5
      SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2235
5
      // Comment out the protocol references.
2236
5
      InsertText(LessLoc, "/*");
2237
5
      InsertText(GreaterLoc, "*/");
2238
5
    }
2239
5
  }
2240
402
  if (!proto)
2241
262
      return; // most likely, was a variable
2242
140
  // Now check arguments.
2243
140
  const char *startBuf = SM->getCharacterData(Loc);
2244
140
  const char *startFuncBuf = startBuf;
2245
225
  for (unsigned i = 0; i < proto->getNumParams(); 
i++85
) {
2246
85
    if (needToScanForQualifiers(proto->getParamType(i))) {
2247
0
      // Since types are unique, we need to scan the buffer.
2248
0
2249
0
      const char *endBuf = startBuf;
2250
0
      // scan forward (from the decl location) for argument types.
2251
0
      scanToNextArgument(endBuf);
2252
0
      const char *startRef = nullptr, *endRef = nullptr;
2253
0
      if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2254
0
        // Get the locations of the startRef, endRef.
2255
0
        SourceLocation LessLoc =
2256
0
          Loc.getLocWithOffset(startRef-startFuncBuf);
2257
0
        SourceLocation GreaterLoc =
2258
0
          Loc.getLocWithOffset(endRef-startFuncBuf+1);
2259
0
        // Comment out the protocol references.
2260
0
        InsertText(LessLoc, "/*");
2261
0
        InsertText(GreaterLoc, "*/");
2262
0
      }
2263
0
      startBuf = ++endBuf;
2264
0
    }
2265
85
    else {
2266
85
      // If the function name is derived from a macro expansion, then the
2267
85
      // argument buffer will not follow the name. Need to speak with Chris.
2268
1.41k
      while (*startBuf && *startBuf != ')' && 
*startBuf != ','1.34k
)
2269
1.32k
        startBuf++; // scan forward (from the decl location) for argument types.
2270
85
      startBuf++;
2271
85
    }
2272
85
  }
2273
140
}
2274
2275
146
void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2276
146
  QualType QT = ND->getType();
2277
146
  const Type* TypePtr = QT->getAs<Type>();
2278
146
  if (!isa<TypeOfExprType>(TypePtr))
2279
143
    return;
2280
9
  
while (3
isa<TypeOfExprType>(TypePtr)) {
2281
6
    const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2282
6
    QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2283
6
    TypePtr = QT->getAs<Type>();
2284
6
  }
2285
3
  // FIXME. This will not work for multiple declarators; as in:
2286
3
  // __typeof__(a) b,c,d;
2287
3
  std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2288
3
  SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2289
3
  const char *startBuf = SM->getCharacterData(DeclLoc);
2290
3
  if (ND->getInit()) {
2291
2
    std::string Name(ND->getNameAsString());
2292
2
    TypeAsString += " " + Name + " = ";
2293
2
    Expr *E = ND->getInit();
2294
2
    SourceLocation startLoc;
2295
2
    if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2296
0
      startLoc = ECE->getLParenLoc();
2297
2
    else
2298
2
      startLoc = E->getBeginLoc();
2299
2
    startLoc = SM->getExpansionLoc(startLoc);
2300
2
    const char *endBuf = SM->getCharacterData(startLoc);
2301
2
    ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2302
2
  }
2303
1
  else {
2304
1
    SourceLocation X = ND->getEndLoc();
2305
1
    X = SM->getExpansionLoc(X);
2306
1
    const char *endBuf = SM->getCharacterData(X);
2307
1
    ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2308
1
  }
2309
3
}
2310
2311
// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2312
3
void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2313
3
  IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2314
3
  SmallVector<QualType, 16> ArgTys;
2315
3
  ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2316
3
  QualType getFuncType =
2317
3
    getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
2318
3
  SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2319
3
                                               SourceLocation(),
2320
3
                                               SourceLocation(),
2321
3
                                               SelGetUidIdent, getFuncType,
2322
3
                                               nullptr, SC_Extern);
2323
3
}
2324
2325
192
void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2326
192
  // declared in <objc/objc.h>
2327
192
  if (FD->getIdentifier() &&
2328
192
      FD->getName() == "sel_registerName") {
2329
29
    SelGetUidFunctionDecl = FD;
2330
29
    return;
2331
29
  }
2332
163
  RewriteObjCQualifiedInterfaceTypes(FD);
2333
163
}
2334
2335
9
void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2336
9
  std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2337
9
  const char *argPtr = TypeString.c_str();
2338
9
  if (!strchr(argPtr, '^')) {
2339
1
    Str += TypeString;
2340
1
    return;
2341
1
  }
2342
116
  
while (8
*argPtr) {
2343
108
    Str += (*argPtr == '^' ? 
'*'8
:
*argPtr100
);
2344
108
    argPtr++;
2345
108
  }
2346
8
}
2347
2348
// FIXME. Consolidate this routine with RewriteBlockPointerType.
2349
void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2350
2
                                                  ValueDecl *VD) {
2351
2
  QualType Type = VD->getType();
2352
2
  std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2353
2
  const char *argPtr = TypeString.c_str();
2354
2
  int paren = 0;
2355
29
  while (*argPtr) {
2356
27
    switch (*argPtr) {
2357
4
      case '(':
2358
4
        Str += *argPtr;
2359
4
        paren++;
2360
4
        break;
2361
4
      case ')':
2362
4
        Str += *argPtr;
2363
4
        paren--;
2364
4
        break;
2365
2
      case '^':
2366
2
        Str += '*';
2367
2
        if (paren == 1)
2368
2
          Str += VD->getNameAsString();
2369
2
        break;
2370
17
      default:
2371
17
        Str += *argPtr;
2372
17
        break;
2373
27
    }
2374
27
    argPtr++;
2375
27
  }
2376
2
}
2377
2378
5
void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2379
5
  SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2380
5
  const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2381
5
  const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2382
5
  if (!proto)
2383
0
    return;
2384
5
  QualType Type = proto->getReturnType();
2385
5
  std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2386
5
  FdStr += " ";
2387
5
  FdStr += FD->getName();
2388
5
  FdStr +=  "(";
2389
5
  unsigned numArgs = proto->getNumParams();
2390
8
  for (unsigned i = 0; i < numArgs; 
i++3
) {
2391
3
    QualType ArgType = proto->getParamType(i);
2392
3
  RewriteBlockPointerType(FdStr, ArgType);
2393
3
  if (i+1 < numArgs)
2394
0
    FdStr += ", ";
2395
3
  }
2396
5
  if (FD->isVariadic()) {
2397
2
    FdStr +=  (numArgs > 0) ? 
", ...);\n"1
:
"...);\n"1
;
2398
2
  }
2399
3
  else
2400
3
    FdStr +=  ");\n";
2401
5
  InsertText(FunLocStart, FdStr);
2402
5
}
2403
2404
// SynthSuperConstructorFunctionDecl - id __rw_objc_super(id obj, id super);
2405
1
void RewriteModernObjC::SynthSuperConstructorFunctionDecl() {
2406
1
  if (SuperConstructorFunctionDecl)
2407
0
    return;
2408
1
  IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2409
1
  SmallVector<QualType, 16> ArgTys;
2410
1
  QualType argT = Context->getObjCIdType();
2411
1
  assert(!argT.isNull() && "Can't find 'id' type");
2412
1
  ArgTys.push_back(argT);
2413
1
  ArgTys.push_back(argT);
2414
1
  QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2415
1
                                               ArgTys);
2416
1
  SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2417
1
                                                     SourceLocation(),
2418
1
                                                     SourceLocation(),
2419
1
                                                     msgSendIdent, msgSendType,
2420
1
                                                     nullptr, SC_Extern);
2421
1
}
2422
2423
// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2424
29
void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2425
29
  IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2426
29
  SmallVector<QualType, 16> ArgTys;
2427
29
  QualType argT = Context->getObjCIdType();
2428
29
  assert(!argT.isNull() && "Can't find 'id' type");
2429
29
  ArgTys.push_back(argT);
2430
29
  argT = Context->getObjCSelType();
2431
29
  assert(!argT.isNull() && "Can't find 'SEL' type");
2432
29
  ArgTys.push_back(argT);
2433
29
  QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2434
29
                                               ArgTys, /*variadic=*/true);
2435
29
  MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2436
29
                                             SourceLocation(),
2437
29
                                             SourceLocation(),
2438
29
                                             msgSendIdent, msgSendType, nullptr,
2439
29
                                             SC_Extern);
2440
29
}
2441
2442
// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
2443
25
void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2444
25
  IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2445
25
  SmallVector<QualType, 2> ArgTys;
2446
25
  ArgTys.push_back(Context->VoidTy);
2447
25
  QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2448
25
                                               ArgTys, /*variadic=*/true);
2449
25
  MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2450
25
                                                  SourceLocation(),
2451
25
                                                  SourceLocation(),
2452
25
                                                  msgSendIdent, msgSendType,
2453
25
                                                  nullptr, SC_Extern);
2454
25
}
2455
2456
// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2457
25
void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2458
25
  IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2459
25
  SmallVector<QualType, 16> ArgTys;
2460
25
  QualType argT = Context->getObjCIdType();
2461
25
  assert(!argT.isNull() && "Can't find 'id' type");
2462
25
  ArgTys.push_back(argT);
2463
25
  argT = Context->getObjCSelType();
2464
25
  assert(!argT.isNull() && "Can't find 'SEL' type");
2465
25
  ArgTys.push_back(argT);
2466
25
  QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2467
25
                                               ArgTys, /*variadic=*/true);
2468
25
  MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2469
25
                                                  SourceLocation(),
2470
25
                                                  SourceLocation(),
2471
25
                                                  msgSendIdent, msgSendType,
2472
25
                                                  nullptr, SC_Extern);
2473
25
}
2474
2475
// SynthMsgSendSuperStretFunctionDecl -
2476
// id objc_msgSendSuper_stret(void);
2477
25
void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2478
25
  IdentifierInfo *msgSendIdent =
2479
25
    &Context->Idents.get("objc_msgSendSuper_stret");
2480
25
  SmallVector<QualType, 2> ArgTys;
2481
25
  ArgTys.push_back(Context->VoidTy);
2482
25
  QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2483
25
                                               ArgTys, /*variadic=*/true);
2484
25
  MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2485
25
                                                       SourceLocation(),
2486
25
                                                       SourceLocation(),
2487
25
                                                       msgSendIdent,
2488
25
                                                       msgSendType, nullptr,
2489
25
                                                       SC_Extern);
2490
25
}
2491
2492
// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2493
25
void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2494
25
  IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2495
25
  SmallVector<QualType, 16> ArgTys;
2496
25
  QualType argT = Context->getObjCIdType();
2497
25
  assert(!argT.isNull() && "Can't find 'id' type");
2498
25
  ArgTys.push_back(argT);
2499
25
  argT = Context->getObjCSelType();
2500
25
  assert(!argT.isNull() && "Can't find 'SEL' type");
2501
25
  ArgTys.push_back(argT);
2502
25
  QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2503
25
                                               ArgTys, /*variadic=*/true);
2504
25
  MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2505
25
                                                  SourceLocation(),
2506
25
                                                  SourceLocation(),
2507
25
                                                  msgSendIdent, msgSendType,
2508
25
                                                  nullptr, SC_Extern);
2509
25
}
2510
2511
// SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
2512
29
void RewriteModernObjC::SynthGetClassFunctionDecl() {
2513
29
  IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2514
29
  SmallVector<QualType, 16> ArgTys;
2515
29
  ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2516
29
  QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2517
29
                                                ArgTys);
2518
29
  GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2519
29
                                              SourceLocation(),
2520
29
                                              SourceLocation(),
2521
29
                                              getClassIdent, getClassType,
2522
29
                                              nullptr, SC_Extern);
2523
29
}
2524
2525
// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2526
25
void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2527
25
  IdentifierInfo *getSuperClassIdent =
2528
25
    &Context->Idents.get("class_getSuperclass");
2529
25
  SmallVector<QualType, 16> ArgTys;
2530
25
  ArgTys.push_back(Context->getObjCClassType());
2531
25
  QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2532
25
                                                ArgTys);
2533
25
  GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2534
25
                                                   SourceLocation(),
2535
25
                                                   SourceLocation(),
2536
25
                                                   getSuperClassIdent,
2537
25
                                                   getClassType, nullptr,
2538
25
                                                   SC_Extern);
2539
25
}
2540
2541
// SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
2542
25
void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2543
25
  IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2544
25
  SmallVector<QualType, 16> ArgTys;
2545
25
  ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2546
25
  QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2547
25
                                                ArgTys);
2548
25
  GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2549
25
                                                  SourceLocation(),
2550
25
                                                  SourceLocation(),
2551
25
                                                  getClassIdent, getClassType,
2552
25
                                                  nullptr, SC_Extern);
2553
25
}
2554
2555
13
Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2556
13
  assert (Exp != nullptr && "Expected non-null ObjCStringLiteral");
2557
13
  QualType strType = getConstantStringStructType();
2558
13
2559
13
  std::string S = "__NSConstantStringImpl_";
2560
13
2561
13
  std::string tmpName = InFileName;
2562
13
  unsigned i;
2563
1.45k
  for (i=0; i < tmpName.length(); 
i++1.44k
) {
2564
1.44k
    char c = tmpName.at(i);
2565
1.44k
    // replace any non-alphanumeric characters with '_'.
2566
1.44k
    if (!isAlphanumeric(c))
2567
194
      tmpName[i] = '_';
2568
1.44k
  }
2569
13
  S += tmpName;
2570
13
  S += "_";
2571
13
  S += utostr(NumObjCStringLiterals++);
2572
13
2573
13
  Preamble += "static __NSConstantStringImpl " + S;
2574
13
  Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2575
13
  Preamble += "0x000007c8,"; // utf8_str
2576
13
  // The pretty printer for StringLiteral handles escape characters properly.
2577
13
  std::string prettyBufS;
2578
13
  llvm::raw_string_ostream prettyBuf(prettyBufS);
2579
13
  Exp->getString()->printPretty(prettyBuf, nullptr, PrintingPolicy(LangOpts));
2580
13
  Preamble += prettyBuf.str();
2581
13
  Preamble += ",";
2582
13
  Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2583
13
2584
13
  VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2585
13
                                   SourceLocation(), &Context->Idents.get(S),
2586
13
                                   strType, nullptr, SC_Static);
2587
13
  DeclRefExpr *DRE = new (Context)
2588
13
      DeclRefExpr(*Context, NewVD, false, strType, VK_LValue, SourceLocation());
2589
13
  Expr *Unop = new (Context)
2590
13
      UnaryOperator(DRE, UO_AddrOf, Context->getPointerType(DRE->getType()),
2591
13
                    VK_RValue, OK_Ordinary, SourceLocation(), false);
2592
13
  // cast to NSConstantString *
2593
13
  CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2594
13
                                            CK_CPointerToObjCPointerCast, Unop);
2595
13
  ReplaceStmt(Exp, cast);
2596
13
  // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2597
13
  return cast;
2598
13
}
2599
2600
16
Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2601
16
  unsigned IntSize =
2602
16
    static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2603
16
2604
16
  Expr *FlagExp = IntegerLiteral::Create(*Context,
2605
16
                                         llvm::APInt(IntSize, Exp->getValue()),
2606
16
                                         Context->IntTy, Exp->getLocation());
2607
16
  CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2608
16
                                            CK_BitCast, FlagExp);
2609
16
  ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2610
16
                                          cast);
2611
16
  ReplaceStmt(Exp, PE);
2612
16
  return PE;
2613
16
}
2614
2615
36
Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
2616
36
  // synthesize declaration of helper functions needed in this routine.
2617
36
  if (!SelGetUidFunctionDecl)
2618
0
    SynthSelGetUidFunctionDecl();
2619
36
  // use objc_msgSend() for all.
2620
36
  if (!MsgSendFunctionDecl)
2621
4
    SynthMsgSendFunctionDecl();
2622
36
  if (!GetClassFunctionDecl)
2623
4
    SynthGetClassFunctionDecl();
2624
36
2625
36
  FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2626
36
  SourceLocation StartLoc = Exp->getBeginLoc();
2627
36
  SourceLocation EndLoc = Exp->getEndLoc();
2628
36
2629
36
  // Synthesize a call to objc_msgSend().
2630
36
  SmallVector<Expr*, 4> MsgExprs;
2631
36
  SmallVector<Expr*, 4> ClsExprs;
2632
36
2633
36
  // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2634
36
  ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2635
36
  ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
2636
36
2637
36
  IdentifierInfo *clsName = BoxingClass->getIdentifier();
2638
36
  ClsExprs.push_back(getStringLiteral(clsName->getName()));
2639
36
  CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
2640
36
                                               StartLoc, EndLoc);
2641
36
  MsgExprs.push_back(Cls);
2642
36
2643
36
  // Create a call to sel_registerName("<BoxingMethod>:"), etc.
2644
36
  // it will be the 2nd argument.
2645
36
  SmallVector<Expr*, 4> SelExprs;
2646
36
  SelExprs.push_back(
2647
36
      getStringLiteral(BoxingMethod->getSelector().getAsString()));
2648
36
  CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2649
36
                                                  SelExprs, StartLoc, EndLoc);
2650
36
  MsgExprs.push_back(SelExp);
2651
36
2652
36
  // User provided sub-expression is the 3rd, and last, argument.
2653
36
  Expr *subExpr  = Exp->getSubExpr();
2654
36
  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
2655
4
    QualType type = ICE->getType();
2656
4
    const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2657
4
    CastKind CK = CK_BitCast;
2658
4
    if (SubExpr->getType()->isIntegralType(*Context) && 
type->isBooleanType()2
)
2659
0
      CK = CK_IntegralToBoolean;
2660
4
    subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
2661
4
  }
2662
36
  MsgExprs.push_back(subExpr);
2663
36
2664
36
  SmallVector<QualType, 4> ArgTypes;
2665
36
  ArgTypes.push_back(Context->getObjCClassType());
2666
36
  ArgTypes.push_back(Context->getObjCSelType());
2667
36
  for (const auto PI : BoxingMethod->parameters())
2668
36
    ArgTypes.push_back(PI->getType());
2669
36
2670
36
  QualType returnType = Exp->getType();
2671
36
  // Get the type, we will need to reference it in a couple spots.
2672
36
  QualType msgSendType = MsgSendFlavor->getType();
2673
36
2674
36
  // Create a reference to the objc_msgSend() declaration.
2675
36
  DeclRefExpr *DRE = new (Context) DeclRefExpr(
2676
36
      *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
2677
36
2678
36
  CastExpr *cast = NoTypeInfoCStyleCastExpr(
2679
36
      Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE);
2680
36
2681
36
  // Now do the "normal" pointer to function cast.
2682
36
  QualType castType =
2683
36
    getSimpleFunctionType(returnType, ArgTypes, BoxingMethod->isVariadic());
2684
36
  castType = Context->getPointerType(castType);
2685
36
  cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2686
36
                                  cast);
2687
36
2688
36
  // Don't forget the parens to enforce the proper binding.
2689
36
  ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2690
36
2691
36
  const FunctionType *FT = msgSendType->getAs<FunctionType>();
2692
36
  CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
2693
36
                                  VK_RValue, EndLoc);
2694
36
  ReplaceStmt(Exp, CE);
2695
36
  return CE;
2696
36
}
2697
2698
5
Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2699
5
  // synthesize declaration of helper functions needed in this routine.
2700
5
  if (!SelGetUidFunctionDecl)
2701
0
    SynthSelGetUidFunctionDecl();
2702
5
  // use objc_msgSend() for all.
2703
5
  if (!MsgSendFunctionDecl)
2704
0
    SynthMsgSendFunctionDecl();
2705
5
  if (!GetClassFunctionDecl)
2706
0
    SynthGetClassFunctionDecl();
2707
5
2708
5
  FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2709
5
  SourceLocation StartLoc = Exp->getBeginLoc();
2710
5
  SourceLocation EndLoc = Exp->getEndLoc();
2711
5
2712
5
  // Build the expression: __NSContainer_literal(int, ...).arr
2713
5
  QualType IntQT = Context->IntTy;
2714
5
  QualType NSArrayFType =
2715
5
    getSimpleFunctionType(Context->VoidTy, IntQT, true);
2716
5
  std::string NSArrayFName("__NSContainer_literal");
2717
5
  FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2718
5
  DeclRefExpr *NSArrayDRE = new (Context) DeclRefExpr(
2719
5
      *Context, NSArrayFD, false, NSArrayFType, VK_RValue, SourceLocation());
2720
5
2721
5
  SmallVector<Expr*, 16> InitExprs;
2722
5
  unsigned NumElements = Exp->getNumElements();
2723
5
  unsigned UnsignedIntSize =
2724
5
    static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2725
5
  Expr *count = IntegerLiteral::Create(*Context,
2726
5
                                       llvm::APInt(UnsignedIntSize, NumElements),
2727
5
                                       Context->UnsignedIntTy, SourceLocation());
2728
5
  InitExprs.push_back(count);
2729
18
  for (unsigned i = 0; i < NumElements; 
i++13
)
2730
13
    InitExprs.push_back(Exp->getElement(i));
2731
5
  Expr *NSArrayCallExpr =
2732
5
      CallExpr::Create(*Context, NSArrayDRE, InitExprs, NSArrayFType, VK_LValue,
2733
5
                       SourceLocation());
2734
5
2735
5
  FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
2736
5
                                    SourceLocation(),
2737
5
                                    &Context->Idents.get("arr"),
2738
5
                                    Context->getPointerType(Context->VoidPtrTy),
2739
5
                                    nullptr, /*BitWidth=*/nullptr,
2740
5
                                    /*Mutable=*/true, ICIS_NoInit);
2741
5
  MemberExpr *ArrayLiteralME =
2742
5
      MemberExpr::CreateImplicit(*Context, NSArrayCallExpr, false, ARRFD,
2743
5
                                 ARRFD->getType(), VK_LValue, OK_Ordinary);
2744
5
  QualType ConstIdT = Context->getObjCIdType().withConst();
2745
5
  CStyleCastExpr * ArrayLiteralObjects =
2746
5
    NoTypeInfoCStyleCastExpr(Context,
2747
5
                             Context->getPointerType(ConstIdT),
2748
5
                             CK_BitCast,
2749
5
                             ArrayLiteralME);
2750
5
2751
5
  // Synthesize a call to objc_msgSend().
2752
5
  SmallVector<Expr*, 32> MsgExprs;
2753
5
  SmallVector<Expr*, 4> ClsExprs;
2754
5
  QualType expType = Exp->getType();
2755
5
2756
5
  // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2757
5
  ObjCInterfaceDecl *Class =
2758
5
    expType->getPointeeType()->castAs<ObjCObjectType>()->getInterface();
2759
5
2760
5
  IdentifierInfo *clsName = Class->getIdentifier();
2761
5
  ClsExprs.push_back(getStringLiteral(clsName->getName()));
2762
5
  CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
2763
5
                                               StartLoc, EndLoc);
2764
5
  MsgExprs.push_back(Cls);
2765
5
2766
5
  // Create a call to sel_registerName("arrayWithObjects:count:").
2767
5
  // it will be the 2nd argument.
2768
5
  SmallVector<Expr*, 4> SelExprs;
2769
5
  ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
2770
5
  SelExprs.push_back(
2771
5
      getStringLiteral(ArrayMethod->getSelector().getAsString()));
2772
5
  CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2773
5
                                                  SelExprs, StartLoc, EndLoc);
2774
5
  MsgExprs.push_back(SelExp);
2775
5
2776
5
  // (const id [])objects
2777
5
  MsgExprs.push_back(ArrayLiteralObjects);
2778
5
2779
5
  // (NSUInteger)cnt
2780
5
  Expr *cnt = IntegerLiteral::Create(*Context,
2781
5
                                     llvm::APInt(UnsignedIntSize, NumElements),
2782
5
                                     Context->UnsignedIntTy, SourceLocation());
2783
5
  MsgExprs.push_back(cnt);
2784
5
2785
5
  SmallVector<QualType, 4> ArgTypes;
2786
5
  ArgTypes.push_back(Context->getObjCClassType());
2787
5
  ArgTypes.push_back(Context->getObjCSelType());
2788
5
  for (const auto *PI : ArrayMethod->parameters())
2789
10
    ArgTypes.push_back(PI->getType());
2790
5
2791
5
  QualType returnType = Exp->getType();
2792
5
  // Get the type, we will need to reference it in a couple spots.
2793
5
  QualType msgSendType = MsgSendFlavor->getType();
2794
5
2795
5
  // Create a reference to the objc_msgSend() declaration.
2796
5
  DeclRefExpr *DRE = new (Context) DeclRefExpr(
2797
5
      *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
2798
5
2799
5
  CastExpr *cast = NoTypeInfoCStyleCastExpr(
2800
5
      Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE);
2801
5
2802
5
  // Now do the "normal" pointer to function cast.
2803
5
  QualType castType =
2804
5
  getSimpleFunctionType(returnType, ArgTypes, ArrayMethod->isVariadic());
2805
5
  castType = Context->getPointerType(castType);
2806
5
  cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2807
5
                                  cast);
2808
5
2809
5
  // Don't forget the parens to enforce the proper binding.
2810
5
  ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2811
5
2812
5
  const FunctionType *FT = msgSendType->castAs<FunctionType>();
2813
5
  CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
2814
5
                                  VK_RValue, EndLoc);
2815
5
  ReplaceStmt(Exp, CE);
2816
5
  return CE;
2817
5
}
2818
2819
2
Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2820
2
  // synthesize declaration of helper functions needed in this routine.
2821
2
  if (!SelGetUidFunctionDecl)
2822
0
    SynthSelGetUidFunctionDecl();
2823
2
  // use objc_msgSend() for all.
2824
2
  if (!MsgSendFunctionDecl)
2825
0
    SynthMsgSendFunctionDecl();
2826
2
  if (!GetClassFunctionDecl)
2827
0
    SynthGetClassFunctionDecl();
2828
2
2829
2
  FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2830
2
  SourceLocation StartLoc = Exp->getBeginLoc();
2831
2
  SourceLocation EndLoc = Exp->getEndLoc();
2832
2
2833
2
  // Build the expression: __NSContainer_literal(int, ...).arr
2834
2
  QualType IntQT = Context->IntTy;
2835
2
  QualType NSDictFType =
2836
2
    getSimpleFunctionType(Context->VoidTy, IntQT, true);
2837
2
  std::string NSDictFName("__NSContainer_literal");
2838
2
  FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2839
2
  DeclRefExpr *NSDictDRE = new (Context) DeclRefExpr(
2840
2
      *Context, NSDictFD, false, NSDictFType, VK_RValue, SourceLocation());
2841
2
2842
2
  SmallVector<Expr*, 16> KeyExprs;
2843
2
  SmallVector<Expr*, 16> ValueExprs;
2844
2
2845
2
  unsigned NumElements = Exp->getNumElements();
2846
2
  unsigned UnsignedIntSize =
2847
2
    static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2848
2
  Expr *count = IntegerLiteral::Create(*Context,
2849
2
                                       llvm::APInt(UnsignedIntSize, NumElements),
2850
2
                                       Context->UnsignedIntTy, SourceLocation());
2851
2
  KeyExprs.push_back(count);
2852
2
  ValueExprs.push_back(count);
2853
8
  for (unsigned i = 0; i < NumElements; 
i++6
) {
2854
6
    ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2855
6
    KeyExprs.push_back(Element.Key);
2856
6
    ValueExprs.push_back(Element.Value);
2857
6
  }
2858
2
2859
2
  // (const id [])objects
2860
2
  Expr *NSValueCallExpr =
2861
2
      CallExpr::Create(*Context, NSDictDRE, ValueExprs, NSDictFType, VK_LValue,
2862
2
                       SourceLocation());
2863
2
2864
2
  FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
2865
2
                                       SourceLocation(),
2866
2
                                       &Context->Idents.get("arr"),
2867
2
                                       Context->getPointerType(Context->VoidPtrTy),
2868
2
                                       nullptr, /*BitWidth=*/nullptr,
2869
2
                                       /*Mutable=*/true, ICIS_NoInit);
2870
2
  MemberExpr *DictLiteralValueME =
2871
2
      MemberExpr::CreateImplicit(*Context, NSValueCallExpr, false, ARRFD,
2872
2
                                 ARRFD->getType(), VK_LValue, OK_Ordinary);
2873
2
  QualType ConstIdT = Context->getObjCIdType().withConst();
2874
2
  CStyleCastExpr * DictValueObjects =
2875
2
    NoTypeInfoCStyleCastExpr(Context,
2876
2
                             Context->getPointerType(ConstIdT),
2877
2
                             CK_BitCast,
2878
2
                             DictLiteralValueME);
2879
2
  // (const id <NSCopying> [])keys
2880
2
  Expr *NSKeyCallExpr = CallExpr::Create(
2881
2
      *Context, NSDictDRE, KeyExprs, NSDictFType, VK_LValue, SourceLocation());
2882
2
2883
2
  MemberExpr *DictLiteralKeyME =
2884
2
      MemberExpr::CreateImplicit(*Context, NSKeyCallExpr, false, ARRFD,
2885
2
                                 ARRFD->getType(), VK_LValue, OK_Ordinary);
2886
2
2887
2
  CStyleCastExpr * DictKeyObjects =
2888
2
    NoTypeInfoCStyleCastExpr(Context,
2889
2
                             Context->getPointerType(ConstIdT),
2890
2
                             CK_BitCast,
2891
2
                             DictLiteralKeyME);
2892
2
2893
2
  // Synthesize a call to objc_msgSend().
2894
2
  SmallVector<Expr*, 32> MsgExprs;
2895
2
  SmallVector<Expr*, 4> ClsExprs;
2896
2
  QualType expType = Exp->getType();
2897
2
2898
2
  // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2899
2
  ObjCInterfaceDecl *Class =
2900
2
  expType->getPointeeType()->castAs<ObjCObjectType>()->getInterface();
2901
2
2902
2
  IdentifierInfo *clsName = Class->getIdentifier();
2903
2
  ClsExprs.push_back(getStringLiteral(clsName->getName()));
2904
2
  CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
2905
2
                                               StartLoc, EndLoc);
2906
2
  MsgExprs.push_back(Cls);
2907
2
2908
2
  // Create a call to sel_registerName("arrayWithObjects:count:").
2909
2
  // it will be the 2nd argument.
2910
2
  SmallVector<Expr*, 4> SelExprs;
2911
2
  ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
2912
2
  SelExprs.push_back(getStringLiteral(DictMethod->getSelector().getAsString()));
2913
2
  CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2914
2
                                                  SelExprs, StartLoc, EndLoc);
2915
2
  MsgExprs.push_back(SelExp);
2916
2
2917
2
  // (const id [])objects
2918
2
  MsgExprs.push_back(DictValueObjects);
2919
2
2920
2
  // (const id <NSCopying> [])keys
2921
2
  MsgExprs.push_back(DictKeyObjects);
2922
2
2923
2
  // (NSUInteger)cnt
2924
2
  Expr *cnt = IntegerLiteral::Create(*Context,
2925
2
                                     llvm::APInt(UnsignedIntSize, NumElements),
2926
2
                                     Context->UnsignedIntTy, SourceLocation());
2927
2
  MsgExprs.push_back(cnt);
2928
2
2929
2
  SmallVector<QualType, 8> ArgTypes;
2930
2
  ArgTypes.push_back(Context->getObjCClassType());
2931
2
  ArgTypes.push_back(Context->getObjCSelType());
2932
6
  for (const auto *PI : DictMethod->parameters()) {
2933
6
    QualType T = PI->getType();
2934
6
    if (const PointerType* PT = T->getAs<PointerType>()) {
2935
4
      QualType PointeeTy = PT->getPointeeType();
2936
4
      convertToUnqualifiedObjCType(PointeeTy);
2937
4
      T = Context->getPointerType(PointeeTy);
2938
4
    }
2939
6
    ArgTypes.push_back(T);
2940
6
  }
2941
2
2942
2
  QualType returnType = Exp->getType();
2943
2
  // Get the type, we will need to reference it in a couple spots.
2944
2
  QualType msgSendType = MsgSendFlavor->getType();
2945
2
2946
2
  // Create a reference to the objc_msgSend() declaration.
2947
2
  DeclRefExpr *DRE = new (Context) DeclRefExpr(
2948
2
      *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
2949
2
2950
2
  CastExpr *cast = NoTypeInfoCStyleCastExpr(
2951
2
      Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE);
2952
2
2953
2
  // Now do the "normal" pointer to function cast.
2954
2
  QualType castType =
2955
2
  getSimpleFunctionType(returnType, ArgTypes, DictMethod->isVariadic());
2956
2
  castType = Context->getPointerType(castType);
2957
2
  cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2958
2
                                  cast);
2959
2
2960
2
  // Don't forget the parens to enforce the proper binding.
2961
2
  ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2962
2
2963
2
  const FunctionType *FT = msgSendType->castAs<FunctionType>();
2964
2
  CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
2965
2
                                  VK_RValue, EndLoc);
2966
2
  ReplaceStmt(Exp, CE);
2967
2
  return CE;
2968
2
}
2969
2970
// struct __rw_objc_super {
2971
//   struct objc_object *object; struct objc_object *superClass;
2972
// };
2973
2
QualType RewriteModernObjC::getSuperStructType() {
2974
2
  if (!SuperStructDecl) {
2975
1
    SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2976
1
                                         SourceLocation(), SourceLocation(),
2977
1
                                         &Context->Idents.get("__rw_objc_super"));
2978
1
    QualType FieldTypes[2];
2979
1
2980
1
    // struct objc_object *object;
2981
1
    FieldTypes[0] = Context->getObjCIdType();
2982
1
    // struct objc_object *superClass;
2983
1
    FieldTypes[1] = Context->getObjCIdType();
2984
1
2985
1
    // Create fields
2986
3
    for (unsigned i = 0; i < 2; 
++i2
) {
2987
2
      SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2988
2
                                                 SourceLocation(),
2989
2
                                                 SourceLocation(), nullptr,
2990
2
                                                 FieldTypes[i], nullptr,
2991
2
                                                 /*BitWidth=*/nullptr,
2992
2
                                                 /*Mutable=*/false,
2993
2
                                                 ICIS_NoInit));
2994
2
    }
2995
1
2996
1
    SuperStructDecl->completeDefinition();
2997
1
  }
2998
2
  return Context->getTagDeclType(SuperStructDecl);
2999
2
}
3000
3001
13
QualType RewriteModernObjC::getConstantStringStructType() {
3002
13
  if (!ConstantStringDecl) {
3003
3
    ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3004
3
                                            SourceLocation(), SourceLocation(),
3005
3
                         &Context->Idents.get("__NSConstantStringImpl"));
3006
3
    QualType FieldTypes[4];
3007
3
3008
3
    // struct objc_object *receiver;
3009
3
    FieldTypes[0] = Context->getObjCIdType();
3010
3
    // int flags;
3011
3
    FieldTypes[1] = Context->IntTy;
3012
3
    // char *str;
3013
3
    FieldTypes[2] = Context->getPointerType(Context->CharTy);
3014
3
    // long length;
3015
3
    FieldTypes[3] = Context->LongTy;
3016
3
3017
3
    // Create fields
3018
15
    for (unsigned i = 0; i < 4; 
++i12
) {
3019
12
      ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3020
12
                                                    ConstantStringDecl,
3021
12
                                                    SourceLocation(),
3022
12
                                                    SourceLocation(), nullptr,
3023
12
                                                    FieldTypes[i], nullptr,
3024
12
                                                    /*BitWidth=*/nullptr,
3025
12
                                                    /*Mutable=*/true,
3026
12
                                                    ICIS_NoInit));
3027
12
    }
3028
3
3029
3
    ConstantStringDecl->completeDefinition();
3030
3
  }
3031
13
  return Context->getTagDeclType(ConstantStringDecl);
3032
13
}
3033
3034
/// getFunctionSourceLocation - returns start location of a function
3035
/// definition. Complication arises when function has declared as
3036
/// extern "C" or extern "C" {...}
3037
static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3038
75
                                                 FunctionDecl *FD) {
3039
75
  if (FD->isExternC()  && 
!FD->isMain()16
) {
3040
16
    const DeclContext *DC = FD->getDeclContext();
3041
16
    if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3042
12
      // if it is extern "C" {...}, return function decl's own location.
3043
12
      if (!LSD->getRBraceLoc().isValid())
3044
4
        return LSD->getExternLoc();
3045
71
  }
3046
71
  if (FD->getStorageClass() != SC_None)
3047
5
    R.RewriteBlockLiteralFunctionDecl(FD);
3048
71
  return FD->getTypeSpecStartLoc();
3049
71
}
3050
3051
162
void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
3052
162
3053
162
  SourceLocation Location = D->getLocation();
3054
162
3055
162
  if (Location.isFileID() && GenerateLineInfo) {
3056
3
    std::string LineString("\n#line ");
3057
3
    PresumedLoc PLoc = SM->getPresumedLoc(Location);
3058
3
    LineString += utostr(PLoc.getLine());
3059
3
    LineString += " \"";
3060
3
    LineString += Lexer::Stringify(PLoc.getFilename());
3061
3
    if (isa<ObjCMethodDecl>(D))
3062
1
      LineString += "\"";
3063
2
    else LineString += "\"\n";
3064
3
3065
3
    Location = D->getBeginLoc();
3066
3
    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3067
2
      if (FD->isExternC()  && 
!FD->isMain()0
) {
3068
0
        const DeclContext *DC = FD->getDeclContext();
3069
0
        if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3070
0
          // if it is extern "C" {...}, return function decl's own location.
3071
0
          if (!LSD->getRBraceLoc().isValid())
3072
0
            Location = LSD->getExternLoc();
3073
0
      }
3074
2
    }
3075
3
    InsertText(Location, LineString);
3076
3
  }
3077
162
}
3078
3079
/// SynthMsgSendStretCallExpr - This routine translates message expression
3080
/// into a call to objc_msgSend_stret() entry point. Tricky part is that
3081
/// nil check on receiver must be performed before calling objc_msgSend_stret.
3082
/// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3083
/// msgSendType - function type of objc_msgSend_stret(...)
3084
/// returnType - Result type of the method being synthesized.
3085
/// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
3086
/// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
3087
/// starting with receiver.
3088
/// Method - Method being rewritten.
3089
Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
3090
                                                 QualType returnType,
3091
                                                 SmallVectorImpl<QualType> &ArgTypes,
3092
                                                 SmallVectorImpl<Expr*> &MsgExprs,
3093
12
                                                 ObjCMethodDecl *Method) {
3094
12
  // Now do the "normal" pointer to function cast.
3095
12
  QualType FuncType = getSimpleFunctionType(
3096
12
      returnType, ArgTypes, Method ? Method->isVariadic() : 
false0
);
3097
12
  QualType castType = Context->getPointerType(FuncType);
3098
12
3099
12
  // build type for containing the objc_msgSend_stret object.
3100
12
  static unsigned stretCount=0;
3101
12
  std::string name = "__Stret"; name += utostr(stretCount);
3102
12
  std::string str =
3103
12
    "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
3104
12
  str += "namespace {\n";
3105
12
  str += "struct "; str += name;
3106
12
  str += " {\n\t";
3107
12
  str += name;
3108
12
  str += "(id receiver, SEL sel";
3109
22
  for (unsigned i = 2; i < ArgTypes.size(); 
i++10
) {
3110
10
    std::string ArgName = "arg"; ArgName += utostr(i);
3111
10
    ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3112
10
    str += ", "; str += ArgName;
3113
10
  }
3114
12
  // could be vararg.
3115
19
  for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); 
i++7
) {
3116
7
    std::string ArgName = "arg"; ArgName += utostr(i);
3117
7
    MsgExprs[i]->getType().getAsStringInternal(ArgName,
3118
7
                                               Context->getPrintingPolicy());
3119
7
    str += ", "; str += ArgName;
3120
7
  }
3121
12
3122
12
  str += ") {\n";
3123
12
  str += "\t  unsigned size = sizeof(";
3124
12
  str += returnType.getAsString(Context->getPrintingPolicy()); str += ");\n";
3125
12
3126
12
  str += "\t  if (size == 1 || size == 2 || size == 4 || size == 8)\n";
3127
12
3128
12
  str += "\t    s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3129
12
  str += ")(void *)objc_msgSend)(receiver, sel";
3130
22
  for (unsigned i = 2; i < ArgTypes.size(); 
i++10
) {
3131
10
    str += ", arg"; str += utostr(i);
3132
10
  }
3133
12
  // could be vararg.
3134
19
  for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); 
i++7
) {
3135
7
    str += ", arg"; str += utostr(i);
3136
7
  }
3137
12
  str+= ");\n";
3138
12
3139
12
  str += "\t  else if (receiver == 0)\n";
3140
12
  str += "\t    memset((void*)&s, 0, sizeof(s));\n";
3141
12
  str += "\t  else\n";
3142
12
3143
12
  str += "\t    s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3144
12
  str += ")(void *)objc_msgSend_stret)(receiver, sel";
3145
22
  for (unsigned i = 2; i < ArgTypes.size(); 
i++10
) {
3146
10
    str += ", arg"; str += utostr(i);
3147
10
  }
3148
12
  // could be vararg.
3149
19
  for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); 
i++7
) {
3150
7
    str += ", arg"; str += utostr(i);
3151
7
  }
3152
12
  str += ");\n";
3153
12
3154
12
  str += "\t}\n";
3155
12
  str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3156
12
  str += " s;\n";
3157
12
  str += "};\n};\n\n";
3158
12
  SourceLocation FunLocStart;
3159
12
  if (CurFunctionDef)
3160
11
    FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3161
1
  else {
3162
1
    assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
3163
1
    FunLocStart = CurMethodDef->getBeginLoc();
3164
1
  }
3165
12
3166
12
  InsertText(FunLocStart, str);
3167
12
  ++stretCount;
3168
12
3169
12
  // AST for __Stretn(receiver, args).s;
3170
12
  IdentifierInfo *ID = &Context->Idents.get(name);
3171
12
  FunctionDecl *FD =
3172
12
      FunctionDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(),
3173
12
                           ID, FuncType, nullptr, SC_Extern, false, false);
3174
12
  DeclRefExpr *DRE = new (Context)
3175
12
      DeclRefExpr(*Context, FD, false, castType, VK_RValue, SourceLocation());
3176
12
  CallExpr *STCE = CallExpr::Create(*Context, DRE, MsgExprs, castType,
3177
12
                                    VK_LValue, SourceLocation());
3178
12
3179
12
  FieldDecl *FieldD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
3180
12
                                    SourceLocation(),
3181
12
                                    &Context->Idents.get("s"),
3182
12
                                    returnType, nullptr,
3183
12
                                    /*BitWidth=*/nullptr,
3184
12
                                    /*Mutable=*/true, ICIS_NoInit);
3185
12
  MemberExpr *ME = MemberExpr::CreateImplicit(
3186
12
      *Context, STCE, false, FieldD, FieldD->getType(), VK_LValue, OK_Ordinary);
3187
12
3188
12
  return ME;
3189
12
}
3190
3191
Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3192
                                    SourceLocation StartLoc,
3193
104
                                    SourceLocation EndLoc) {
3194
104
  if (!SelGetUidFunctionDecl)
3195
3
    SynthSelGetUidFunctionDecl();
3196
104
  if (!MsgSendFunctionDecl)
3197
25
    SynthMsgSendFunctionDecl();
3198
104
  if (!MsgSendSuperFunctionDecl)
3199
25
    SynthMsgSendSuperFunctionDecl();
3200
104
  if (!MsgSendStretFunctionDecl)
3201
25
    SynthMsgSendStretFunctionDecl();
3202
104
  if (!MsgSendSuperStretFunctionDecl)
3203
25
    SynthMsgSendSuperStretFunctionDecl();
3204
104
  if (!MsgSendFpretFunctionDecl)
3205
25
    SynthMsgSendFpretFunctionDecl();
3206
104
  if (!GetClassFunctionDecl)
3207
25
    SynthGetClassFunctionDecl();
3208
104
  if (!GetSuperClassFunctionDecl)
3209
25
    SynthGetSuperClassFunctionDecl();
3210
104
  if (!GetMetaClassFunctionDecl)
3211
25
    SynthGetMetaClassFunctionDecl();
3212
104
3213
104
  // default to objc_msgSend().
3214
104
  FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3215
104
  // May need to use objc_msgSend_stret() as well.
3216
104
  FunctionDecl *MsgSendStretFlavor = nullptr;
3217
104
  if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
3218
98
    QualType resultType = mDecl->getReturnType();
3219
98
    if (resultType->isRecordType())
3220
12
      MsgSendStretFlavor = MsgSendStretFunctionDecl;
3221
86
    else if (resultType->isRealFloatingType())
3222
0
      MsgSendFlavor = MsgSendFpretFunctionDecl;
3223
98
  }
3224
104
3225
104
  // Synthesize a call to objc_msgSend().
3226
104
  SmallVector<Expr*, 8> MsgExprs;
3227
104
  switch (Exp->getReceiverKind()) {
3228
0
  case ObjCMessageExpr::SuperClass: {
3229
0
    MsgSendFlavor = MsgSendSuperFunctionDecl;
3230
0
    if (MsgSendStretFlavor)
3231
0
      MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3232
0
    assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3233
0
3234
0
    ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3235
0
3236
0
    SmallVector<Expr*, 4> InitExprs;
3237
0
3238
0
    // set the receiver to self, the first argument to all methods.
3239
0
    InitExprs.push_back(
3240
0
      NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3241
0
                               CK_BitCast,
3242
0
                   new (Context) DeclRefExpr(*Context,
3243
0
                                             CurMethodDef->getSelfDecl(),
3244
0
                                             false,
3245
0
                                             Context->getObjCIdType(),
3246
0
                                             VK_RValue,
3247
0
                                             SourceLocation()))
3248
0
                        ); // set the 'receiver'.
3249
0
3250
0
    // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3251
0
    SmallVector<Expr*, 8> ClsExprs;
3252
0
    ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
3253
0
    // (Class)objc_getClass("CurrentClass")
3254
0
    CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3255
0
                                                 ClsExprs, StartLoc, EndLoc);
3256
0
    ClsExprs.clear();
3257
0
    ClsExprs.push_back(Cls);
3258
0
    Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
3259
0
                                       StartLoc, EndLoc);
3260
0
3261
0
    // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3262
0
    // To turn off a warning, type-cast to 'id'
3263
0
    InitExprs.push_back( // set 'super class', using class_getSuperclass().
3264
0
                        NoTypeInfoCStyleCastExpr(Context,
3265
0
                                                 Context->getObjCIdType(),
3266
0
                                                 CK_BitCast, Cls));
3267
0
    // struct __rw_objc_super
3268
0
    QualType superType = getSuperStructType();
3269
0
    Expr *SuperRep;
3270
0
3271
0
    if (LangOpts.MicrosoftExt) {
3272
0
      SynthSuperConstructorFunctionDecl();
3273
0
      // Simulate a constructor call...
3274
0
      DeclRefExpr *DRE = new (Context)
3275
0
          DeclRefExpr(*Context, SuperConstructorFunctionDecl, false, superType,
3276
0
                      VK_LValue, SourceLocation());
3277
0
      SuperRep = CallExpr::Create(*Context, DRE, InitExprs, superType,
3278
0
                                  VK_LValue, SourceLocation());
3279
0
      // The code for super is a little tricky to prevent collision with
3280
0
      // the structure definition in the header. The rewriter has it's own
3281
0
      // internal definition (__rw_objc_super) that is uses. This is why
3282
0
      // we need the cast below. For example:
3283
0
      // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
3284
0
      //
3285
0
      SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3286
0
                               Context->getPointerType(SuperRep->getType()),
3287
0
                                             VK_RValue, OK_Ordinary,
3288
0
                                             SourceLocation(), false);
3289
0
      SuperRep = NoTypeInfoCStyleCastExpr(Context,
3290
0
                                          Context->getPointerType(superType),
3291
0
                                          CK_BitCast, SuperRep);
3292
0
    } else {
3293
0
      // (struct __rw_objc_super) { <exprs from above> }
3294
0
      InitListExpr *ILE =
3295
0
        new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
3296
0
                                   SourceLocation());
3297
0
      TypeSourceInfo *superTInfo
3298
0
        = Context->getTrivialTypeSourceInfo(superType);
3299
0
      SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3300
0
                                                   superType, VK_LValue,
3301
0
                                                   ILE, false);
3302
0
      // struct __rw_objc_super *
3303
0
      SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3304
0
                               Context->getPointerType(SuperRep->getType()),
3305
0
                                             VK_RValue, OK_Ordinary,
3306
0
                                             SourceLocation(), false);
3307
0
    }
3308
0
    MsgExprs.push_back(SuperRep);
3309
0
    break;
3310
0
  }
3311
0
3312
23
  case ObjCMessageExpr::Class: {
3313
23
    SmallVector<Expr*, 8> ClsExprs;
3314
23
    ObjCInterfaceDecl *Class
3315
23
      = Exp->getClassReceiver()->castAs<ObjCObjectType>()->getInterface();
3316
23
    IdentifierInfo *clsName = Class->getIdentifier();
3317
23
    ClsExprs.push_back(getStringLiteral(clsName->getName()));
3318
23
    CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
3319
23
                                                 StartLoc, EndLoc);
3320
23
    CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3321
23
                                                 Context->getObjCIdType(),
3322
23
                                                 CK_BitCast, Cls);
3323
23
    MsgExprs.push_back(ArgExpr);
3324
23
    break;
3325
0
  }
3326
0
3327
1
  case ObjCMessageExpr::SuperInstance:{
3328
1
    MsgSendFlavor = MsgSendSuperFunctionDecl;
3329
1
    if (MsgSendStretFlavor)
3330
0
      MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3331
1
    assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3332
1
    ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3333
1
    SmallVector<Expr*, 4> InitExprs;
3334
1
3335
1
    InitExprs.push_back(
3336
1
      NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3337
1
                               CK_BitCast,
3338
1
                   new (Context) DeclRefExpr(*Context,
3339
1
                                             CurMethodDef->getSelfDecl(),
3340
1
                                             false,
3341
1
                                             Context->getObjCIdType(),
3342
1
                                             VK_RValue, SourceLocation()))
3343
1
                        ); // set the 'receiver'.
3344
1
3345
1
    // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3346
1
    SmallVector<Expr*, 8> ClsExprs;
3347
1
    ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
3348
1
    // (Class)objc_getClass("CurrentClass")
3349
1
    CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
3350
1
                                                 StartLoc, EndLoc);
3351
1
    ClsExprs.clear();
3352
1
    ClsExprs.push_back(Cls);
3353
1
    Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
3354
1
                                       StartLoc, EndLoc);
3355
1
3356
1
    // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3357
1
    // To turn off a warning, type-cast to 'id'
3358
1
    InitExprs.push_back(
3359
1
      // set 'super class', using class_getSuperclass().
3360
1
      NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3361
1
                               CK_BitCast, Cls));
3362
1
    // struct __rw_objc_super
3363
1
    QualType superType = getSuperStructType();
3364
1
    Expr *SuperRep;
3365
1
3366
1
    if (LangOpts.MicrosoftExt) {
3367
1
      SynthSuperConstructorFunctionDecl();
3368
1
      // Simulate a constructor call...
3369
1
      DeclRefExpr *DRE = new (Context)
3370
1
          DeclRefExpr(*Context, SuperConstructorFunctionDecl, false, superType,
3371
1
                      VK_LValue, SourceLocation());
3372
1
      SuperRep = CallExpr::Create(*Context, DRE, InitExprs, superType,
3373
1
                                  VK_LValue, SourceLocation());
3374
1
      // The code for super is a little tricky to prevent collision with
3375
1
      // the structure definition in the header. The rewriter has it's own
3376
1
      // internal definition (__rw_objc_super) that is uses. This is why
3377
1
      // we need the cast below. For example:
3378
1
      // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
3379
1
      //
3380
1
      SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3381
1
                               Context->getPointerType(SuperRep->getType()),
3382
1
                               VK_RValue, OK_Ordinary,
3383
1
                               SourceLocation(), false);
3384
1
      SuperRep = NoTypeInfoCStyleCastExpr(Context,
3385
1
                               Context->getPointerType(superType),
3386
1
                               CK_BitCast, SuperRep);
3387
1
    } else {
3388
0
      // (struct __rw_objc_super) { <exprs from above> }
3389
0
      InitListExpr *ILE =
3390
0
        new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
3391
0
                                   SourceLocation());
3392
0
      TypeSourceInfo *superTInfo
3393
0
        = Context->getTrivialTypeSourceInfo(superType);
3394
0
      SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3395
0
                                                   superType, VK_RValue, ILE,
3396
0
                                                   false);
3397
0
    }
3398
1
    MsgExprs.push_back(SuperRep);
3399
1
    break;
3400
0
  }
3401
0
3402
80
  case ObjCMessageExpr::Instance: {
3403
80
    // Remove all type-casts because it may contain objc-style types; e.g.
3404
80
    // Foo<Proto> *.
3405
80
    Expr *recExpr = Exp->getInstanceReceiver();
3406
81
    while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3407
1
      recExpr = CE->getSubExpr();
3408
80
    CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3409
80
                    ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3410
0
                                     ? CK_BlockPointerToObjCPointerCast
3411
0
                                     : CK_CPointerToObjCPointerCast;
3412
80
3413
80
    recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3414
80
                                       CK, recExpr);
3415
80
    MsgExprs.push_back(recExpr);
3416
80
    break;
3417
104
  }
3418
104
  }
3419
104
3420
104
  // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3421
104
  SmallVector<Expr*, 8> SelExprs;
3422
104
  SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
3423
104
  CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3424
104
                                                  SelExprs, StartLoc, EndLoc);
3425
104
  MsgExprs.push_back(SelExp);
3426
104
3427
104
  // Now push any user supplied arguments.
3428
158
  for (unsigned i = 0; i < Exp->getNumArgs(); 
i++54
) {
3429
54
    Expr *userExpr = Exp->getArg(i);
3430
54
    // Make all implicit casts explicit...ICE comes in handy:-)
3431
54
    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3432
28
      // Reuse the ICE type, it is exactly what the doctor ordered.
3433
28
      QualType type = ICE->getType();
3434
28
      if (needToScanForQualifiers(type))
3435
0
        type = Context->getObjCIdType();
3436
28
      // Make sure we convert "type (^)(...)" to "type (*)(...)".
3437
28
      (void)convertBlockPointerToFunctionPointer(type);
3438
28
      const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3439
28
      CastKind CK;
3440
28
      if (SubExpr->getType()->isIntegralType(*Context) &&
3441
28
          
type->isBooleanType()13
) {
3442
0
        CK = CK_IntegralToBoolean;
3443
28
      } else if (type->isObjCObjectPointerType()) {
3444
13
        if (SubExpr->getType()->isBlockPointerType()) {
3445
0
          CK = CK_BlockPointerToObjCPointerCast;
3446
13
        } else if (SubExpr->getType()->isPointerType()) {
3447
0
          CK = CK_CPointerToObjCPointerCast;
3448
13
        } else {
3449
13
          CK = CK_BitCast;
3450
13
        }
3451
15
      } else {
3452
15
        CK = CK_BitCast;
3453
15
      }
3454
28
3455
28
      userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3456
28
    }
3457
26
    // Make id<P...> cast into an 'id' cast.
3458
26
    else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3459
3
      if (CE->getType()->isObjCQualifiedIdType()) {
3460
0
        while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3461
0
          userExpr = CE->getSubExpr();
3462
0
        CastKind CK;
3463
0
        if (userExpr->getType()->isIntegralType(*Context)) {
3464
0
          CK = CK_IntegralToPointer;
3465
0
        } else if (userExpr->getType()->isBlockPointerType()) {
3466
0
          CK = CK_BlockPointerToObjCPointerCast;
3467
0
        } else if (userExpr->getType()->isPointerType()) {
3468
0
          CK = CK_CPointerToObjCPointerCast;
3469
0
        } else {
3470
0
          CK = CK_BitCast;
3471
0
        }
3472
0
        userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3473
0
                                            CK, userExpr);
3474
0
      }
3475
3
    }
3476
54
    MsgExprs.push_back(userExpr);
3477
54
    // We've transferred the ownership to MsgExprs. For now, we *don't* null
3478
54
    // out the argument in the original expression (since we aren't deleting
3479
54
    // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3480
54
    //Exp->setArg(i, 0);
3481
54
  }
3482
104
  // Generate the funky cast.
3483
104
  CastExpr *cast;
3484
104
  SmallVector<QualType, 8> ArgTypes;
3485
104
  QualType returnType;
3486
104
3487
104
  // Push 'id' and 'SEL', the 2 implicit arguments.
3488
104
  if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3489
1
    ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3490
103
  else
3491
103
    ArgTypes.push_back(Context->getObjCIdType());
3492
104
  ArgTypes.push_back(Context->getObjCSelType());
3493
104
  if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3494
98
    // Push any user argument types.
3495
98
    for (const auto *PI : OMD->parameters()) {
3496
44
      QualType t = PI->getType()->isObjCQualifiedIdType()
3497
44
                     ? 
Context->getObjCIdType()0
3498
44
                     : PI->getType();
3499
44
      // Make sure we convert "t (^)(...)" to "t (*)(...)".
3500
44
      (void)convertBlockPointerToFunctionPointer(t);
3501
44
      ArgTypes.push_back(t);
3502
44
    }
3503
98
    returnType = Exp->getType();
3504
98
    convertToUnqualifiedObjCType(returnType);
3505
98
    (void)convertBlockPointerToFunctionPointer(returnType);
3506
98
  } else {
3507
6
    returnType = Context->getObjCIdType();
3508
6
  }
3509
104
  // Get the type, we will need to reference it in a couple spots.
3510
104
  QualType msgSendType = MsgSendFlavor->getType();
3511
104
3512
104
  // Create a reference to the objc_msgSend() declaration.
3513
104
  DeclRefExpr *DRE = new (Context) DeclRefExpr(
3514
104
      *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
3515
104
3516
104
  // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3517
104
  // If we don't do this cast, we get the following bizarre warning/note:
3518
104
  // xx.m:13: warning: function called through a non-compatible type
3519
104
  // xx.m:13: note: if this code is reached, the program will abort
3520
104
  cast = NoTypeInfoCStyleCastExpr(Context,
3521
104
                                  Context->getPointerType(Context->VoidTy),
3522
104
                                  CK_BitCast, DRE);
3523
104
3524
104
  // Now do the "normal" pointer to function cast.
3525
104
  // If we don't have a method decl, force a variadic cast.
3526
104
  const ObjCMethodDecl *MD = Exp->getMethodDecl();
3527
104
  QualType castType =
3528
104
    getSimpleFunctionType(returnType, ArgTypes, MD ? 
MD->isVariadic()98
:
true6
);
3529
104
  castType = Context->getPointerType(castType);
3530
104
  cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3531
104
                                  cast);
3532
104
3533
104
  // Don't forget the parens to enforce the proper binding.
3534
104
  ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3535
104
3536
104
  const FunctionType *FT = msgSendType->castAs<FunctionType>();
3537
104
  CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
3538
104
                                  VK_RValue, EndLoc);
3539
104
  Stmt *ReplacingStmt = CE;
3540
104
  if (MsgSendStretFlavor) {
3541
12
    // We have the method which returns a struct/union. Must also generate
3542
12
    // call to objc_msgSend_stret and hang both varieties on a conditional
3543
12
    // expression which dictate which one to envoke depending on size of
3544
12
    // method's return type.
3545
12
3546
12
    Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3547
12
                                           returnType,
3548
12
                                           ArgTypes, MsgExprs,
3549
12
                                           Exp->getMethodDecl());
3550
12
    ReplacingStmt = STCE;
3551
12
  }
3552
104
  // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3553
104
  return ReplacingStmt;
3554
104
}
3555
3556
71
Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3557
71
  Stmt *ReplacingStmt =
3558
71
      SynthMessageExpr(Exp, Exp->getBeginLoc(), Exp->getEndLoc());
3559
71
3560
71
  // Now do the actual rewrite.
3561
71
  ReplaceStmt(Exp, ReplacingStmt);
3562
71
3563
71
  // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3564
71
  return ReplacingStmt;
3565
71
}
3566
3567
// typedef struct objc_object Protocol;
3568
4
QualType RewriteModernObjC::getProtocolType() {
3569
4
  if (!ProtocolTypeDecl) {
3570
1
    TypeSourceInfo *TInfo
3571
1
      = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3572
1
    ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3573
1
                                           SourceLocation(), SourceLocation(),
3574
1
                                           &Context->Idents.get("Protocol"),
3575
1
                                           TInfo);
3576
1
  }
3577
4
  return Context->getTypeDeclType(ProtocolTypeDecl);
3578
4
}
3579
3580
/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3581
/// a synthesized/forward data reference (to the protocol's metadata).
3582
/// The forward references (and metadata) are generated in
3583
/// RewriteModernObjC::HandleTranslationUnit().
3584
2
Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
3585
2
  std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3586
2
                      Exp->getProtocol()->getNameAsString();
3587
2
  IdentifierInfo *ID = &Context->Idents.get(Name);
3588
2
  VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3589
2
                                SourceLocation(), ID, getProtocolType(),
3590
2
                                nullptr, SC_Extern);
3591
2
  DeclRefExpr *DRE = new (Context) DeclRefExpr(
3592
2
      *Context, VD, false, getProtocolType(), VK_LValue, SourceLocation());
3593
2
  CastExpr *castExpr = NoTypeInfoCStyleCastExpr(
3594
2
      Context, Context->getPointerType(DRE->getType()), CK_BitCast, DRE);
3595
2
  ReplaceStmt(Exp, castExpr);
3596
2
  ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3597
2
  // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3598
2
  return castExpr;
3599
2
}
3600
3601
/// IsTagDefinedInsideClass - This routine checks that a named tagged type
3602
/// is defined inside an objective-c class. If so, it returns true.
3603
bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
3604
                                                TagDecl *Tag,
3605
39
                                                bool &IsNamedDefinition) {
3606
39
  if (!IDecl)
3607
0
    return false;
3608
39
  SourceLocation TagLocation;
3609
39
  if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3610
31
    RD = RD->getDefinition();
3611
31
    if (!RD || !RD->getDeclName().getAsIdentifierInfo())
3612
16
      return false;
3613
15
    IsNamedDefinition = true;
3614
15
    TagLocation = RD->getLocation();
3615
15
    return Context->getSourceManager().isBeforeInTranslationUnit(
3616
15
                                          IDecl->getLocation(), TagLocation);
3617
15
  }
3618
8
  if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3619
8
    if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3620
4
      return false;
3621
4
    IsNamedDefinition = true;
3622
4
    TagLocation = ED->getLocation();
3623
4
    return Context->getSourceManager().isBeforeInTranslationUnit(
3624
4
                                          IDecl->getLocation(), TagLocation);
3625
4
  }
3626
0
  return false;
3627
0
}
3628
3629
/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
3630
/// It handles elaborated types, as well as enum types in the process.
3631
bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3632
297
                                                 std::string &Result) {
3633
297
  if (isa<TypedefType>(Type)) {
3634
44
    Result += "\t";
3635
44
    return false;
3636
44
  }
3637
253
3638
253
  if (Type->isArrayType()) {
3639
2
    QualType ElemTy = Context->getBaseElementType(Type);
3640
2
    return RewriteObjCFieldDeclType(ElemTy, Result);
3641
2
  }
3642
251
  else if (Type->isRecordType()) {
3643
68
    RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
3644
68
    if (RD->isCompleteDefinition()) {
3645
68
      if (RD->isStruct())
3646
61
        Result += "\n\tstruct ";
3647
7
      else if (RD->isUnion())
3648
7
        Result += "\n\tunion ";
3649
7
      else
3650
7
        assert(false && "class not allowed as an ivar type");
3651
68
3652
68
      Result += RD->getName();
3653
68
      if (GlobalDefinedTags.count(RD)) {
3654
27
        // struct/union is defined globally, use it.
3655
27
        Result += " ";
3656
27
        return true;
3657
27
      }
3658
41
      Result += " {\n";
3659
41
      for (auto *FD : RD->fields())
3660
102
        RewriteObjCFieldDecl(FD, Result);
3661
41
      Result += "\t} ";
3662
41
      return true;
3663
41
    }
3664
183
  }
3665
183
  else if (Type->isEnumeralType()) {
3666
16
    EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
3667
16
    if (ED->isCompleteDefinition()) {
3668
16
      Result += "\n\tenum ";
3669
16
      Result += ED->getName();
3670
16
      if (GlobalDefinedTags.count(ED)) {
3671
9
        // Enum is globall defined, use it.
3672
9
        Result += " ";
3673
9
        return true;
3674
9
      }
3675
7
3676
7
      Result += " {\n";
3677
13
      for (const auto *EC : ED->enumerators()) {
3678
13
        Result += "\t"; Result += EC->getName(); Result += " = ";
3679
13
        llvm::APSInt Val = EC->getInitVal();
3680
13
        Result += Val.toString(10);
3681
13
        Result += ",\n";
3682
13
      }
3683
7
      Result += "\t} ";
3684
7
      return true;
3685
7
    }
3686
16
  }
3687
167
3688
167
  Result += "\t";
3689
167
  convertObjCTypeToCStyleType(Type);
3690
167
  return false;
3691
167
}
3692
3693
3694
/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3695
/// It handles elaborated types, as well as enum types in the process.
3696
void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3697
269
                                             std::string &Result) {
3698
269
  QualType Type = fieldDecl->getType();
3699
269
  std::string Name = fieldDecl->getNameAsString();
3700
269
3701
269
  bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3702
269
  if (!EleboratedType)
3703
211
    Type.getAsStringInternal(Name, Context->getPrintingPolicy());
3704
269
  Result += Name;
3705
269
  if (fieldDecl->isBitField()) {
3706
64
    Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3707
64
  }
3708
205
  else if (EleboratedType && 
Type->isArrayType()58
) {
3709
1
    const ArrayType *AT = Context->getAsArrayType(Type);
3710
2
    do {
3711
2
      if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
3712
2
        Result += "[";
3713
2
        llvm::APInt Dim = CAT->getSize();
3714
2
        Result += utostr(Dim.getZExtValue());
3715
2
        Result += "]";
3716
2
      }
3717
2
      AT = Context->getAsArrayType(AT->getElementType());
3718
2
    } while (AT);
3719
1
  }
3720
269
3721
269
  Result += ";\n";
3722
269
}
3723
3724
/// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3725
/// named aggregate types into the input buffer.
3726
void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3727
213
                                             std::string &Result) {
3728
213
  QualType Type = fieldDecl->getType();
3729
213
  if (isa<TypedefType>(Type))
3730
42
    return;
3731
171
  if (Type->isArrayType())
3732
2
    Type = Context->getBaseElementType(Type);
3733
171
3734
171
  auto *IDecl = dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
3735
171
3736
171
  TagDecl *TD = nullptr;
3737
171
  if (Type->isRecordType()) {
3738
43
    TD = Type->castAs<RecordType>()->getDecl();
3739
43
  }
3740
128
  else if (Type->isEnumeralType()) {
3741
13
    TD = Type->castAs<EnumType>()->getDecl();
3742
13
  }
3743
171
3744
171
  if (TD) {
3745
56
    if (GlobalDefinedTags.count(TD))
3746
17
      return;
3747
39
3748
39
    bool IsNamedDefinition = false;
3749
39
    if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3750
14
      RewriteObjCFieldDeclType(Type, Result);
3751
14
      Result += ";";
3752
14
    }
3753
39
    if (IsNamedDefinition)
3754
19
      GlobalDefinedTags.insert(TD);
3755
39
  }
3756
171
}
3757
3758
171
unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) {
3759
171
  const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3760
171
  if (ObjCInterefaceHasBitfieldGroups.count(CDecl)) {
3761
160
    return IvarGroupNumber[IV];
3762
160
  }
3763
11
  unsigned GroupNo = 0;
3764
11
  SmallVector<const ObjCIvarDecl *, 8> IVars;
3765
11
  for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3766
90
       IVD; 
IVD = IVD->getNextIvar()79
)
3767
79
    IVars.push_back(IVD);
3768
11
3769
56
  for (unsigned i = 0, e = IVars.size(); i < e; 
i++45
)
3770
45
    if (IVars[i]->isBitField()) {
3771
12
      IvarGroupNumber[IVars[i++]] = ++GroupNo;
3772
46
      while (i < e && 
IVars[i]->isBitField()39
)
3773
34
        IvarGroupNumber[IVars[i++]] = GroupNo;
3774
12
      if (i < e)
3775
5
        --i;
3776
12
    }
3777
11
3778
11
  ObjCInterefaceHasBitfieldGroups.insert(CDecl);
3779
11
  return IvarGroupNumber[IV];
3780
11
}
3781
3782
QualType RewriteModernObjC::SynthesizeBitfieldGroupStructType(
3783
                              ObjCIvarDecl *IV,
3784
12
                              SmallVectorImpl<ObjCIvarDecl *> &IVars) {
3785
12
  std::string StructTagName;
3786
12
  ObjCIvarBitfieldGroupType(IV, StructTagName);
3787
12
  RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct,
3788
12
                                      Context->getTranslationUnitDecl(),
3789
12
                                      SourceLocation(), SourceLocation(),
3790
12
                                      &Context->Idents.get(StructTagName));
3791
58
  for (unsigned i=0, e = IVars.size(); i < e; 
i++46
) {
3792
46
    ObjCIvarDecl *Ivar = IVars[i];
3793
46
    RD->addDecl(FieldDecl::Create(*Context, RD, SourceLocation(), SourceLocation(),
3794
46
                                  &Context->Idents.get(Ivar->getName()),
3795
46
                                  Ivar->getType(),
3796
46
                                  nullptr, /*Expr *BW */Ivar->getBitWidth(),
3797
46
                                  false, ICIS_NoInit));
3798
46
  }
3799
12
  RD->completeDefinition();
3800
12
  return Context->getTagDeclType(RD);
3801
12
}
3802
3803
42
QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV) {
3804
42
  const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3805
42
  unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3806
42
  std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo);
3807
42
  if (GroupRecordType.count(tuple))
3808
31
    return GroupRecordType[tuple];
3809
11
3810
11
  SmallVector<ObjCIvarDecl *, 8> IVars;
3811
11
  for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3812
90
       IVD; 
IVD = IVD->getNextIvar()79
) {
3813
79
    if (IVD->isBitField())
3814
46
      IVars.push_back(const_cast<ObjCIvarDecl *>(IVD));
3815
33
    else {
3816
33
      if (!IVars.empty()) {
3817
5
        unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3818
5
        // Generate the struct type for this group of bitfield ivars.
3819
5
        GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3820
5
          SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3821
5
        IVars.clear();
3822
5
      }
3823
33
    }
3824
79
  }
3825
11
  if (!IVars.empty()) {
3826
7
    // Do the last one.
3827
7
    unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3828
7
    GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3829
7
      SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3830
7
  }
3831
11
  QualType RetQT = GroupRecordType[tuple];
3832
11
  assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL");
3833
11
3834
11
  return RetQT;
3835
11
}
3836
3837
/// ObjCIvarBitfieldGroupDecl - Names field decl. for ivar bitfield group.
3838
/// Name would be: classname__GRBF_n where n is the group number for this ivar.
3839
void RewriteModernObjC::ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV,
3840
82
                                                  std::string &Result) {
3841
82
  const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3842
82
  Result += CDecl->getName();
3843
82
  Result += "__GRBF_";
3844
82
  unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3845
82
  Result += utostr(GroupNo);
3846
82
}
3847
3848
/// ObjCIvarBitfieldGroupType - Names struct type for ivar bitfield group.
3849
/// Name of the struct would be: classname__T_n where n is the group number for
3850
/// this ivar.
3851
void RewriteModernObjC::ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV,
3852
24
                                                  std::string &Result) {
3853
24
  const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3854
24
  Result += CDecl->getName();
3855
24
  Result += "__T_";
3856
24
  unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3857
24
  Result += utostr(GroupNo);
3858
24
}
3859
3860
/// ObjCIvarBitfieldGroupOffset - Names symbol for ivar bitfield group field offset.
3861
/// Name would be: OBJC_IVAR_$_classname__GRBF_n where n is the group number for
3862
/// this ivar.
3863
void RewriteModernObjC::ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV,
3864
44
                                                    std::string &Result) {
3865
44
  Result += "OBJC_IVAR_$_";
3866
44
  ObjCIvarBitfieldGroupDecl(IV, Result);
3867
44
}
3868
3869
46
#define SKIP_BITFIELDS(IX, ENDIX, VEC) { \
3870
204
      while ((IX < ENDIX) && 
VEC[IX]->isBitField()178
) \
3871
158
        ++IX; \
3872
46
      if (IX < ENDIX) \
3873
46
        
--IX20
; \
3874
46
}
3875
3876
/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3877
/// an objective-c class with ivars.
3878
void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3879
152
                                               std::string &Result) {
3880
152
  assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3881
152
  assert(CDecl->getName() != "" &&
3882
152
         "Name missing in SynthesizeObjCInternalStruct");
3883
152
  ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
3884
152
  SmallVector<ObjCIvarDecl *, 8> IVars;
3885
152
  for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3886
365
       IVD; 
IVD = IVD->getNextIvar()213
)
3887
213
    IVars.push_back(IVD);
3888
152
3889
152
  SourceLocation LocStart = CDecl->getBeginLoc();
3890
152
  SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
3891
152
3892
152
  const char *startBuf = SM->getCharacterData(LocStart);
3893
152
  const char *endBuf = SM->getCharacterData(LocEnd);
3894
152
3895
152
  // If no ivars and no root or if its root, directly or indirectly,
3896
152
  // have no ivars (thus not synthesized) then no need to synthesize this class.
3897
152
  if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
3898
152
      
(88
!RCDecl88
||
!ObjCSynthesizedStructs.count(RCDecl)15
)) {
3899
86
    endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3900
86
    ReplaceText(LocStart, endBuf-startBuf, Result);
3901
86
    return;
3902
86
  }
3903
66
3904
66
  // Insert named struct/union definitions inside class to
3905
66
  // outer scope. This follows semantics of locally defined
3906
66
  // struct/unions in objective-c classes.
3907
279
  
for (unsigned i = 0, e = IVars.size(); 66
i < e;
i++213
)
3908
213
    RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
3909
66
3910
66
  // Insert named structs which are syntheized to group ivar bitfields
3911
66
  // to outer scope as well.
3912
245
  for (unsigned i = 0, e = IVars.size(); i < e; 
i++179
)
3913
179
    if (IVars[i]->isBitField()) {
3914
12
      ObjCIvarDecl *IV = IVars[i];
3915
12
      QualType QT = GetGroupRecordTypeForObjCIvarBitfield(IV);
3916
12
      RewriteObjCFieldDeclType(QT, Result);
3917
12
      Result += ";";
3918
12
      // skip over ivar bitfields in this group.
3919
12
      SKIP_BITFIELDS(i , e, IVars);
3920
12
    }
3921
66
3922
66
  Result += "\nstruct ";
3923
66
  Result += CDecl->getNameAsString();
3924
66
  Result += "_IMPL {\n";
3925
66
3926
66
  if (RCDecl && 
ObjCSynthesizedStructs.count(RCDecl)14
) {
3927
9
    Result += "\tstruct "; Result += RCDecl->getNameAsString();
3928
9
    Result += "_IMPL "; Result += RCDecl->getNameAsString();
3929
9
    Result += "_IVARS;\n";
3930
9
  }
3931
66
3932
245
  for (unsigned i = 0, e = IVars.size(); i < e; 
i++179
) {
3933
179
    if (IVars[i]->isBitField()) {
3934
12
      ObjCIvarDecl *IV = IVars[i];
3935
12
      Result += "\tstruct ";
3936
12
      ObjCIvarBitfieldGroupType(IV, Result); Result += " ";
3937
12
      ObjCIvarBitfieldGroupDecl(IV, Result); Result += ";\n";
3938
12
      // skip over ivar bitfields in this group.
3939
12
      SKIP_BITFIELDS(i , e, IVars);
3940
12
    }
3941
167
    else
3942
167
      RewriteObjCFieldDecl(IVars[i], Result);
3943
179
  }
3944
66
3945
66
  Result += "};\n";
3946
66
  endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3947
66
  ReplaceText(LocStart, endBuf-startBuf, Result);
3948
66
  // Mark this struct as having been generated.
3949
66
  if (!ObjCSynthesizedStructs.insert(CDecl).second)
3950
66
    
llvm_unreachable0
("struct already synthesize- RewriteObjCInternalStruct");
3951
66
}
3952
3953
/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3954
/// have been referenced in an ivar access expression.
3955
void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3956
152
                                                  std::string &Result) {
3957
152
  // write out ivar offset symbols which have been referenced in an ivar
3958
152
  // access expression.
3959
152
  llvm::SmallSetVector<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3960
152
3961
152
  if (Ivars.empty())
3962
109
    return;
3963
43
3964
43
  llvm::DenseSet<std::pair<const ObjCInterfaceDecl*, unsigned> > GroupSymbolOutput;
3965
85
  for (ObjCIvarDecl *IvarDecl : Ivars) {
3966
85
    const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface();
3967
85
    unsigned GroupNo = 0;
3968
85
    if (IvarDecl->isBitField()) {
3969
11
      GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl);
3970
11
      if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo)))
3971
8
        continue;
3972
77
    }
3973
77
    Result += "\n";
3974
77
    if (LangOpts.MicrosoftExt)
3975
77
      Result += "__declspec(allocate(\".objc_ivar$B\")) ";
3976
77
    Result += "extern \"C\" ";
3977
77
    if (LangOpts.MicrosoftExt &&
3978
77
        IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
3979
77
        
IvarDecl->getAccessControl() != ObjCIvarDecl::Package50
)
3980
50
        Result += "__declspec(dllimport) ";
3981
77
3982
77
    Result += "unsigned long ";
3983
77
    if (IvarDecl->isBitField()) {
3984
3
      ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
3985
3
      GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo));
3986
3
    }
3987
74
    else
3988
74
      WriteInternalIvarName(CDecl, IvarDecl, Result);
3989
77
    Result += ";";
3990
77
  }
3991
43
}
3992
3993
//===----------------------------------------------------------------------===//
3994
// Meta Data Emission
3995
//===----------------------------------------------------------------------===//
3996
3997
/// RewriteImplementations - This routine rewrites all method implementations
3998
/// and emits meta-data.
3999
4000
52
void RewriteModernObjC::RewriteImplementations() {
4001
52
  int ClsDefCount = ClassImplementation.size();
4002
52
  int CatDefCount = CategoryImplementation.size();
4003
52
4004
52
  // Rewrite implemented methods
4005
140
  for (int i = 0; i < ClsDefCount; 
i++88
) {
4006
88
    ObjCImplementationDecl *OIMP = ClassImplementation[i];
4007
88
    ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
4008
88
    if (CDecl->isImplicitInterfaceDecl())
4009
88
      assert(false &&
4010
88
             "Legacy implicit interface rewriting not supported in moder abi");
4011
88
    RewriteImplementationDecl(OIMP);
4012
88
  }
4013
52
4014
57
  for (int i = 0; i < CatDefCount; 
i++5
) {
4015
5
    ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
4016
5
    ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
4017
5
    if (CDecl->isImplicitInterfaceDecl())
4018
5
      assert(false &&
4019
5
             "Legacy implicit interface rewriting not supported in moder abi");
4020
5
    RewriteImplementationDecl(CIMP);
4021
5
  }
4022
52
}
4023
4024
void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
4025
                                     const std::string &Name,
4026
291
                                     ValueDecl *VD, bool def) {
4027
291
  assert(BlockByRefDeclNo.count(VD) &&
4028
291
         "RewriteByRefString: ByRef decl missing");
4029
291
  if (def)
4030
83
    ResultStr += "struct ";
4031
291
  ResultStr += "__Block_byref_" + Name +
4032
291
    "_" + utostr(BlockByRefDeclNo[VD]) ;
4033
291
}
4034
4035
907
static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4036
907
  if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4037
436
    return (Var->isFunctionOrMethodVarDecl() && 
!Var->hasLocalStorage()176
);
4038
471
  return false;
4039
471
}
4040
4041
std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4042
                                                   StringRef funcName,
4043
80
                                                   std::string Tag) {
4044
80
  const FunctionType *AFT = CE->getFunctionType();
4045
80
  QualType RT = AFT->getReturnType();
4046
80
  std::string StructRef = "struct " + Tag;
4047
80
  SourceLocation BlockLoc = CE->getExprLoc();
4048
80
  std::string S;
4049
80
  ConvertSourceLocationToLineDirective(BlockLoc, S);
4050
80
4051
80
  S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
4052
80
         funcName.str() + "_block_func_" + utostr(i);
4053
80
4054
80
  BlockDecl *BD = CE->getBlockDecl();
4055
80
4056
80
  if (isa<FunctionNoProtoType>(AFT)) {
4057
0
    // No user-supplied arguments. Still need to pass in a pointer to the
4058
0
    // block (to reference imported block decl refs).
4059
0
    S += "(" + StructRef + " *__cself)";
4060
80
  } else if (BD->param_empty()) {
4061
70
    S += "(" + StructRef + " *__cself)";
4062
70
  } else {
4063
10
    const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4064
10
    assert(FT && "SynthesizeBlockFunc: No function proto");
4065
10
    S += '(';
4066
10
    // first add the implicit argument.
4067
10
    S += StructRef + " *__cself, ";
4068
10
    std::string ParamStr;
4069
10
    for (BlockDecl::param_iterator AI = BD->param_begin(),
4070
23
         E = BD->param_end(); AI != E; 
++AI13
) {
4071
13
      if (AI != BD->param_begin()) 
S += ", "3
;
4072
13
      ParamStr = (*AI)->getNameAsString();
4073
13
      QualType QT = (*AI)->getType();
4074
13
      (void)convertBlockPointerToFunctionPointer(QT);
4075
13
      QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
4076
13
      S += ParamStr;
4077
13
    }
4078
10
    if (FT->isVariadic()) {
4079
0
      if (!BD->param_empty()) S += ", ";
4080
0
      S += "...";
4081
0
    }
4082
10
    S += ')';
4083
10
  }
4084
80
  S += " {\n";
4085
80
4086
80
  // Create local declarations to avoid rewriting all closure decl ref exprs.
4087
80
  // First, emit a declaration for all "by ref" decls.
4088
80
  for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
4089
121
       E = BlockByRefDecls.end(); I != E; 
++I41
) {
4090
41
    S += "  ";
4091
41
    std::string Name = (*I)->getNameAsString();
4092
41
    std::string TypeString;
4093
41
    RewriteByRefString(TypeString, Name, (*I));
4094
41
    TypeString += " *";
4095
41
    Name = TypeString + Name;
4096
41
    S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4097
41
  }
4098
80
  // Next, emit a declaration for all "by copy" declarations.
4099
80
  for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
4100
116
       E = BlockByCopyDecls.end(); I != E; 
++I36
) {
4101
36
    S += "  ";
4102
36
    // Handle nested closure invocation. For example:
4103
36
    //
4104
36
    //   void (^myImportedClosure)(void);
4105
36
    //   myImportedClosure  = ^(void) { setGlobalInt(x + y); };
4106
36
    //
4107
36
    //   void (^anotherClosure)(void);
4108
36
    //   anotherClosure = ^(void) {
4109
36
    //     myImportedClosure(); // import and invoke the closure
4110
36
    //   };
4111
36
    //
4112
36
    if (isTopLevelBlockPointerType((*I)->getType())) {
4113
2
      RewriteBlockPointerTypeVariable(S, (*I));
4114
2
      S += " = (";
4115
2
      RewriteBlockPointerType(S, (*I)->getType());
4116
2
      S += ")";
4117
2
      S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4118
2
    }
4119
34
    else {
4120
34
      std::string Name = (*I)->getNameAsString();
4121
34
      QualType QT = (*I)->getType();
4122
34
      if (HasLocalVariableExternalStorage(*I))
4123
0
        QT = Context->getPointerType(QT);
4124
34
      QT.getAsStringInternal(Name, Context->getPrintingPolicy());
4125
34
      S += Name + " = __cself->" +
4126
34
                              (*I)->getNameAsString() + "; // bound by copy\n";
4127
34
    }
4128
36
  }
4129
80
  std::string RewrittenStr = RewrittenBlockExprs[CE];
4130
80
  const char *cstr = RewrittenStr.c_str();
4131
356
  while (*cstr++ != '{') 
;276
4132
80
  S += cstr;
4133
80
  S += "\n";
4134
80
  return S;
4135
80
}
4136
4137
std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4138
                                                   StringRef funcName,
4139
29
                                                   std::string Tag) {
4140
29
  std::string StructRef = "struct " + Tag;
4141
29
  std::string S = "static void __";
4142
29
4143
29
  S += funcName;
4144
29
  S += "_block_copy_" + utostr(i);
4145
29
  S += "(" + StructRef;
4146
29
  S += "*dst, " + StructRef;
4147
29
  S += "*src) {";
4148
44
  for (ValueDecl *VD : ImportedBlockDecls) {
4149
44
    S += "_Block_object_assign((void*)&dst->";
4150
44
    S += VD->getNameAsString();
4151
44
    S += ", (void*)src->";
4152
44
    S += VD->getNameAsString();
4153
44
    if (BlockByRefDeclsPtrSet.count(VD))
4154
28
      S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4155
16
    else if (VD->getType()->isBlockPointerType())
4156
2
      S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4157
14
    else
4158
14
      S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4159
44
  }
4160
29
  S += "}\n";
4161
29
4162
29
  S += "\nstatic void __";
4163
29
  S += funcName;
4164
29
  S += "_block_dispose_" + utostr(i);
4165
29
  S += "(" + StructRef;
4166
29
  S += "*src) {";
4167
44
  for (ValueDecl *VD : ImportedBlockDecls) {
4168
44
    S += "_Block_object_dispose((void*)src->";
4169
44
    S += VD->getNameAsString();
4170
44
    if (BlockByRefDeclsPtrSet.count(VD))
4171
28
      S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4172
16
    else if (VD->getType()->isBlockPointerType())
4173
2
      S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4174
14
    else
4175
14
      S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4176
44
  }
4177
29
  S += "}\n";
4178
29
  return S;
4179
29
}
4180
4181
std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4182
80
                                             std::string Desc) {
4183
80
  std::string S = "\nstruct " + Tag;
4184
80
  std::string Constructor = "  " + Tag;
4185
80
4186
80
  S += " {\n  struct __block_impl impl;\n";
4187
80
  S += "  struct " + Desc;
4188
80
  S += "* Desc;\n";
4189
80
4190
80
  Constructor += "(void *fp, "; // Invoke function pointer.
4191
80
  Constructor += "struct " + Desc; // Descriptor pointer.
4192
80
  Constructor += " *desc";
4193
80
4194
80
  if (BlockDeclRefs.size()) {
4195
43
    // Output all "by copy" declarations.
4196
43
    for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
4197
79
         E = BlockByCopyDecls.end(); I != E; 
++I36
) {
4198
36
      S += "  ";
4199
36
      std::string FieldName = (*I)->getNameAsString();
4200
36
      std::string ArgName = "_" + FieldName;
4201
36
      // Handle nested closure invocation. For example:
4202
36
      //
4203
36
      //   void (^myImportedBlock)(void);
4204
36
      //   myImportedBlock  = ^(void) { setGlobalInt(x + y); };
4205
36
      //
4206
36
      //   void (^anotherBlock)(void);
4207
36
      //   anotherBlock = ^(void) {
4208
36
      //     myImportedBlock(); // import and invoke the closure
4209
36
      //   };
4210
36
      //
4211
36
      if (isTopLevelBlockPointerType((*I)->getType())) {
4212
2
        S += "struct __block_impl *";
4213
2
        Constructor += ", void *" + ArgName;
4214
34
      } else {
4215
34
        QualType QT = (*I)->getType();
4216
34
        if (HasLocalVariableExternalStorage(*I))
4217
0
          QT = Context->getPointerType(QT);
4218
34
        QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4219
34
        QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4220
34
        Constructor += ", " + ArgName;
4221
34
      }
4222
36
      S += FieldName + ";\n";
4223
36
    }
4224
43
    // Output all "by ref" declarations.
4225
43
    for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
4226
84
         E = BlockByRefDecls.end(); I != E; 
++I41
) {
4227
41
      S += "  ";
4228
41
      std::string FieldName = (*I)->getNameAsString();
4229
41
      std::string ArgName = "_" + FieldName;
4230
41
      {
4231
41
        std::string TypeString;
4232
41
        RewriteByRefString(TypeString, FieldName, (*I));
4233
41
        TypeString += " *";
4234
41
        FieldName = TypeString + FieldName;
4235
41
        ArgName = TypeString + ArgName;
4236
41
        Constructor += ", " + ArgName;
4237
41
      }
4238
41
      S += FieldName + "; // by ref\n";
4239
41
    }
4240
43
    // Finish writing the constructor.
4241
43
    Constructor += ", int flags=0)";
4242
43
    // Initialize all "by copy" arguments.
4243
43
    bool firsTime = true;
4244
43
    for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
4245
79
         E = BlockByCopyDecls.end(); I != E; 
++I36
) {
4246
36
      std::string Name = (*I)->getNameAsString();
4247
36
        if (firsTime) {
4248
24
          Constructor += " : ";
4249
24
          firsTime = false;
4250
24
        }
4251
12
        else
4252
12
          Constructor += ", ";
4253
36
        if (isTopLevelBlockPointerType((*I)->getType()))
4254
2
          Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4255
34
        else
4256
34
          Constructor += Name + "(_" + Name + ")";
4257
36
    }
4258
43
    // Initialize all "by ref" arguments.
4259
43
    for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
4260
84
         E = BlockByRefDecls.end(); I != E; 
++I41
) {
4261
41
      std::string Name = (*I)->getNameAsString();
4262
41
      if (firsTime) {
4263
19
        Constructor += " : ";
4264
19
        firsTime = false;
4265
19
      }
4266
22
      else
4267
22
        Constructor += ", ";
4268
41
      Constructor += Name + "(_" + Name + "->__forwarding)";
4269
41
    }
4270
43
4271
43
    Constructor += " {\n";
4272
43
    if (GlobalVarDecl)
4273
0
      Constructor += "    impl.isa = &_NSConcreteGlobalBlock;\n";
4274
43
    else
4275
43
      Constructor += "    impl.isa = &_NSConcreteStackBlock;\n";
4276
43
    Constructor += "    impl.Flags = flags;\n    impl.FuncPtr = fp;\n";
4277
43
4278
43
    Constructor += "    Desc = desc;\n";
4279
43
  } else {
4280
37
    // Finish writing the constructor.
4281
37
    Constructor += ", int flags=0) {\n";
4282
37
    if (GlobalVarDecl)
4283
6
      Constructor += "    impl.isa = &_NSConcreteGlobalBlock;\n";
4284
31
    else
4285
31
      Constructor += "    impl.isa = &_NSConcreteStackBlock;\n";
4286
37
    Constructor += "    impl.Flags = flags;\n    impl.FuncPtr = fp;\n";
4287
37
    Constructor += "    Desc = desc;\n";
4288
37
  }
4289
80
  Constructor += "  ";
4290
80
  Constructor += "}\n";
4291
80
  S += Constructor;
4292
80
  S += "};\n";
4293
80
  return S;
4294
80
}
4295
4296
std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4297
                                                   std::string ImplTag, int i,
4298
                                                   StringRef FunName,
4299
80
                                                   unsigned hasCopy) {
4300
80
  std::string S = "\nstatic struct " + DescTag;
4301
80
4302
80
  S += " {\n  size_t reserved;\n";
4303
80
  S += "  size_t Block_size;\n";
4304
80
  if (hasCopy) {
4305
29
    S += "  void (*copy)(struct ";
4306
29
    S += ImplTag; S += "*, struct ";
4307
29
    S += ImplTag; S += "*);\n";
4308
29
4309
29
    S += "  void (*dispose)(struct ";
4310
29
    S += ImplTag; S += "*);\n";
4311
29
  }
4312
80
  S += "} ";
4313
80
4314
80
  S += DescTag + "_DATA = { 0, sizeof(struct ";
4315
80
  S += ImplTag + ")";
4316
80
  if (hasCopy) {
4317
29
    S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4318
29
    S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4319
29
  }
4320
80
  S += "};\n";
4321
80
  return S;
4322
80
}
4323
4324
void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4325
171
                                          StringRef FunName) {
4326
171
  bool RewriteSC = (GlobalVarDecl &&
4327
171
                    
!Blocks.empty()9
&&
4328
171
                    
GlobalVarDecl->getStorageClass() == SC_Static6
&&
4329
171
                    
GlobalVarDecl->getType().getCVRQualifiers()4
);
4330
171
  if (RewriteSC) {
4331
4
    std::string SC(" void __");
4332
4
    SC += GlobalVarDecl->getNameAsString();
4333
4
    SC += "() {}";
4334
4
    InsertText(FunLocStart, SC);
4335
4
  }
4336
171
4337
171
  // Insert closures that were part of the function.
4338
251
  for (unsigned i = 0, count=0; i < Blocks.size(); 
i++80
) {
4339
80
    CollectBlockDeclRefInfo(Blocks[i]);
4340
80
    // Need to copy-in the inner copied-in variables not actually used in this
4341
80
    // block.
4342
105
    for (int j = 0; j < InnerDeclRefsCount[i]; 
j++25
) {
4343
25
      DeclRefExpr *Exp = InnerDeclRefs[count++];
4344
25
      ValueDecl *VD = Exp->getDecl();
4345
25
      BlockDeclRefs.push_back(Exp);
4346
25
      if (!VD->hasAttr<BlocksAttr>()) {
4347
12
        if (!BlockByCopyDeclsPtrSet.count(VD)) {
4348
12
          BlockByCopyDeclsPtrSet.insert(VD);
4349
12
          BlockByCopyDecls.push_back(VD);
4350
12
        }
4351
12
        continue;
4352
12
      }
4353
13
4354
13
      if (!BlockByRefDeclsPtrSet.count(VD)) {
4355
13
        BlockByRefDeclsPtrSet.insert(VD);
4356
13
        BlockByRefDecls.push_back(VD);
4357
13
      }
4358
13
4359
13
      // imported objects in the inner blocks not used in the outer
4360
13
      // blocks must be copied/disposed in the outer block as well.
4361
13
      if (VD->getType()->isObjCObjectPointerType() ||
4362
13
          VD->getType()->isBlockPointerType())
4363
0
        ImportedBlockDecls.insert(VD);
4364
13
    }
4365
80
4366
80
    std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4367
80
    std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4368
80
4369
80
    std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4370
80
4371
80
    InsertText(FunLocStart, CI);
4372
80
4373
80
    std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4374
80
4375
80
    InsertText(FunLocStart, CF);
4376
80
4377
80
    if (ImportedBlockDecls.size()) {
4378
29
      std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4379
29
      InsertText(FunLocStart, HF);
4380
29
    }
4381
80
    std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4382
80
                                               ImportedBlockDecls.size() > 0);
4383
80
    InsertText(FunLocStart, BD);
4384
80
4385
80
    BlockDeclRefs.clear();
4386
80
    BlockByRefDecls.clear();
4387
80
    BlockByRefDeclsPtrSet.clear();
4388
80
    BlockByCopyDecls.clear();
4389
80
    BlockByCopyDeclsPtrSet.clear();
4390
80
    ImportedBlockDecls.clear();
4391
80
  }
4392
171
  if (RewriteSC) {
4393
4
    // Must insert any 'const/volatile/static here. Since it has been
4394
4
    // removed as result of rewriting of block literals.
4395
4
    std::string SC;
4396
4
    if (GlobalVarDecl->getStorageClass() == SC_Static)
4397
4
      SC = "static ";
4398
4
    if (GlobalVarDecl->getType().isConstQualified())
4399
4
      SC += "const ";
4400
4
    if (GlobalVarDecl->getType().isVolatileQualified())
4401
0
      SC += "volatile ";
4402
4
    if (GlobalVarDecl->getType().isRestrictQualified())
4403
0
      SC += "restrict ";
4404
4
    InsertText(FunLocStart, SC);
4405
4
  }
4406
171
  if (GlobalConstructionExp) {
4407
6
    // extra fancy dance for global literal expression.
4408
6
4409
6
    // Always the latest block expression on the block stack.
4410
6
    std::string Tag = "__";
4411
6
    Tag += FunName;
4412
6
    Tag += "_block_impl_";
4413
6
    Tag += utostr(Blocks.size()-1);
4414
6
    std::string globalBuf = "static ";
4415
6
    globalBuf += Tag; globalBuf += " ";
4416
6
    std::string SStr;
4417
6
4418
6
    llvm::raw_string_ostream constructorExprBuf(SStr);
4419
6
    GlobalConstructionExp->printPretty(constructorExprBuf, nullptr,
4420
6
                                       PrintingPolicy(LangOpts));
4421
6
    globalBuf += constructorExprBuf.str();
4422
6
    globalBuf += ";\n";
4423
6
    InsertText(FunLocStart, globalBuf);
4424
6
    GlobalConstructionExp = nullptr;
4425
6
  }
4426
171
4427
171
  Blocks.clear();
4428
171
  InnerDeclRefsCount.clear();
4429
171
  InnerDeclRefs.clear();
4430
171
  RewrittenBlockExprs.clear();
4431
171
}
4432
4433
99
void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4434
99
  SourceLocation FunLocStart =
4435
99
    (!Blocks.empty()) ? 
getFunctionSourceLocation(*this, FD)31
4436
99
                      : 
FD->getTypeSpecStartLoc()68
;
4437
99
  StringRef FuncName = FD->getName();
4438
99
4439
99
  SynthesizeBlockLiterals(FunLocStart, FuncName);
4440
99
}
4441
4442
static void BuildUniqueMethodName(std::string &Name,
4443
84
                                  ObjCMethodDecl *MD) {
4444
84
  ObjCInterfaceDecl *IFace = MD->getClassInterface();
4445
84
  Name = std::string(IFace->getName());
4446
84
  Name += "__" + MD->getSelector().getAsString();
4447
84
  // Convert colons to underscores.
4448
84
  std::string::size_type loc = 0;
4449
114
  while ((loc = Name.find(':', loc)) != std::string::npos)
4450
30
    Name.replace(loc, 1, "_");
4451
84
}
4452
4453
63
void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4454
63
  // fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4455
63
  // SourceLocation FunLocStart = MD->getBeginLoc();
4456
63
  SourceLocation FunLocStart = MD->getBeginLoc();
4457
63
  std::string FuncName;
4458
63
  BuildUniqueMethodName(FuncName, MD);
4459
63
  SynthesizeBlockLiterals(FunLocStart, FuncName);
4460
63
}
4461
4462
1.91k
void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4463
1.91k
  for (Stmt *SubStmt : S->children())
4464
1.75k
    if (SubStmt) {
4465
1.75k
      if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt))
4466
0
        GetBlockDeclRefExprs(CBE->getBody());
4467
1.75k
      else
4468
1.75k
        GetBlockDeclRefExprs(SubStmt);
4469
1.75k
    }
4470
1.91k
  // Handle specific things.
4471
1.91k
  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4472
448
    if (DRE->refersToEnclosingVariableOrCapture() ||
4473
448
        
HasLocalVariableExternalStorage(DRE->getDecl())336
)
4474
112
      // FIXME: Handle enums.
4475
112
      BlockDeclRefs.push_back(DRE);
4476
1.91k
}
4477
4478
void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4479
                SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
4480
720
                llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts) {
4481
720
  for (Stmt *SubStmt : S->children())
4482
640
    if (SubStmt) {
4483
640
      if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt)) {
4484
21
        InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4485
21
        GetInnerBlockDeclRefExprs(CBE->getBody(),
4486
21
                                  InnerBlockDeclRefs,
4487
21
                                  InnerContexts);
4488
21
      }
4489
619
      else
4490
619
        GetInnerBlockDeclRefExprs(SubStmt, InnerBlockDeclRefs, InnerContexts);
4491
640
    }
4492
720
  // Handle specific things.
4493
720
  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4494
154
    if (DRE->refersToEnclosingVariableOrCapture() ||
4495
154
        
HasLocalVariableExternalStorage(DRE->getDecl())61
) {
4496
93
      if (!InnerContexts.count(DRE->getDecl()->getDeclContext()))
4497
88
        InnerBlockDeclRefs.push_back(DRE);
4498
93
      if (VarDecl *Var = cast<VarDecl>(DRE->getDecl()))
4499
93
        if (Var->isFunctionOrMethodVarDecl())
4500
70
          ImportedLocalExternalDecls.insert(Var);
4501
93
    }
4502
154
  }
4503
720
}
4504
4505
/// convertObjCTypeToCStyleType - This routine converts such objc types
4506
/// as qualified objects, and blocks to their closest c/c++ types that
4507
/// it can. It returns true if input type was modified.
4508
419
bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4509
419
  QualType oldT = T;
4510
419
  convertBlockPointerToFunctionPointer(T);
4511
419
  if (T->isFunctionPointerType()) {
4512
14
    QualType PointeeTy;
4513
14
    if (const PointerType* PT = T->getAs<PointerType>()) {
4514
14
      PointeeTy = PT->getPointeeType();
4515
14
      if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4516
14
        T = convertFunctionTypeOfBlocks(FT);
4517
14
        T = Context->getPointerType(T);
4518
14
      }
4519
14
    }
4520
14
  }
4521
419
4522
419
  convertToUnqualifiedObjCType(T);
4523
419
  return T != oldT;
4524
419
}
4525
4526
/// convertFunctionTypeOfBlocks - This routine converts a function type
4527
/// whose result type may be a block pointer or whose argument type(s)
4528
/// might be block pointers to an equivalent function type replacing
4529
/// all block pointers to function pointers.
4530
94
QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4531
94
  const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4532
94
  // FTP will be null for closures that don't take arguments.
4533
94
  // Generate a funky cast.
4534
94
  SmallVector<QualType, 8> ArgTypes;
4535
94
  QualType Res = FT->getReturnType();
4536
94
  bool modified = convertObjCTypeToCStyleType(Res);
4537
94
4538
94
  if (FTP) {
4539
94
    for (auto &I : FTP->param_types()) {
4540
31
      QualType t = I;
4541
31
      // Make sure we convert "t (^)(...)" to "t (*)(...)".
4542
31
      if (convertObjCTypeToCStyleType(t))
4543
16
        modified = true;
4544
31
      ArgTypes.push_back(t);
4545
31
    }
4546
94
  }
4547
94
  QualType FuncType;
4548
94
  if (modified)
4549
12
    FuncType = getSimpleFunctionType(Res, ArgTypes);
4550
82
  else FuncType = QualType(FT, 0);
4551
94
  return FuncType;
4552
94
}
4553
4554
14
Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4555
14
  // Navigate to relevant type information.
4556
14
  const BlockPointerType *CPT = nullptr;
4557
14
4558
14
  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4559
0
    CPT = DRE->getType()->getAs<BlockPointerType>();
4560
14
  } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4561
0
    CPT = MExpr->getType()->getAs<BlockPointerType>();
4562
0
  }
4563
14
  else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4564
0
    return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4565
0
  }
4566
14
  else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4567
14
    CPT = IEXPR->getType()->getAs<BlockPointerType>();
4568
0
  else if (const ConditionalOperator *CEXPR =
4569
0
            dyn_cast<ConditionalOperator>(BlockExp)) {
4570
0
    Expr *LHSExp = CEXPR->getLHS();
4571
0
    Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4572
0
    Expr *RHSExp = CEXPR->getRHS();
4573
0
    Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4574
0
    Expr *CONDExp = CEXPR->getCond();
4575
0
    ConditionalOperator *CondExpr =
4576
0
      new (Context) ConditionalOperator(CONDExp,
4577
0
                                      SourceLocation(), cast<Expr>(LHSStmt),
4578
0
                                      SourceLocation(), cast<Expr>(RHSStmt),
4579
0
                                      Exp->getType(), VK_RValue, OK_Ordinary);
4580
0
    return CondExpr;
4581
0
  } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4582
0
    CPT = IRE->getType()->getAs<BlockPointerType>();
4583
0
  } else if (const PseudoObjectExpr *POE
4584
0
               = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4585
0
    CPT = POE->getType()->castAs<BlockPointerType>();
4586
0
  } else {
4587
0
    assert(false && "RewriteBlockClass: Bad type");
4588
0
  }
4589
14
  assert(CPT && "RewriteBlockClass: Bad type");
4590
14
  const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4591
14
  assert(FT && "RewriteBlockClass: Bad type");
4592
14
  const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4593
14
  // FTP will be null for closures that don't take arguments.
4594
14
4595
14
  RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4596
14
                                      SourceLocation(), SourceLocation(),
4597
14
                                      &Context->Idents.get("__block_impl"));
4598
14
  QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4599
14
4600
14
  // Generate a funky cast.
4601
14
  SmallVector<QualType, 8> ArgTypes;
4602
14
4603
14
  // Push the block argument type.
4604
14
  ArgTypes.push_back(PtrBlock);
4605
14
  if (FTP) {
4606
14
    for (auto &I : FTP->param_types()) {
4607
8
      QualType t = I;
4608
8
      // Make sure we convert "t (^)(...)" to "t (*)(...)".
4609
8
      if (!convertBlockPointerToFunctionPointer(t))
4610
8
        convertToUnqualifiedObjCType(t);
4611
8
      ArgTypes.push_back(t);
4612
8
    }
4613
14
  }
4614
14
  // Now do the pointer to function cast.
4615
14
  QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
4616
14
4617
14
  PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4618
14
4619
14
  CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4620
14
                                               CK_BitCast,
4621
14
                                               const_cast<Expr*>(BlockExp));
4622
14
  // Don't forget the parens to enforce the proper binding.
4623
14
  ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4624
14
                                          BlkCast);
4625
14
  //PE->dump();
4626
14
4627
14
  FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
4628
14
                                    SourceLocation(),
4629
14
                                    &Context->Idents.get("FuncPtr"),
4630
14
                                    Context->VoidPtrTy, nullptr,
4631
14
                                    /*BitWidth=*/nullptr, /*Mutable=*/true,
4632
14
                                    ICIS_NoInit);
4633
14
  MemberExpr *ME = MemberExpr::CreateImplicit(
4634
14
      *Context, PE, true, FD, FD->getType(), VK_LValue, OK_Ordinary);
4635
14
4636
14
  CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4637
14
                                                CK_BitCast, ME);
4638
14
  PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4639
14
4640
14
  SmallVector<Expr*, 8> BlkExprs;
4641
14
  // Add the implicit argument.
4642
14
  BlkExprs.push_back(BlkCast);
4643
14
  // Add the user arguments.
4644
14
  for (CallExpr::arg_iterator I = Exp->arg_begin(),
4645
22
       E = Exp->arg_end(); I != E; 
++I8
) {
4646
8
    BlkExprs.push_back(*I);
4647
8
  }
4648
14
  CallExpr *CE = CallExpr::Create(*Context, PE, BlkExprs, Exp->getType(),
4649
14
                                  VK_RValue, SourceLocation());
4650
14
  return CE;
4651
14
}
4652
4653
// We need to return the rewritten expression to handle cases where the
4654
// DeclRefExpr is embedded in another expression being rewritten.
4655
// For example:
4656
//
4657
// int main() {
4658
//    __block Foo *f;
4659
//    __block int i;
4660
//
4661
//    void (^myblock)() = ^() {
4662
//        [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
4663
//        i = 77;
4664
//    };
4665
//}
4666
36
Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
4667
36
  // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4668
36
  // for each DeclRefExp where BYREFVAR is name of the variable.
4669
36
  ValueDecl *VD = DeclRefExp->getDecl();
4670
36
  bool isArrow = DeclRefExp->refersToEnclosingVariableOrCapture() ||
4671
36
                 
HasLocalVariableExternalStorage(DeclRefExp->getDecl())8
;
4672
36
4673
36
  FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
4674
36
                                    SourceLocation(),
4675
36
                                    &Context->Idents.get("__forwarding"),
4676
36
                                    Context->VoidPtrTy, nullptr,
4677
36
                                    /*BitWidth=*/nullptr, /*Mutable=*/true,
4678
36
                                    ICIS_NoInit);
4679
36
  MemberExpr *ME = MemberExpr::CreateImplicit(
4680
36
      *Context, DeclRefExp, isArrow, FD, FD->getType(), VK_LValue, OK_Ordinary);
4681
36
4682
36
  StringRef Name = VD->getName();
4683
36
  FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(),
4684
36
                         &Context->Idents.get(Name),
4685
36
                         Context->VoidPtrTy, nullptr,
4686
36
                         /*BitWidth=*/nullptr, /*Mutable=*/true,
4687
36
                         ICIS_NoInit);
4688
36
  ME = MemberExpr::CreateImplicit(*Context, ME, true, FD, DeclRefExp->getType(),
4689
36
                                  VK_LValue, OK_Ordinary);
4690
36
4691
36
  // Need parens to enforce precedence.
4692
36
  ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4693
36
                                          DeclRefExp->getExprLoc(),
4694
36
                                          ME);
4695
36
  ReplaceStmt(DeclRefExp, PE);
4696
36
  return PE;
4697
36
}
4698
4699
// Rewrites the imported local variable V with external storage
4700
// (static, extern, etc.) as *V
4701
//
4702
0
Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4703
0
  ValueDecl *VD = DRE->getDecl();
4704
0
  if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4705
0
    if (!ImportedLocalExternalDecls.count(Var))
4706
0
      return DRE;
4707
0
  Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4708
0
                                          VK_LValue, OK_Ordinary,
4709
0
                                          DRE->getLocation(), false);
4710
0
  // Need parens to enforce precedence.
4711
0
  ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4712
0
                                          Exp);
4713
0
  ReplaceStmt(DRE, PE);
4714
0
  return PE;
4715
0
}
4716
4717
30
void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4718
30
  SourceLocation LocStart = CE->getLParenLoc();
4719
30
  SourceLocation LocEnd = CE->getRParenLoc();
4720
30
4721
30
  // Need to avoid trying to rewrite synthesized casts.
4722
30
  if (LocStart.isInvalid())
4723
0
    return;
4724
30
  // Need to avoid trying to rewrite casts contained in macros.
4725
30
  if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4726
0
    return;
4727
30
4728
30
  const char *startBuf = SM->getCharacterData(LocStart);
4729
30
  const char *endBuf = SM->getCharacterData(LocEnd);
4730
30
  QualType QT = CE->getType();
4731
30
  const Type* TypePtr = QT->getAs<Type>();
4732
30
  if (isa<TypeOfExprType>(TypePtr)) {
4733
4
    const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4734
4
    QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4735
4
    std::string TypeAsString = "(";
4736
4
    RewriteBlockPointerType(TypeAsString, QT);
4737
4
    TypeAsString += ")";
4738
4
    ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4739
4
    return;
4740
4
  }
4741
26
  // advance the location to startArgList.
4742
26
  const char *argPtr = startBuf;
4743
26
4744
221
  while (*argPtr++ && (argPtr < endBuf)) {
4745
195
    switch (*argPtr) {
4746
0
    case '^':
4747
0
      // Replace the '^' with '*'.
4748
0
      LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4749
0
      ReplaceText(LocStart, 1, "*");
4750
0
      break;
4751
195
    }
4752
195
  }
4753
26
}
4754
4755
604
void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4756
604
  CastKind CastKind = IC->getCastKind();
4757
604
  if (CastKind != CK_BlockPointerToObjCPointerCast &&
4758
604
      
CastKind != CK_AnyPointerToBlockPointerCast599
)
4759
595
    return;
4760
9
4761
9
  QualType QT = IC->getType();
4762
9
  (void)convertBlockPointerToFunctionPointer(QT);
4763
9
  std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4764
9
  std::string Str = "(";
4765
9
  Str += TypeString;
4766
9
  Str += ")";
4767
9
  InsertText(IC->getSubExpr()->getBeginLoc(), Str);
4768
9
}
4769
4770
26
void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4771
26
  SourceLocation DeclLoc = FD->getLocation();
4772
26
  unsigned parenCount = 0;
4773
26
4774
26
  // We have 1 or more arguments that have closure pointers.
4775
26
  const char *startBuf = SM->getCharacterData(DeclLoc);
4776
26
  const char *startArgList = strchr(startBuf, '(');
4777
26
4778
26
  assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4779
26
4780
26
  parenCount++;
4781
26
  // advance the location to startArgList.
4782
26
  DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4783
26
  assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4784
26
4785
26
  const char *argPtr = startArgList;
4786
26
4787
488
  while (*argPtr++ && parenCount) {
4788
462
    switch (*argPtr) {
4789
26
    case '^':
4790
26
      // Replace the '^' with '*'.
4791
26
      DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4792
26
      ReplaceText(DeclLoc, 1, "*");
4793
26
      break;
4794
52
    case '(':
4795
52
      parenCount++;
4796
52
      break;
4797
78
    case ')':
4798
78
      parenCount--;
4799
78
      break;
4800
462
    }
4801
462
  }
4802
26
}
4803
4804
50
bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4805
50
  const FunctionProtoType *FTP;
4806
50
  const PointerType *PT = QT->getAs<PointerType>();
4807
50
  if (PT) {
4808
2
    FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4809
48
  } else {
4810
48
    const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4811
48
    assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4812
48
    FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4813
48
  }
4814
50
  if (FTP) {
4815
50
    for (const auto &I : FTP->param_types())
4816
29
      if (isTopLevelBlockPointerType(I))
4817
3
        return true;
4818
50
  }
4819
50
  
return false47
;
4820
50
}
4821
4822
45
bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4823
45
  const FunctionProtoType *FTP;
4824
45
  const PointerType *PT = QT->getAs<PointerType>();
4825
45
  if (PT) {
4826
0
    FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4827
45
  } else {
4828
45
    const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4829
45
    assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4830
45
    FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4831
45
  }
4832
45
  if (FTP) {
4833
45
    for (const auto &I : FTP->param_types()) {
4834
15
      if (I->isObjCQualifiedIdType())
4835
5
        return true;
4836
10
      if (I->isObjCObjectPointerType() &&
4837
10
          
I->getPointeeType()->isObjCQualifiedInterfaceType()6
)
4838
1
        return true;
4839
10
    }
4840
45
4841
45
  }
4842
45
  
return false39
;
4843
45
}
4844
4845
void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4846
9
                                     const char *&RParen) {
4847
9
  const char *argPtr = strchr(Name, '(');
4848
9
  assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4849
9
4850
9
  LParen = argPtr; // output the start.
4851
9
  argPtr++; // skip past the left paren.
4852
9
  unsigned parenCount = 1;
4853
9
4854
884
  while (*argPtr && parenCount) {
4855
875
    switch (*argPtr) {
4856
10
    case '(': parenCount++; break;
4857
19
    case ')': parenCount--; break;
4858
846
    default: break;
4859
875
    }
4860
875
    if (parenCount) 
argPtr++866
;
4861
875
  }
4862
9
  assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4863
9
  RParen = argPtr; // output the end
4864
9
}
4865
4866
74
void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4867
74
  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4868
26
    RewriteBlockPointerFunctionArgs(FD);
4869
26
    return;
4870
26
  }
4871
48
  // Handle Variables and Typedefs.
4872
48
  SourceLocation DeclLoc = ND->getLocation();
4873
48
  QualType DeclT;
4874
48
  if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4875
28
    DeclT = VD->getType();
4876
20
  else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4877
19
    DeclT = TDD->getUnderlyingType();
4878
1
  else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4879
1
    DeclT = FD->getType();
4880
1
  else
4881
1
    
llvm_unreachable0
("RewriteBlockPointerDecl(): Decl type not yet handled");
4882
48
4883
48
  const char *startBuf = SM->getCharacterData(DeclLoc);
4884
48
  const char *endBuf = startBuf;
4885
48
  // scan backward (from the decl location) for the end of the previous decl.
4886
98
  while (*startBuf != '^' && 
*startBuf != ';'50
&&
startBuf != MainFileStart50
)
4887
50
    startBuf--;
4888
48
  SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4889
48
  std::string buf;
4890
48
  unsigned OrigLength=0;
4891
48
  // *startBuf != '^' if we are dealing with a pointer to function that
4892
48
  // may take block argument types (which will be handled below).
4893
48
  if (*startBuf == '^') {
4894
48
    // Replace the '^' with '*', computing a negative offset.
4895
48
    buf = '*';
4896
48
    startBuf++;
4897
48
    OrigLength++;
4898
48
  }
4899
432
  while (*startBuf != ')') {
4900
384
    buf += *startBuf;
4901
384
    startBuf++;
4902
384
    OrigLength++;
4903
384
  }
4904
48
  buf += ')';
4905
48
  OrigLength++;
4906
48
4907
48
  if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4908
48
      
PointerTypeTakesAnyObjCQualifiedType(DeclT)45
) {
4909
9
    // Replace the '^' with '*' for arguments.
4910
9
    // Replace id<P> with id/*<>*/
4911
9
    DeclLoc = ND->getLocation();
4912
9
    startBuf = SM->getCharacterData(DeclLoc);
4913
9
    const char *argListBegin, *argListEnd;
4914
9
    GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4915
453
    while (argListBegin < argListEnd) {
4916
444
      if (*argListBegin == '^')
4917
5
        buf += '*';
4918
439
      else if (*argListBegin ==  '<') {
4919
17
        buf += "/*";
4920
17
        buf += *argListBegin++;
4921
17
        OrigLength++;
4922
431
        while (*argListBegin != '>') {
4923
414
          buf += *argListBegin++;
4924
414
          OrigLength++;
4925
414
        }
4926
17
        buf += *argListBegin;
4927
17
        buf += "*/";
4928
17
      }
4929
422
      else
4930
422
        buf += *argListBegin;
4931
444
      argListBegin++;
4932
444
      OrigLength++;
4933
444
    }
4934
9
    buf += ')';
4935
9
    OrigLength++;
4936
9
  }
4937
48
  ReplaceText(Start, OrigLength, buf);
4938
48
}
4939
4940
/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4941
/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4942
///                    struct Block_byref_id_object *src) {
4943
///  _Block_object_assign (&_dest->object, _src->object,
4944
///                        BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4945
///                        [|BLOCK_FIELD_IS_WEAK]) // object
4946
///  _Block_object_assign(&_dest->object, _src->object,
4947
///                       BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4948
///                       [|BLOCK_FIELD_IS_WEAK]) // block
4949
/// }
4950
/// And:
4951
/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4952
///  _Block_object_dispose(_src->object,
4953
///                        BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4954
///                        [|BLOCK_FIELD_IS_WEAK]) // object
4955
///  _Block_object_dispose(_src->object,
4956
///                         BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4957
///                         [|BLOCK_FIELD_IS_WEAK]) // block
4958
/// }
4959
4960
std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4961
6
                                                          int flag) {
4962
6
  std::string S;
4963
6
  if (CopyDestroyCache.count(flag))
4964
2
    return S;
4965
4
  CopyDestroyCache.insert(flag);
4966
4
  S = "static void __Block_byref_id_object_copy_";
4967
4
  S += utostr(flag);
4968
4
  S += "(void *dst, void *src) {\n";
4969
4
4970
4
  // offset into the object pointer is computed as:
4971
4
  // void * + void* + int + int + void* + void *
4972
4
  unsigned IntSize =
4973
4
  static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4974
4
  unsigned VoidPtrSize =
4975
4
  static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4976
4
4977
4
  unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4978
4
  S += " _Block_object_assign((char*)dst + ";
4979
4
  S += utostr(offset);
4980
4
  S += ", *(void * *) ((char*)src + ";
4981
4
  S += utostr(offset);
4982
4
  S += "), ";
4983
4
  S += utostr(flag);
4984
4
  S += ");\n}\n";
4985
4
4986
4
  S += "static void __Block_byref_id_object_dispose_";
4987
4
  S += utostr(flag);
4988
4
  S += "(void *src) {\n";
4989
4
  S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4990
4
  S += utostr(offset);
4991
4
  S += "), ";
4992
4
  S += utostr(flag);
4993
4
  S += ");\n}\n";
4994
4
  return S;
4995
4
}
4996
4997
/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4998
/// the declaration into:
4999
/// struct __Block_byref_ND {
5000
/// void *__isa;                  // NULL for everything except __weak pointers
5001
/// struct __Block_byref_ND *__forwarding;
5002
/// int32_t __flags;
5003
/// int32_t __size;
5004
/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5005
/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
5006
/// typex ND;
5007
/// };
5008
///
5009
/// It then replaces declaration of ND variable with:
5010
/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5011
///                               __size=sizeof(struct __Block_byref_ND),
5012
///                               ND=initializer-if-any};
5013
///
5014
///
5015
void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
5016
42
                                        bool lastDecl) {
5017
42
  int flag = 0;
5018
42
  int isa = 0;
5019
42
  SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
5020
42
  if (DeclLoc.isInvalid())
5021
0
    // If type location is missing, it is because of missing type (a warning).
5022
0
    // Use variable's location which is good for this case.
5023
0
    DeclLoc = ND->getLocation();
5024
42
  const char *startBuf = SM->getCharacterData(DeclLoc);
5025
42
  SourceLocation X = ND->getEndLoc();
5026
42
  X = SM->getExpansionLoc(X);
5027
42
  const char *endBuf = SM->getCharacterData(X);
5028
42
  std::string Name(ND->getNameAsString());
5029
42
  std::string ByrefType;
5030
42
  RewriteByRefString(ByrefType, Name, ND, true);
5031
42
  ByrefType += " {\n";
5032
42
  ByrefType += "  void *__isa;\n";
5033
42
  RewriteByRefString(ByrefType, Name, ND);
5034
42
  ByrefType += " *__forwarding;\n";
5035
42
  ByrefType += " int __flags;\n";
5036
42
  ByrefType += " int __size;\n";
5037
42
  // Add void *__Block_byref_id_object_copy;
5038
42
  // void *__Block_byref_id_object_dispose; if needed.
5039
42
  QualType Ty = ND->getType();
5040
42
  bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
5041
42
  if (HasCopyAndDispose) {
5042
6
    ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5043
6
    ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5044
6
  }
5045
42
5046
42
  QualType T = Ty;
5047
42
  (void)convertBlockPointerToFunctionPointer(T);
5048
42
  T.getAsStringInternal(Name, Context->getPrintingPolicy());
5049
42
5050
42
  ByrefType += " " + Name + ";\n";
5051
42
  ByrefType += "};\n";
5052
42
  // Insert this type in global scope. It is needed by helper function.
5053
42
  SourceLocation FunLocStart;
5054
42
  if (CurFunctionDef)
5055
33
     FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
5056
9
  else {
5057
9
    assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5058
9
    FunLocStart = CurMethodDef->getBeginLoc();
5059
9
  }
5060
42
  InsertText(FunLocStart, ByrefType);
5061
42
5062
42
  if (Ty.isObjCGCWeak()) {
5063
0
    flag |= BLOCK_FIELD_IS_WEAK;
5064
0
    isa = 1;
5065
0
  }
5066
42
  if (HasCopyAndDispose) {