Coverage Report

Created: 2017-10-03 07:32

/Users/buildslave/jenkins/sharedspace/clang-stage2-coverage-R@2/llvm/tools/clang/lib/Frontend/Rewrite/RewriteObjC.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
2
//
3
//                     The LLVM Compiler Infrastructure
4
//
5
// This file is distributed under the University of Illinois Open Source
6
// License. See LICENSE.TXT for details.
7
//
8
//===----------------------------------------------------------------------===//
9
//
10
// Hacks and fun related to the code rewriter.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "clang/Rewrite/Frontend/ASTConsumers.h"
15
#include "clang/AST/AST.h"
16
#include "clang/AST/ASTConsumer.h"
17
#include "clang/AST/Attr.h"
18
#include "clang/AST/ParentMap.h"
19
#include "clang/Basic/CharInfo.h"
20
#include "clang/Basic/Diagnostic.h"
21
#include "clang/Basic/IdentifierTable.h"
22
#include "clang/Basic/SourceManager.h"
23
#include "clang/Config/config.h"
24
#include "clang/Lex/Lexer.h"
25
#include "clang/Rewrite/Core/Rewriter.h"
26
#include "llvm/ADT/DenseSet.h"
27
#include "llvm/ADT/SmallPtrSet.h"
28
#include "llvm/ADT/StringExtras.h"
29
#include "llvm/Support/MemoryBuffer.h"
30
#include "llvm/Support/raw_ostream.h"
31
#include <memory>
32
33
#ifdef CLANG_ENABLE_OBJC_REWRITER
34
35
using namespace clang;
36
using llvm::utostr;
37
38
namespace {
39
  class RewriteObjC : public ASTConsumer {
40
  protected:
41
    enum {
42
      BLOCK_FIELD_IS_OBJECT   =  3,  /* id, NSObject, __attribute__((NSObject)),
43
                                        block, ... */
44
      BLOCK_FIELD_IS_BLOCK    =  7,  /* a block variable */
45
      BLOCK_FIELD_IS_BYREF    =  8,  /* the on stack structure holding the 
46
                                        __block variable */
47
      BLOCK_FIELD_IS_WEAK     = 16,  /* declared __weak, only used in byref copy
48
                                        helpers */
49
      BLOCK_BYREF_CALLER      = 128, /* called from __block (byref) copy/dispose
50
                                        support routines */
51
      BLOCK_BYREF_CURRENT_MAX = 256
52
    };
53
    
54
    enum {
55
      BLOCK_NEEDS_FREE =        (1 << 24),
56
      BLOCK_HAS_COPY_DISPOSE =  (1 << 25),
57
      BLOCK_HAS_CXX_OBJ =       (1 << 26),
58
      BLOCK_IS_GC =             (1 << 27),
59
      BLOCK_IS_GLOBAL =         (1 << 28),
60
      BLOCK_HAS_DESCRIPTOR =    (1 << 29)
61
    };
62
    static const int OBJC_ABI_VERSION = 7;
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
    unsigned RewriteFailedDiag;
81
    // ObjC string constant support.
82
    unsigned NumObjCStringLiterals;
83
    VarDecl *ConstantStringClassReference;
84
    RecordDecl *NSStringRecord;
85
86
    // ObjC foreach break/continue generation support.
87
    int BcLabelCount;
88
    
89
    unsigned TryFinallyContainsReturnDiag;
90
    // Needed for super.
91
    ObjCMethodDecl *CurMethodDef;
92
    RecordDecl *SuperStructDecl;
93
    RecordDecl *ConstantStringDecl;
94
    
95
    FunctionDecl *MsgSendFunctionDecl;
96
    FunctionDecl *MsgSendSuperFunctionDecl;
97
    FunctionDecl *MsgSendStretFunctionDecl;
98
    FunctionDecl *MsgSendSuperStretFunctionDecl;
99
    FunctionDecl *MsgSendFpretFunctionDecl;
100
    FunctionDecl *GetClassFunctionDecl;
101
    FunctionDecl *GetMetaClassFunctionDecl;
102
    FunctionDecl *GetSuperClassFunctionDecl;
103
    FunctionDecl *SelGetUidFunctionDecl;
104
    FunctionDecl *CFStringFunctionDecl;
105
    FunctionDecl *SuperConstructorFunctionDecl;
106
    FunctionDecl *CurFunctionDef;
107
    FunctionDecl *CurFunctionDeclToDeclareForBlock;
108
109
    /* Misc. containers needed for meta-data rewrite. */
110
    SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
111
    SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
112
    llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
113
    llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
114
    llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
115
    llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
116
    SmallVector<Stmt *, 32> Stmts;
117
    SmallVector<int, 8> ObjCBcLabelNo;
118
    // Remember all the @protocol(<expr>) expressions.
119
    llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
120
    
121
    llvm::DenseSet<uint64_t> CopyDestroyCache;
122
123
    // Block expressions.
124
    SmallVector<BlockExpr *, 32> Blocks;
125
    SmallVector<int, 32> InnerDeclRefsCount;
126
    SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
127
    
128
    SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
129
130
    // Block related declarations.
131
    SmallVector<ValueDecl *, 8> BlockByCopyDecls;
132
    llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
133
    SmallVector<ValueDecl *, 8> BlockByRefDecls;
134
    llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
135
    llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
136
    llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
137
    llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
138
    
139
    llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
140
141
    // This maps an original source AST to it's rewritten form. This allows
142
    // us to avoid rewriting the same node twice (which is very uncommon).
143
    // This is needed to support some of the exotic property rewriting.
144
    llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
145
146
    // Needed for header files being rewritten
147
    bool IsHeader;
148
    bool SilenceRewriteMacroWarning;
149
    bool objc_impl_method;
150
    
151
    bool DisableReplaceStmt;
152
    class DisableReplaceStmtScope {
153
      RewriteObjC &R;
154
      bool SavedValue;
155
    
156
    public:
157
      DisableReplaceStmtScope(RewriteObjC &R)
158
79
        : R(R), SavedValue(R.DisableReplaceStmt) {
159
79
        R.DisableReplaceStmt = true;
160
79
      }
161
162
79
      ~DisableReplaceStmtScope() {
163
79
        R.DisableReplaceStmt = SavedValue;
164
79
      }
165
    };
166
167
    void InitializeCommon(ASTContext &context);
168
169
  public:
170
    // Top Level Driver code.
171
439
    bool HandleTopLevelDecl(DeclGroupRef D) override {
172
949
      for (DeclGroupRef::iterator I = D.begin(), E = D.end(); 
I != E949
;
++I510
) {
173
533
        if (ObjCInterfaceDecl *
Class533
= dyn_cast<ObjCInterfaceDecl>(*I)) {
174
135
          if (
!Class->isThisDeclarationADefinition()135
) {
175
17
            RewriteForwardClassDecl(D);
176
17
            break;
177
17
          }
178
516
        }
179
516
180
516
        
if (ObjCProtocolDecl *516
Proto516
= dyn_cast<ObjCProtocolDecl>(*I)) {
181
27
          if (
!Proto->isThisDeclarationADefinition()27
) {
182
6
            RewriteForwardProtocolDecl(D);
183
6
            break;
184
6
          }
185
510
        }
186
510
187
510
        HandleTopLevelSingleDecl(*I);
188
510
      }
189
439
      return true;
190
439
    }
191
192
    void HandleTopLevelSingleDecl(Decl *D);
193
    void HandleDeclInMainFile(Decl *D);
194
    RewriteObjC(std::string inFile, std::unique_ptr<raw_ostream> OS,
195
                DiagnosticsEngine &D, const LangOptions &LOpts,
196
                bool silenceMacroWarn);
197
198
86
    ~RewriteObjC() override {}
199
200
    void HandleTranslationUnit(ASTContext &C) override;
201
202
227
    void ReplaceStmt(Stmt *Old, Stmt *New) {
203
227
      ReplaceStmtWithRange(Old, New, Old->getSourceRange());
204
227
    }
205
206
306
    void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
207
306
      assert(Old != nullptr && New != nullptr && "Expected non-null Stmt's");
208
306
209
306
      Stmt *ReplacingStmt = ReplacedNodes[Old];
210
306
      if (ReplacingStmt)
211
0
        return; // We can't rewrite the same node twice.
212
306
213
306
      
if (306
DisableReplaceStmt306
)
214
24
        return;
215
282
216
282
      // Measure the old text.
217
282
      int Size = Rewrite.getRangeSize(SrcRange);
218
282
      if (
Size == -1282
) {
219
0
        Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
220
0
                     << Old->getSourceRange();
221
0
        return;
222
0
      }
223
282
      // Get the new text.
224
282
      std::string SStr;
225
282
      llvm::raw_string_ostream S(SStr);
226
282
      New->printPretty(S, nullptr, PrintingPolicy(LangOpts));
227
282
      const std::string &Str = S.str();
228
282
229
282
      // If replacement succeeded or warning disabled return with no warning.
230
282
      if (
!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)282
) {
231
282
        ReplacedNodes[Old] = New;
232
282
        return;
233
282
      }
234
0
      
if (0
SilenceRewriteMacroWarning0
)
235
0
        return;
236
0
      Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
237
0
                   << Old->getSourceRange();
238
0
    }
239
240
    void InsertText(SourceLocation Loc, StringRef Str,
241
817
                    bool InsertAfter = true) {
242
817
      // If insertion succeeded or warning disabled return with no warning.
243
817
      if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
244
0
          SilenceRewriteMacroWarning)
245
817
        return;
246
0
247
0
      Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
248
0
    }
249
250
    void ReplaceText(SourceLocation Start, unsigned OrigLength,
251
599
                     StringRef Str) {
252
599
      // If removal succeeded or warning disabled return with no warning.
253
599
      if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
254
0
          SilenceRewriteMacroWarning)
255
599
        return;
256
0
257
0
      Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
258
0
    }
259
260
    // Syntactic Rewriting.
261
    void RewriteRecordBody(RecordDecl *RD);
262
    void RewriteInclude();
263
    void RewriteForwardClassDecl(DeclGroupRef D);
264
    void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG);
265
    void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl, 
266
                                     const std::string &typedefString);
267
    void RewriteImplementations();
268
    void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
269
                                 ObjCImplementationDecl *IMD,
270
                                 ObjCCategoryImplDecl *CID);
271
    void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
272
    void RewriteImplementationDecl(Decl *Dcl);
273
    void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
274
                               ObjCMethodDecl *MDecl, std::string &ResultStr);
275
    void RewriteTypeIntoString(QualType T, std::string &ResultStr,
276
                               const FunctionType *&FPRetType);
277
    void RewriteByRefString(std::string &ResultStr, const std::string &Name,
278
                            ValueDecl *VD, bool def=false);
279
    void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
280
    void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
281
    void RewriteForwardProtocolDecl(DeclGroupRef D);
282
    void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG);
283
    void RewriteMethodDeclaration(ObjCMethodDecl *Method);
284
    void RewriteProperty(ObjCPropertyDecl *prop);
285
    void RewriteFunctionDecl(FunctionDecl *FD);
286
    void RewriteBlockPointerType(std::string& Str, QualType Type);
287
    void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
288
    void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
289
    void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
290
    void RewriteTypeOfDecl(VarDecl *VD);
291
    void RewriteObjCQualifiedInterfaceTypes(Expr *E);
292
  
293
    // Expression Rewriting.
294
    Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
295
    Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
296
    Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
297
    Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
298
    Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
299
    Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
300
    Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
301
    Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
302
    void RewriteTryReturnStmts(Stmt *S);
303
    void RewriteSyncReturnStmts(Stmt *S, std::string buf);
304
    Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
305
    Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
306
    Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
307
    Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
308
                                       SourceLocation OrigEnd);
309
    Stmt *RewriteBreakStmt(BreakStmt *S);
310
    Stmt *RewriteContinueStmt(ContinueStmt *S);
311
    void RewriteCastExpr(CStyleCastExpr *CE);
312
    
313
    // Block rewriting.
314
    void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
315
    
316
    // Block specific rewrite rules.
317
    void RewriteBlockPointerDecl(NamedDecl *VD);
318
    void RewriteByRefVar(VarDecl *VD);
319
    Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
320
    Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
321
    void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
322
    
323
    void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
324
                                      std::string &Result);
325
326
    void Initialize(ASTContext &context) override = 0;
327
328
    // Metadata Rewriting.
329
    virtual void RewriteMetaDataIntoBuffer(std::string &Result) = 0;
330
    virtual void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
331
                                                 StringRef prefix,
332
                                                 StringRef ClassName,
333
                                                 std::string &Result) = 0;
334
    virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
335
                                             std::string &Result) = 0;
336
    virtual void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
337
                                     StringRef prefix,
338
                                     StringRef ClassName,
339
                                     std::string &Result) = 0;
340
    virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
341
                                          std::string &Result) = 0;
342
    
343
    // Rewriting ivar access
344
    virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) = 0;
345
    virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
346
                                         std::string &Result) = 0;
347
    
348
    // Misc. AST transformation routines. Sometimes they end up calling
349
    // rewriting routines on the new ASTs.
350
    CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
351
                                           ArrayRef<Expr *> Args,
352
                                           SourceLocation StartLoc=SourceLocation(),
353
                                           SourceLocation EndLoc=SourceLocation());
354
    CallExpr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
355
                                        QualType msgSendType, 
356
                                        QualType returnType, 
357
                                        SmallVectorImpl<QualType> &ArgTypes,
358
                                        SmallVectorImpl<Expr*> &MsgExprs,
359
                                        ObjCMethodDecl *Method);
360
    Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
361
                           SourceLocation StartLoc=SourceLocation(),
362
                           SourceLocation EndLoc=SourceLocation());
363
    
364
    void SynthCountByEnumWithState(std::string &buf);
365
    void SynthMsgSendFunctionDecl();
366
    void SynthMsgSendSuperFunctionDecl();
367
    void SynthMsgSendStretFunctionDecl();
368
    void SynthMsgSendFpretFunctionDecl();
369
    void SynthMsgSendSuperStretFunctionDecl();
370
    void SynthGetClassFunctionDecl();
371
    void SynthGetMetaClassFunctionDecl();
372
    void SynthGetSuperClassFunctionDecl();
373
    void SynthSelGetUidFunctionDecl();
374
    void SynthSuperConstructorFunctionDecl();
375
    
376
    std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
377
    std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
378
                                      StringRef funcName, std::string Tag);
379
    std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
380
                                      StringRef funcName, std::string Tag);
381
    std::string SynthesizeBlockImpl(BlockExpr *CE, 
382
                                    std::string Tag, std::string Desc);
383
    std::string SynthesizeBlockDescriptor(std::string DescTag, 
384
                                          std::string ImplTag,
385
                                          int i, StringRef funcName,
386
                                          unsigned hasCopy);
387
    Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
388
    void SynthesizeBlockLiterals(SourceLocation FunLocStart,
389
                                 StringRef FunName);
390
    FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
391
    Stmt *SynthBlockInitExpr(BlockExpr *Exp,
392
            const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
393
394
    // Misc. helper routines.
395
    QualType getProtocolType();
396
    void WarnAboutReturnGotoStmts(Stmt *S);
397
    void HasReturnStmts(Stmt *S, bool &hasReturns);
398
    void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
399
    void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
400
    void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
401
402
    bool IsDeclStmtInForeachHeader(DeclStmt *DS);
403
    void CollectBlockDeclRefInfo(BlockExpr *Exp);
404
    void GetBlockDeclRefExprs(Stmt *S);
405
    void GetInnerBlockDeclRefExprs(Stmt *S,
406
                SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
407
                llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts);
408
409
    // We avoid calling Type::isBlockPointerType(), since it operates on the
410
    // canonical type. We only care if the top-level type is a closure pointer.
411
845
    bool isTopLevelBlockPointerType(QualType T) {
412
845
      return isa<BlockPointerType>(T);
413
845
    }
414
415
    /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
416
    /// to a function pointer type and upon success, returns true; false
417
    /// otherwise.
418
324
    bool convertBlockPointerToFunctionPointer(QualType &T) {
419
324
      if (
isTopLevelBlockPointerType(T)324
) {
420
14
        const BlockPointerType *BPT = T->getAs<BlockPointerType>();
421
14
        T = Context->getPointerType(BPT->getPointeeType());
422
14
        return true;
423
14
      }
424
310
      return false;
425
310
    }
426
    
427
    bool needToScanForQualifiers(QualType T);
428
    QualType getSuperStructType();
429
    QualType getConstantStringStructType();
430
    QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
431
    bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
432
    
433
109
    void convertToUnqualifiedObjCType(QualType &T) {
434
109
      if (T->isObjCQualifiedIdType())
435
2
        T = Context->getObjCIdType();
436
107
      else 
if (107
T->isObjCQualifiedClassType()107
)
437
0
        T = Context->getObjCClassType();
438
107
      else 
if (107
T->isObjCObjectPointerType() &&
439
107
               
T->getPointeeType()->isObjCQualifiedInterfaceType()56
) {
440
12
        if (const ObjCObjectPointerType * OBJPT =
441
12
              T->getAsObjCInterfacePointerType()) {
442
12
          const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
443
12
          T = QualType(IFaceT, 0);
444
12
          T = Context->getPointerType(T);
445
12
        }
446
107
     }
447
109
    }
448
    
449
    // FIXME: This predicate seems like it would be useful to add to ASTContext.
450
42
    bool isObjCType(QualType T) {
451
42
      if (
!LangOpts.ObjC1 && 42
!LangOpts.ObjC20
)
452
0
        return false;
453
42
454
42
      QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
455
42
456
42
      if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
457
35
          OCT == Context->getCanonicalType(Context->getObjCClassType()))
458
7
        return true;
459
35
460
35
      
if (const PointerType *35
PT35
= OCT->getAs<PointerType>()) {
461
2
        if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
462
2
            PT->getPointeeType()->isObjCQualifiedIdType())
463
0
          return true;
464
35
      }
465
35
      return false;
466
35
    }
467
    bool PointerTypeTakesAnyBlockArguments(QualType QT);
468
    bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
469
    void GetExtentOfArgList(const char *Name, const char *&LParen,
470
                            const char *&RParen);
471
    
472
43
    void QuoteDoublequotes(std::string &From, std::string &To) {
473
347
      for (unsigned i = 0; 
i < From.length()347
;
i++304
) {
474
304
        if (From[i] == '"')
475
38
          To += "\\\"";
476
304
        else
477
266
          To += From[i];
478
304
      }
479
43
    }
480
481
    QualType getSimpleFunctionType(QualType result,
482
                                   ArrayRef<QualType> args,
483
435
                                   bool variadic = false) {
484
435
      if (result == Context->getObjCInstanceType())
485
0
        result =  Context->getObjCIdType();
486
435
      FunctionProtoType::ExtProtoInfo fpi;
487
435
      fpi.Variadic = variadic;
488
435
      return Context->getFunctionType(result, args, fpi);
489
435
    }
490
491
    // Helper function: create a CStyleCastExpr with trivial type source info.
492
    CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
493
620
                                             CastKind Kind, Expr *E) {
494
620
      TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
495
620
      return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, nullptr,
496
620
                                    TInfo, SourceLocation(), SourceLocation());
497
620
    }
498
499
139
    StringLiteral *getStringLiteral(StringRef Str) {
500
139
      QualType StrType = Context->getConstantArrayType(
501
139
          Context->CharTy, llvm::APInt(32, Str.size() + 1), ArrayType::Normal,
502
139
          0);
503
139
      return StringLiteral::Create(*Context, Str, StringLiteral::Ascii,
504
139
                                   /*Pascal=*/false, StrType, SourceLocation());
505
139
    }
506
  };
507
  
508
  class RewriteObjCFragileABI : public RewriteObjC {
509
  public:
510
    RewriteObjCFragileABI(std::string inFile, std::unique_ptr<raw_ostream> OS,
511
                          DiagnosticsEngine &D, const LangOptions &LOpts,
512
                          bool silenceMacroWarn)
513
86
        : RewriteObjC(inFile, std::move(OS), D, LOpts, silenceMacroWarn) {}
514
515
86
    ~RewriteObjCFragileABI() override {}
516
    void Initialize(ASTContext &context) override;
517
518
    // Rewriting metadata
519
    template<typename MethodIterator>
520
    void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
521
                                    MethodIterator MethodEnd,
522
                                    bool IsInstanceMethod,
523
                                    StringRef prefix,
524
                                    StringRef ClassName,
525
                                    std::string &Result);
526
    void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
527
                                     StringRef prefix, StringRef ClassName,
528
                                     std::string &Result) override;
529
    void RewriteObjCProtocolListMetaData(
530
          const ObjCList<ObjCProtocolDecl> &Prots,
531
          StringRef prefix, StringRef ClassName, std::string &Result) override;
532
    void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
533
                                  std::string &Result) override;
534
    void RewriteMetaDataIntoBuffer(std::string &Result) override;
535
    void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
536
                                     std::string &Result) override;
537
538
    // Rewriting ivar
539
    void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
540
                                      std::string &Result) override;
541
    Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) override;
542
  };
543
} // end anonymous namespace
544
545
void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
546
136
                                                   NamedDecl *D) {
547
136
  if (const FunctionProtoType *fproto
548
113
      = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
549
113
    for (const auto &I : fproto->param_types())
550
101
      
if (101
isTopLevelBlockPointerType(I)101
) {
551
20
        // All the args are checked/rewritten. Don't call twice!
552
20
        RewriteBlockPointerDecl(D);
553
20
        break;
554
20
      }
555
136
  }
556
136
}
557
558
1
void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
559
1
  const PointerType *PT = funcType->getAs<PointerType>();
560
1
  if (
PT && 1
PointerTypeTakesAnyBlockArguments(funcType)1
)
561
0
    RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
562
1
}
563
564
86
static bool IsHeaderFile(const std::string &Filename) {
565
86
  std::string::size_type DotPos = Filename.rfind('.');
566
86
567
86
  if (
DotPos == std::string::npos86
) {
568
0
    // no file extension
569
0
    return false;
570
0
  }
571
86
572
86
  std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
573
86
  // C header: .h
574
86
  // C++ header: .hh or .H;
575
86
  return Ext == "h" || 
Ext == "hh"86
||
Ext == "H"86
;
576
86
}
577
578
RewriteObjC::RewriteObjC(std::string inFile, std::unique_ptr<raw_ostream> OS,
579
                         DiagnosticsEngine &D, const LangOptions &LOpts,
580
                         bool silenceMacroWarn)
581
    : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(std::move(OS)),
582
86
      SilenceRewriteMacroWarning(silenceMacroWarn) {
583
86
  IsHeader = IsHeaderFile(inFile);
584
86
  RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
585
86
               "rewriting sub-expression within a macro (may not be correct)");
586
86
  TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
587
86
               DiagnosticsEngine::Warning,
588
86
               "rewriter doesn't support user-specified control flow semantics "
589
86
               "for @try/@finally (code may not execute properly)");
590
86
}
591
592
std::unique_ptr<ASTConsumer>
593
clang::CreateObjCRewriter(const std::string &InFile,
594
                          std::unique_ptr<raw_ostream> OS,
595
                          DiagnosticsEngine &Diags, const LangOptions &LOpts,
596
86
                          bool SilenceRewriteMacroWarning) {
597
86
  return llvm::make_unique<RewriteObjCFragileABI>(
598
86
      InFile, std::move(OS), Diags, LOpts, SilenceRewriteMacroWarning);
599
86
}
600
601
86
void RewriteObjC::InitializeCommon(ASTContext &context) {
602
86
  Context = &context;
603
86
  SM = &Context->getSourceManager();
604
86
  TUDecl = Context->getTranslationUnitDecl();
605
86
  MsgSendFunctionDecl = nullptr;
606
86
  MsgSendSuperFunctionDecl = nullptr;
607
86
  MsgSendStretFunctionDecl = nullptr;
608
86
  MsgSendSuperStretFunctionDecl = nullptr;
609
86
  MsgSendFpretFunctionDecl = nullptr;
610
86
  GetClassFunctionDecl = nullptr;
611
86
  GetMetaClassFunctionDecl = nullptr;
612
86
  GetSuperClassFunctionDecl = nullptr;
613
86
  SelGetUidFunctionDecl = nullptr;
614
86
  CFStringFunctionDecl = nullptr;
615
86
  ConstantStringClassReference = nullptr;
616
86
  NSStringRecord = nullptr;
617
86
  CurMethodDef = nullptr;
618
86
  CurFunctionDef = nullptr;
619
86
  CurFunctionDeclToDeclareForBlock = nullptr;
620
86
  GlobalVarDecl = nullptr;
621
86
  SuperStructDecl = nullptr;
622
86
  ProtocolTypeDecl = nullptr;
623
86
  ConstantStringDecl = nullptr;
624
86
  BcLabelCount = 0;
625
86
  SuperConstructorFunctionDecl = nullptr;
626
86
  NumObjCStringLiterals = 0;
627
86
  PropParentMap = nullptr;
628
86
  CurrentBody = nullptr;
629
86
  DisableReplaceStmt = false;
630
86
  objc_impl_method = false;
631
86
632
86
  // Get the ID and start/end of the main file.
633
86
  MainFileID = SM->getMainFileID();
634
86
  const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
635
86
  MainFileStart = MainBuf->getBufferStart();
636
86
  MainFileEnd = MainBuf->getBufferEnd();
637
86
638
86
  Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
639
86
}
640
641
//===----------------------------------------------------------------------===//
642
// Top Level Driver Code
643
//===----------------------------------------------------------------------===//
644
645
524
void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
646
524
  if (Diags.hasErrorOccurred())
647
0
    return;
648
524
649
524
  // Two cases: either the decl could be in the main file, or it could be in a
650
524
  // #included file.  If the former, rewrite it now.  If the later, check to see
651
524
  // if we rewrote the #include/#import.
652
524
  SourceLocation Loc = D->getLocation();
653
524
  Loc = SM->getExpansionLoc(Loc);
654
524
655
524
  // If this is for a builtin, ignore it.
656
524
  if (
Loc.isInvalid()524
)
return0
;
657
524
658
524
  // Look for built-in declarations that we need to refer during the rewrite.
659
524
  
if (FunctionDecl *524
FD524
= dyn_cast<FunctionDecl>(D)) {
660
136
    RewriteFunctionDecl(FD);
661
524
  } else 
if (VarDecl *388
FVD388
= dyn_cast<VarDecl>(D)) {
662
17
    // declared in <Foundation/NSString.h>
663
17
    if (
FVD->getName() == "_NSConstantStringClassReference"17
) {
664
0
      ConstantStringClassReference = FVD;
665
0
      return;
666
0
    }
667
371
  } else 
if (ObjCInterfaceDecl *371
ID371
= dyn_cast<ObjCInterfaceDecl>(D)) {
668
118
    if (ID->isThisDeclarationADefinition())
669
118
      RewriteInterfaceDecl(ID);
670
371
  } else 
if (ObjCCategoryDecl *253
CD253
= dyn_cast<ObjCCategoryDecl>(D)) {
671
6
    RewriteCategoryDecl(CD);
672
253
  } else 
if (ObjCProtocolDecl *247
PD247
= dyn_cast<ObjCProtocolDecl>(D)) {
673
21
    if (PD->isThisDeclarationADefinition())
674
21
      RewriteProtocolDecl(PD);
675
247
  } else 
if (LinkageSpecDecl *226
LSD226
= dyn_cast<LinkageSpecDecl>(D)) {
676
13
    // Recurse into linkage specifications
677
13
    for (DeclContext::decl_iterator DI = LSD->decls_begin(),
678
13
                                 DIEnd = LSD->decls_end();
679
27
         
DI != DIEnd27
; ) {
680
14
      if (ObjCInterfaceDecl *
IFace14
= dyn_cast<ObjCInterfaceDecl>((*DI))) {
681
0
        if (
!IFace->isThisDeclarationADefinition()0
) {
682
0
          SmallVector<Decl *, 8> DG;
683
0
          SourceLocation StartLoc = IFace->getLocStart();
684
0
          do {
685
0
            if (isa<ObjCInterfaceDecl>(*DI) &&
686
0
                !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
687
0
                StartLoc == (*DI)->getLocStart())
688
0
              DG.push_back(*DI);
689
0
            else
690
0
              break;
691
0
            
692
0
            ++DI;
693
0
          } while (DI != DIEnd);
694
0
          RewriteForwardClassDecl(DG);
695
0
          continue;
696
0
        }
697
14
      }
698
14
699
14
      
if (ObjCProtocolDecl *14
Proto14
= dyn_cast<ObjCProtocolDecl>((*DI))) {
700
0
        if (
!Proto->isThisDeclarationADefinition()0
) {
701
0
          SmallVector<Decl *, 8> DG;
702
0
          SourceLocation StartLoc = Proto->getLocStart();
703
0
          do {
704
0
            if (isa<ObjCProtocolDecl>(*DI) &&
705
0
                !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
706
0
                StartLoc == (*DI)->getLocStart())
707
0
              DG.push_back(*DI);
708
0
            else
709
0
              break;
710
0
            
711
0
            ++DI;
712
0
          } while (DI != DIEnd);
713
0
          RewriteForwardProtocolDecl(DG);
714
0
          continue;
715
0
        }
716
14
      }
717
14
      
718
14
      HandleTopLevelSingleDecl(*DI);
719
14
      ++DI;
720
14
    }
721
388
  }
722
524
  // If we have a decl in the main file, see if we should rewrite it.
723
524
  
if (524
SM->isWrittenInMainFile(Loc)524
)
724
522
    return HandleDeclInMainFile(D);
725
2
}
726
727
//===----------------------------------------------------------------------===//
728
// Syntactic (non-AST) Rewriting Code
729
//===----------------------------------------------------------------------===//
730
731
86
void RewriteObjC::RewriteInclude() {
732
86
  SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
733
86
  StringRef MainBuf = SM->getBufferData(MainFileID);
734
86
  const char *MainBufStart = MainBuf.begin();
735
86
  const char *MainBufEnd = MainBuf.end();
736
86
  size_t ImportLen = strlen("import");
737
86
738
86
  // Loop over the whole file, looking for includes.
739
60.2k
  for (const char *BufPtr = MainBufStart; 
BufPtr < MainBufEnd60.2k
;
++BufPtr60.1k
) {
740
60.1k
    if (
*BufPtr == '#'60.1k
) {
741
23
      if (++BufPtr == MainBufEnd)
742
0
        return;
743
44
      
while (23
*BufPtr == ' ' || 44
*BufPtr == '\t'23
)
744
21
        
if (21
++BufPtr == MainBufEnd21
)
745
0
          return;
746
23
      
if (23
!strncmp(BufPtr, "import", ImportLen)23
) {
747
0
        // replace import with include
748
0
        SourceLocation ImportLoc =
749
0
          LocStart.getLocWithOffset(BufPtr-MainBufStart);
750
0
        ReplaceText(ImportLoc, ImportLen, "include");
751
0
        BufPtr += ImportLen;
752
0
      }
753
23
    }
754
60.1k
  }
755
86
}
756
757
3
static std::string getIvarAccessString(ObjCIvarDecl *OID) {
758
3
  const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
759
3
  std::string S;
760
3
  S = "((struct ";
761
3
  S += ClassDecl->getIdentifier()->getName();
762
3
  S += "_IMPL *)self)->";
763
3
  S += OID->getName();
764
3
  return S;
765
3
}
766
767
void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
768
                                          ObjCImplementationDecl *IMD,
769
12
                                          ObjCCategoryImplDecl *CID) {
770
12
  static bool objcGetPropertyDefined = false;
771
12
  static bool objcSetPropertyDefined = false;
772
12
  SourceLocation startLoc = PID->getLocStart();
773
12
  InsertText(startLoc, "// ");
774
12
  const char *startBuf = SM->getCharacterData(startLoc);
775
12
  assert((*startBuf == '@') && "bogus @synthesize location");
776
12
  const char *semiBuf = strchr(startBuf, ';');
777
12
  assert((*semiBuf == ';') && "@synthesize: can't find ';'");
778
12
  SourceLocation onePastSemiLoc =
779
12
    startLoc.getLocWithOffset(semiBuf-startBuf+1);
780
12
781
12
  if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
782
2
    return; // FIXME: is this correct?
783
10
784
10
  // Generate the 'getter' function.
785
10
  ObjCPropertyDecl *PD = PID->getPropertyDecl();
786
10
  ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
787
10
788
10
  if (!OID)
789
0
    return;
790
10
  unsigned Attributes = PD->getPropertyAttributes();
791
10
  if (
!PD->getGetterMethodDecl()->isDefined()10
) {
792
9
    bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
793
9
                          (Attributes & (ObjCPropertyDecl::OBJC_PR_retain | 
794
9
                                         ObjCPropertyDecl::OBJC_PR_copy));
795
9
    std::string Getr;
796
9
    if (
GenGetProperty && 9
!objcGetPropertyDefined7
) {
797
5
      objcGetPropertyDefined = true;
798
5
      // FIXME. Is this attribute correct in all cases?
799
5
      Getr = "\nextern \"C\" __declspec(dllimport) "
800
5
            "id objc_getProperty(id, SEL, long, bool);\n";
801
5
    }
802
9
    RewriteObjCMethodDecl(OID->getContainingInterface(),  
803
9
                          PD->getGetterMethodDecl(), Getr);
804
9
    Getr += "{ ";
805
9
    // Synthesize an explicit cast to gain access to the ivar.
806
9
    // See objc-act.c:objc_synthesize_new_getter() for details.
807
9
    if (
GenGetProperty9
) {
808
7
      // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
809
7
      Getr += "typedef ";
810
7
      const FunctionType *FPRetType = nullptr;
811
7
      RewriteTypeIntoString(PD->getGetterMethodDecl()->getReturnType(), Getr,
812
7
                            FPRetType);
813
7
      Getr += " _TYPE";
814
7
      if (
FPRetType7
) {
815
1
        Getr += ")"; // close the precedence "scope" for "*".
816
1
      
817
1
        // Now, emit the argument types (if any).
818
1
        if (const FunctionProtoType *
FT1
= dyn_cast<FunctionProtoType>(FPRetType)){
819
1
          Getr += "(";
820
1
          for (unsigned i = 0, e = FT->getNumParams(); 
i != e1
;
++i0
) {
821
0
            if (
i0
)
Getr += ", "0
;
822
0
            std::string ParamStr =
823
0
                FT->getParamType(i).getAsString(Context->getPrintingPolicy());
824
0
            Getr += ParamStr;
825
0
          }
826
1
          if (
FT->isVariadic()1
) {
827
0
            if (FT->getNumParams())
828
0
              Getr += ", ";
829
0
            Getr += "...";
830
0
          }
831
1
          Getr += ")";
832
1
        } else
833
0
          Getr += "()";
834
1
      }
835
7
      Getr += ";\n";
836
7
      Getr += "return (_TYPE)";
837
7
      Getr += "objc_getProperty(self, _cmd, ";
838
7
      RewriteIvarOffsetComputation(OID, Getr);
839
7
      Getr += ", 1)";
840
7
    }
841
9
    else
842
2
      Getr += "return " + getIvarAccessString(OID);
843
9
    Getr += "; }";
844
9
    InsertText(onePastSemiLoc, Getr);
845
9
  }
846
10
  
847
10
  if (
PD->isReadOnly() || 10
PD->getSetterMethodDecl()->isDefined()9
)
848
2
    return;
849
8
850
8
  // Generate the 'setter' function.
851
8
  std::string Setr;
852
8
  bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain | 
853
8
                                      ObjCPropertyDecl::OBJC_PR_copy);
854
8
  if (
GenSetProperty && 8
!objcSetPropertyDefined7
) {
855
5
    objcSetPropertyDefined = true;
856
5
    // FIXME. Is this attribute correct in all cases?
857
5
    Setr = "\nextern \"C\" __declspec(dllimport) "
858
5
    "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
859
5
  }
860
8
  
861
8
  RewriteObjCMethodDecl(OID->getContainingInterface(), 
862
8
                        PD->getSetterMethodDecl(), Setr);
863
8
  Setr += "{ ";
864
8
  // Synthesize an explicit cast to initialize the ivar.
865
8
  // See objc-act.c:objc_synthesize_new_setter() for details.
866
8
  if (
GenSetProperty8
) {
867
7
    Setr += "objc_setProperty (self, _cmd, ";
868
7
    RewriteIvarOffsetComputation(OID, Setr);
869
7
    Setr += ", (id)";
870
7
    Setr += PD->getName();
871
7
    Setr += ", ";
872
7
    if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
873
0
      Setr += "0, ";
874
7
    else
875
7
      Setr += "1, ";
876
7
    if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
877
3
      Setr += "1)";
878
7
    else
879
4
      Setr += "0)";
880
7
  }
881
1
  else {
882
1
    Setr += getIvarAccessString(OID) + " = ";
883
1
    Setr += PD->getName();
884
1
  }
885
12
  Setr += "; }";
886
12
  InsertText(onePastSemiLoc, Setr);
887
12
}
888
889
static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
890
27
                                       std::string &typedefString) {
891
27
  typedefString += "#ifndef _REWRITER_typedef_";
892
27
  typedefString += ForwardDecl->getNameAsString();
893
27
  typedefString += "\n";
894
27
  typedefString += "#define _REWRITER_typedef_";
895
27
  typedefString += ForwardDecl->getNameAsString();
896
27
  typedefString += "\n";
897
27
  typedefString += "typedef struct objc_object ";
898
27
  typedefString += ForwardDecl->getNameAsString();
899
27
  typedefString += ";\n#endif\n";
900
27
}
901
902
void RewriteObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
903
17
                                              const std::string &typedefString) {
904
17
    SourceLocation startLoc = ClassDecl->getLocStart();
905
17
    const char *startBuf = SM->getCharacterData(startLoc);
906
17
    const char *semiPtr = strchr(startBuf, ';'); 
907
17
    // Replace the @class with typedefs corresponding to the classes.
908
17
    ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);  
909
17
}
910
911
17
void RewriteObjC::RewriteForwardClassDecl(DeclGroupRef D) {
912
17
  std::string typedefString;
913
44
  for (DeclGroupRef::iterator I = D.begin(), E = D.end(); 
I != E44
;
++I27
) {
914
27
    ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
915
27
    if (
I == D.begin()27
) {
916
17
      // Translate to typedef's that forward reference structs with the same name
917
17
      // as the class. As a convenience, we include the original declaration
918
17
      // as a comment.
919
17
      typedefString += "// @class ";
920
17
      typedefString += ForwardDecl->getNameAsString();
921
17
      typedefString += ";\n";
922
17
    }
923
27
    RewriteOneForwardClassDecl(ForwardDecl, typedefString);
924
27
  }
925
17
  DeclGroupRef::iterator I = D.begin();
926
17
  RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
927
17
}
928
929
0
void RewriteObjC::RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &D) {
930
0
  std::string typedefString;
931
0
  for (unsigned i = 0; 
i < D.size()0
;
i++0
) {
932
0
    ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
933
0
    if (
i == 00
) {
934
0
      typedefString += "// @class ";
935
0
      typedefString += ForwardDecl->getNameAsString();
936
0
      typedefString += ";\n";
937
0
    }
938
0
    RewriteOneForwardClassDecl(ForwardDecl, typedefString);
939
0
  }
940
0
  RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
941
0
}
942
943
123
void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
944
123
  // When method is a synthesized one, such as a getter/setter there is
945
123
  // nothing to rewrite.
946
123
  if (Method->isImplicit())
947
42
    return;
948
81
  SourceLocation LocStart = Method->getLocStart();
949
81
  SourceLocation LocEnd = Method->getLocEnd();
950
81
951
81
  if (SM->getExpansionLineNumber(LocEnd) >
952
81
      SM->getExpansionLineNumber(LocStart)) {
953
0
    InsertText(LocStart, "#if 0\n");
954
0
    ReplaceText(LocEnd, 1, ";\n#endif\n");
955
81
  } else {
956
81
    InsertText(LocStart, "// ");
957
81
  }
958
123
}
959
960
23
void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
961
23
  SourceLocation Loc = prop->getAtLoc();
962
23
963
23
  ReplaceText(Loc, 0, "// ");
964
23
  // FIXME: handle properties that are declared across multiple lines.
965
23
}
966
967
6
void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
968
6
  SourceLocation LocStart = CatDecl->getLocStart();
969
6
970
6
  // FIXME: handle category headers that are declared across multiple lines.
971
6
  ReplaceText(LocStart, 0, "// ");
972
6
973
6
  for (auto *I : CatDecl->instance_properties())
974
1
    RewriteProperty(I);  
975
6
  for (auto *I : CatDecl->instance_methods())
976
6
    RewriteMethodDeclaration(I);
977
6
  for (auto *I : CatDecl->class_methods())
978
0
    RewriteMethodDeclaration(I);
979
6
980
6
  // Lastly, comment out the @end.
981
6
  ReplaceText(CatDecl->getAtEndRange().getBegin(), 
982
6
              strlen("@end"), "/* @end */");
983
6
}
984
985
21
void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
986
21
  SourceLocation LocStart = PDecl->getLocStart();
987
21
  assert(PDecl->isThisDeclarationADefinition());
988
21
  
989
21
  // FIXME: handle protocol headers that are declared across multiple lines.
990
21
  ReplaceText(LocStart, 0, "// ");
991
21
992
21
  for (auto *I : PDecl->instance_methods())
993
13
    RewriteMethodDeclaration(I);
994
21
  for (auto *I : PDecl->class_methods())
995
1
    RewriteMethodDeclaration(I);
996
21
  for (auto *I : PDecl->instance_properties())
997
2
    RewriteProperty(I);
998
21
  
999
21
  // Lastly, comment out the @end.
1000
21
  SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1001
21
  ReplaceText(LocEnd, strlen("@end"), "/* @end */");
1002
21
1003
21
  // Must comment out @optional/@required
1004
21
  const char *startBuf = SM->getCharacterData(LocStart);
1005
21
  const char *endBuf = SM->getCharacterData(LocEnd);
1006
998
  for (const char *p = startBuf; 
p < endBuf998
;
p++977
) {
1007
977
    if (
*p == '@' && 977
!strncmp(p+1, "optional", strlen("optional"))25
) {
1008
2
      SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1009
2
      ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1010
2
1011
2
    }
1012
975
    else 
if (975
*p == '@' && 975
!strncmp(p+1, "required", strlen("required"))23
) {
1013
0
      SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1014
0
      ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1015
0
1016
0
    }
1017
977
  }
1018
21
}
1019
1020
6
void RewriteObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1021
6
  SourceLocation LocStart = (*D.begin())->getLocStart();
1022
6
  if (LocStart.isInvalid())
1023
0
    llvm_unreachable("Invalid SourceLocation");
1024
6
  // FIXME: handle forward protocol that are declared across multiple lines.
1025
6
  ReplaceText(LocStart, 0, "// ");
1026
6
}
1027
1028
void 
1029
0
RewriteObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
1030
0
  SourceLocation LocStart = DG[0]->getLocStart();
1031
0
  if (LocStart.isInvalid())
1032
0
    llvm_unreachable("Invalid SourceLocation");
1033
0
  // FIXME: handle forward protocol that are declared across multiple lines.
1034
0
  ReplaceText(LocStart, 0, "// ");
1035
0
}
1036
1037
void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1038
101
                                        const FunctionType *&FPRetType) {
1039
101
  if (T->isObjCQualifiedIdType())
1040
2
    ResultStr += "id";
1041
99
  else 
if (99
T->isFunctionPointerType() ||
1042
99
           
T->isBlockPointerType()99
) {
1043
3
    // needs special handling, since pointer-to-functions have special
1044
3
    // syntax (where a decaration models use).
1045
3
    QualType retType = T;
1046
3
    QualType PointeeTy;
1047
3
    if (const PointerType* PT = retType->getAs<PointerType>())
1048
0
      PointeeTy = PT->getPointeeType();
1049
3
    else 
if (const BlockPointerType *3
BPT3
= retType->getAs<BlockPointerType>())
1050
3
      PointeeTy = BPT->getPointeeType();
1051
3
    if (
(FPRetType = PointeeTy->getAs<FunctionType>())3
) {
1052
3
      ResultStr +=
1053
3
          FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
1054
3
      ResultStr += "(*";
1055
3
    }
1056
3
  } else
1057
96
    ResultStr += T.getAsString(Context->getPrintingPolicy());
1058
101
}
1059
1060
void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1061
                                        ObjCMethodDecl *OMD,
1062
94
                                        std::string &ResultStr) {
1063
94
  //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1064
94
  const FunctionType *FPRetType = nullptr;
1065
94
  ResultStr += "\nstatic ";
1066
94
  RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
1067
94
  ResultStr += " ";
1068
94
1069
94
  // Unique method name
1070
94
  std::string NameStr;
1071
94
1072
94
  if (OMD->isInstanceMethod())
1073
88
    NameStr += "_I_";
1074
94
  else
1075
6
    NameStr += "_C_";
1076
94
1077
94
  NameStr += IDecl->getNameAsString();
1078
94
  NameStr += "_";
1079
94
1080
94
  if (ObjCCategoryImplDecl *CID =
1081
6
      dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1082
6
    NameStr += CID->getNameAsString();
1083
6
    NameStr += "_";
1084
6
  }
1085
94
  // Append selector names, replacing ':' with '_'
1086
94
  {
1087
94
    std::string selString = OMD->getSelector().getAsString();
1088
94
    int len = selString.size();
1089
1.11k
    for (int i = 0; 
i < len1.11k
;
i++1.02k
)
1090
1.02k
      
if (1.02k
selString[i] == ':'1.02k
)
1091
47
        selString[i] = '_';
1092
94
    NameStr += selString;
1093
94
  }
1094
94
  // Remember this name for metadata emission
1095
94
  MethodInternalNames[OMD] = NameStr;
1096
94
  ResultStr += NameStr;
1097
94
1098
94
  // Rewrite arguments
1099
94
  ResultStr += "(";
1100
94
1101
94
  // invisible arguments
1102
94
  if (
OMD->isInstanceMethod()94
) {
1103
88
    QualType selfTy = Context->getObjCInterfaceType(IDecl);
1104
88
    selfTy = Context->getPointerType(selfTy);
1105
88
    if (
!LangOpts.MicrosoftExt88
) {
1106
30
      if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1107
8
        ResultStr += "struct ";
1108
30
    }
1109
88
    // When rewriting for Microsoft, explicitly omit the structure name.
1110
88
    ResultStr += IDecl->getNameAsString();
1111
88
    ResultStr += " *";
1112
88
  }
1113
94
  else
1114
6
    ResultStr += Context->getObjCClassType().getAsString(
1115
6
      Context->getPrintingPolicy());
1116
94
1117
94
  ResultStr += " self, ";
1118
94
  ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1119
94
  ResultStr += " _cmd";
1120
94
1121
94
  // Method arguments.
1122
47
  for (const auto *PDecl : OMD->parameters()) {
1123
47
    ResultStr += ", ";
1124
47
    if (
PDecl->getType()->isObjCQualifiedIdType()47
) {
1125
1
      ResultStr += "id ";
1126
1
      ResultStr += PDecl->getNameAsString();
1127
47
    } else {
1128
46
      std::string Name = PDecl->getNameAsString();
1129
46
      QualType QT = PDecl->getType();
1130
46
      // Make sure we convert "t (^)(...)" to "t (*)(...)".
1131
46
      (void)convertBlockPointerToFunctionPointer(QT);
1132
46
      QT.getAsStringInternal(Name, Context->getPrintingPolicy());
1133
46
      ResultStr += Name;
1134
46
    }
1135
47
  }
1136
94
  if (OMD->isVariadic())
1137
1
    ResultStr += ", ...";
1138
94
  ResultStr += ") ";
1139
94
1140
94
  if (
FPRetType94
) {
1141
2
    ResultStr += ")"; // close the precedence "scope" for "*".
1142
2
1143
2
    // Now, emit the argument types (if any).
1144
2
    if (const FunctionProtoType *
FT2
= dyn_cast<FunctionProtoType>(FPRetType)) {
1145
2
      ResultStr += "(";
1146
2
      for (unsigned i = 0, e = FT->getNumParams(); 
i != e2
;
++i0
) {
1147
0
        if (
i0
)
ResultStr += ", "0
;
1148
0
        std::string ParamStr =
1149
0
            FT->getParamType(i).getAsString(Context->getPrintingPolicy());
1150
0
        ResultStr += ParamStr;
1151
0
      }
1152
2
      if (
FT->isVariadic()2
) {
1153
0
        if (FT->getNumParams())
1154
0
          ResultStr += ", ";
1155
0
        ResultStr += "...";
1156
0
      }
1157
2
      ResultStr += ")";
1158
0
    } else {
1159
0
      ResultStr += "()";
1160
0
    }
1161
2
  }
1162
94
}
1163
1164
70
void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
1165
70
  ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1166
70
  ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1167
70
1168
70
  InsertText(IMD ? 
IMD->getLocStart()64
:
CID->getLocStart()6
, "// ");
1169
70
1170
70
  for (auto *OMD : IMD ? 
IMD->instance_methods()64
:
CID->instance_methods()6
) {
1171
71
    std::string ResultStr;
1172
71
    RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1173
71
    SourceLocation LocStart = OMD->getLocStart();
1174
71
    SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1175
71
1176
71
    const char *startBuf = SM->getCharacterData(LocStart);
1177
71
    const char *endBuf = SM->getCharacterData(LocEnd);
1178
71
    ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1179
71
  }
1180
70
1181
70
  for (auto *OMD : IMD ? 
IMD->class_methods()64
:
CID->class_methods()6
) {
1182
6
    std::string ResultStr;
1183
6
    RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1184
6
    SourceLocation LocStart = OMD->getLocStart();
1185
6
    SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1186
6
1187
6
    const char *startBuf = SM->getCharacterData(LocStart);
1188
6
    const char *endBuf = SM->getCharacterData(LocEnd);
1189
6
    ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1190
6
  }
1191
70
  for (auto *I : IMD ? 
IMD->property_impls()64
:
CID->property_impls()6
)
1192
12
    RewritePropertyImplDecl(I, IMD, CID);
1193
70
1194
70
  InsertText(IMD ? 
IMD->getLocEnd()64
:
CID->getLocEnd()6
, "// ");
1195
70
}
1196
1197
118
void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
1198
118
  std::string ResultStr;
1199
118
  if (
!ObjCForwardDecls.count(ClassDecl->getCanonicalDecl())118
) {
1200
118
    // we haven't seen a forward decl - generate a typedef.
1201
118
    ResultStr = "#ifndef _REWRITER_typedef_";
1202
118
    ResultStr += ClassDecl->getNameAsString();
1203
118
    ResultStr += "\n";
1204
118
    ResultStr += "#define _REWRITER_typedef_";
1205
118
    ResultStr += ClassDecl->getNameAsString();
1206
118
    ResultStr += "\n";
1207
118
    ResultStr += "typedef struct objc_object ";
1208
118
    ResultStr += ClassDecl->getNameAsString();
1209
118
    ResultStr += ";\n#endif\n";
1210
118
    // Mark this typedef as having been generated.
1211
118
    ObjCForwardDecls.insert(ClassDecl->getCanonicalDecl());
1212
118
  }
1213
118
  RewriteObjCInternalStruct(ClassDecl, ResultStr);
1214
118
1215
118
  for (auto *I : ClassDecl->instance_properties())
1216
20
    RewriteProperty(I);
1217
118
  for (auto *I : ClassDecl->instance_methods())
1218
92
    RewriteMethodDeclaration(I);
1219
118
  for (auto *I : ClassDecl->class_methods())
1220
11
    RewriteMethodDeclaration(I);
1221
118
1222
118
  // Lastly, comment out the @end.
1223
118
  ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"), 
1224
118
              "/* @end */");
1225
118
}
1226
1227
14
Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1228
14
  SourceRange OldRange = PseudoOp->getSourceRange();
1229
14
1230
14
  // We just magically know some things about the structure of this
1231
14
  // expression.
1232
14
  ObjCMessageExpr *OldMsg =
1233
14
    cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1234
14
                            PseudoOp->getNumSemanticExprs() - 1));
1235
14
1236
14
  // Because the rewriter doesn't allow us to rewrite rewritten code,
1237
14
  // we need to suppress rewriting the sub-statements.
1238
14
  Expr *Base, *RHS;
1239
14
  {
1240
14
    DisableReplaceStmtScope S(*this);
1241
14
1242
14
    // Rebuild the base expression if we have one.
1243
14
    Base = nullptr;
1244
14
    if (
OldMsg->getReceiverKind() == ObjCMessageExpr::Instance14
) {
1245
14
      Base = OldMsg->getInstanceReceiver();
1246
14
      Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1247
14
      Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1248
14
    }
1249
14
1250
14
    // Rebuild the RHS.
1251
14
    RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1252
14
    RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1253
14
    RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1254
14
  }
1255
14
1256
14
  // TODO: avoid this copy.
1257
14
  SmallVector<SourceLocation, 1> SelLocs;
1258
14
  OldMsg->getSelectorLocs(SelLocs);
1259
14
1260
14
  ObjCMessageExpr *NewMsg = nullptr;
1261
14
  switch (OldMsg->getReceiverKind()) {
1262
0
  case ObjCMessageExpr::Class:
1263
0
    NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1264
0
                                     OldMsg->getValueKind(),
1265
0
                                     OldMsg->getLeftLoc(),
1266
0
                                     OldMsg->getClassReceiverTypeInfo(),
1267
0
                                     OldMsg->getSelector(),
1268
0
                                     SelLocs,
1269
0
                                     OldMsg->getMethodDecl(),
1270
0
                                     RHS,
1271
0
                                     OldMsg->getRightLoc(),
1272
0
                                     OldMsg->isImplicit());
1273
0
    break;
1274
14
1275
14
  case ObjCMessageExpr::Instance:
1276
14
    NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1277
14
                                     OldMsg->getValueKind(),
1278
14
                                     OldMsg->getLeftLoc(),
1279
14
                                     Base,
1280
14
                                     OldMsg->getSelector(),
1281
14
                                     SelLocs,
1282
14
                                     OldMsg->getMethodDecl(),
1283
14
                                     RHS,
1284
14
                                     OldMsg->getRightLoc(),
1285
14
                                     OldMsg->isImplicit());
1286
14
    break;
1287
14
1288
0
  case ObjCMessageExpr::SuperClass:
1289
0
  case ObjCMessageExpr::SuperInstance:
1290
0
    NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1291
0
                                     OldMsg->getValueKind(),
1292
0
                                     OldMsg->getLeftLoc(),
1293
0
                                     OldMsg->getSuperLoc(),
1294
0
                 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1295
0
                                     OldMsg->getSuperType(),
1296
0
                                     OldMsg->getSelector(),
1297
0
                                     SelLocs,
1298
0
                                     OldMsg->getMethodDecl(),
1299
0
                                     RHS,
1300
0
                                     OldMsg->getRightLoc(),
1301
0
                                     OldMsg->isImplicit());
1302
0
    break;
1303
14
  }
1304
14
1305
14
  Stmt *Replacement = SynthMessageExpr(NewMsg);
1306
14
  ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1307
14
  return Replacement;
1308
14
}
1309
1310
22
Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1311
22
  SourceRange OldRange = PseudoOp->getSourceRange();
1312
22
1313
22
  // We just magically know some things about the structure of this
1314
22
  // expression.
1315
22
  ObjCMessageExpr *OldMsg =
1316
22
    cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1317
22
1318
22
  // Because the rewriter doesn't allow us to rewrite rewritten code,
1319
22
  // we need to suppress rewriting the sub-statements.
1320
22
  Expr *Base = nullptr;
1321
22
  {
1322
22
    DisableReplaceStmtScope S(*this);
1323
22
1324
22
    // Rebuild the base expression if we have one.
1325
22
    if (
OldMsg->getReceiverKind() == ObjCMessageExpr::Instance22
) {
1326
22
      Base = OldMsg->getInstanceReceiver();
1327
22
      Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1328
22
      Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1329
22
    }
1330
22
  }
1331
22
1332
22
  // Intentionally empty.
1333
22
  SmallVector<SourceLocation, 1> SelLocs;
1334
22
  SmallVector<Expr*, 1> Args;
1335
22
1336
22
  ObjCMessageExpr *NewMsg = nullptr;
1337
22
  switch (OldMsg->getReceiverKind()) {
1338
0
  case ObjCMessageExpr::Class:
1339
0
    NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1340
0
                                     OldMsg->getValueKind(),
1341
0
                                     OldMsg->getLeftLoc(),
1342
0
                                     OldMsg->getClassReceiverTypeInfo(),
1343
0
                                     OldMsg->getSelector(),
1344
0
                                     SelLocs,
1345
0
                                     OldMsg->getMethodDecl(),
1346
0
                                     Args,
1347
0
                                     OldMsg->getRightLoc(),
1348
0
                                     OldMsg->isImplicit());
1349
0
    break;
1350
22
1351
22
  case ObjCMessageExpr::Instance:
1352
22
    NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1353
22
                                     OldMsg->getValueKind(),
1354
22
                                     OldMsg->getLeftLoc(),
1355
22
                                     Base,
1356
22
                                     OldMsg->getSelector(),
1357
22
                                     SelLocs,
1358
22
                                     OldMsg->getMethodDecl(),
1359
22
                                     Args,
1360
22
                                     OldMsg->getRightLoc(),
1361
22
                                     OldMsg->isImplicit());
1362
22
    break;
1363
22
1364
0
  case ObjCMessageExpr::SuperClass:
1365
0
  case ObjCMessageExpr::SuperInstance:
1366
0
    NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1367
0
                                     OldMsg->getValueKind(),
1368
0
                                     OldMsg->getLeftLoc(),
1369
0
                                     OldMsg->getSuperLoc(),
1370
0
                 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1371
0
                                     OldMsg->getSuperType(),
1372
0
                                     OldMsg->getSelector(),
1373
0
                                     SelLocs,
1374
0
                                     OldMsg->getMethodDecl(),
1375
0
                                     Args,
1376
0
                                     OldMsg->getRightLoc(),
1377
0
                                     OldMsg->isImplicit());
1378
0
    break;
1379
22
  }
1380
22
1381
22
  Stmt *Replacement = SynthMessageExpr(NewMsg);
1382
22
  ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1383
22
  return Replacement;
1384
22
}
1385
1386
/// SynthCountByEnumWithState - To print:
1387
/// ((unsigned int (*)
1388
///  (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1389
///  (void *)objc_msgSend)((id)l_collection,
1390
///                        sel_registerName(
1391
///                          "countByEnumeratingWithState:objects:count:"),
1392
///                        &enumState,
1393
///                        (id *)__rw_items, (unsigned int)16)
1394
///
1395
36
void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
1396
36
  buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1397
36
  "id *, unsigned int))(void *)objc_msgSend)";
1398
36
  buf += "\n\t\t";
1399
36
  buf += "((id)l_collection,\n\t\t";
1400
36
  buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1401
36
  buf += "\n\t\t";
1402
36
  buf += "&enumState, "
1403
36
         "(id *)__rw_items, (unsigned int)16)";
1404
36
}
1405
1406
/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1407
/// statement to exit to its outer synthesized loop.
1408
///
1409
6
Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
1410
6
  if (
Stmts.empty() || 6
!isa<ObjCForCollectionStmt>(Stmts.back())6
)
1411
4
    return S;
1412
2
  // replace break with goto __break_label
1413
2
  std::string buf;
1414
2
1415
2
  SourceLocation startLoc = S->getLocStart();
1416
2
  buf = "goto __break_label_";
1417
2
  buf += utostr(ObjCBcLabelNo.back());
1418
2
  ReplaceText(startLoc, strlen("break"), buf);
1419
2
1420
2
  return nullptr;
1421
2
}
1422
1423
/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1424
/// statement to continue with its inner synthesized loop.
1425
///
1426
2
Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
1427
2
  if (
Stmts.empty() || 2
!isa<ObjCForCollectionStmt>(Stmts.back())2
)
1428
0
    return S;
1429
2
  // replace continue with goto __continue_label
1430
2
  std::string buf;
1431
2
1432
2
  SourceLocation startLoc = S->getLocStart();
1433
2
  buf = "goto __continue_label_";
1434
2
  buf += utostr(ObjCBcLabelNo.back());
1435
2
  ReplaceText(startLoc, strlen("continue"), buf);
1436
2
1437
2
  return nullptr;
1438
2
}
1439
1440
/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1441
///  It rewrites:
1442
/// for ( type elem in collection) { stmts; }
1443
1444
/// Into:
1445
/// {
1446
///   type elem;
1447
///   struct __objcFastEnumerationState enumState = { 0 };
1448
///   id __rw_items[16];
1449
///   id l_collection = (id)collection;
1450
///   unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1451
///                                       objects:__rw_items count:16];
1452
/// if (limit) {
1453
///   unsigned long startMutations = *enumState.mutationsPtr;
1454
///   do {
1455
///        unsigned long counter = 0;
1456
///        do {
1457
///             if (startMutations != *enumState.mutationsPtr)
1458
///               objc_enumerationMutation(l_collection);
1459
///             elem = (type)enumState.itemsPtr[counter++];
1460
///             stmts;
1461
///             __continue_label: ;
1462
///        } while (counter < limit);
1463
///   } while (limit = [l_collection countByEnumeratingWithState:&enumState
1464
///                                  objects:__rw_items count:16]);
1465
///   elem = nil;
1466
///   __break_label: ;
1467
///  }
1468
///  else
1469
///       elem = nil;
1470
///  }
1471
///
1472
Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1473
18
                                                SourceLocation OrigEnd) {
1474
18
  assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1475
18
  assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1476
18
         "ObjCForCollectionStmt Statement stack mismatch");
1477
18
  assert(!ObjCBcLabelNo.empty() &&
1478
18
         "ObjCForCollectionStmt - Label No stack empty");
1479
18
1480
18
  SourceLocation startLoc = S->getLocStart();
1481
18
  const char *startBuf = SM->getCharacterData(startLoc);
1482
18
  StringRef elementName;
1483
18
  std::string elementTypeAsString;
1484
18
  std::string buf;
1485
18
  buf = "\n{\n\t";
1486
18
  if (DeclStmt *
DS18
= dyn_cast<DeclStmt>(S->getElement())) {
1487
9
    // type elem;
1488
9
    NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1489
9
    QualType ElementType = cast<ValueDecl>(D)->getType();
1490
9
    if (ElementType->isObjCQualifiedIdType() ||
1491
8
        ElementType->isObjCQualifiedInterfaceType())
1492
9
      // Simply use 'id' for all qualified types.
1493
1
      elementTypeAsString = "id";
1494
9
    else
1495
8
      elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1496
9
    buf += elementTypeAsString;
1497
9
    buf += " ";
1498
9
    elementName = D->getName();
1499
9
    buf += elementName;
1500
9
    buf += ";\n\t";
1501
9
  }
1502
9
  else {
1503
9
    DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1504
9
    elementName = DR->getDecl()->getName();
1505
9
    ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1506
9
    if (VD->getType()->isObjCQualifiedIdType() ||
1507
9
        VD->getType()->isObjCQualifiedInterfaceType())
1508
9
      // Simply use 'id' for all qualified types.
1509
0
      elementTypeAsString = "id";
1510
9
    else
1511
9
      elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1512
9
  }
1513
18
1514
18
  // struct __objcFastEnumerationState enumState = { 0 };
1515
18
  buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1516
18
  // id __rw_items[16];
1517
18
  buf += "id __rw_items[16];\n\t";
1518
18
  // id l_collection = (id)
1519
18
  buf += "id l_collection = (id)";
1520
18
  // Find start location of 'collection' the hard way!
1521
18
  const char *startCollectionBuf = startBuf;
1522
18
  startCollectionBuf += 3;  // skip 'for'
1523
18
  startCollectionBuf = strchr(startCollectionBuf, '(');
1524
18
  startCollectionBuf++; // skip '('
1525
18
  // find 'in' and skip it.
1526
151
  while (*startCollectionBuf != ' ' ||
1527
151
         
*(startCollectionBuf+1) != 'i'29
||
*(startCollectionBuf+2) != 'n'18
||
1528
18
         (*(startCollectionBuf+3) != ' ' &&
1529
151
          
*(startCollectionBuf+3) != '['3
&&
*(startCollectionBuf+3) != '('1
))
1530
133
    startCollectionBuf++;
1531
18
  startCollectionBuf += 3;
1532
18
1533
18
  // Replace: "for (type element in" with string constructed thus far.
1534
18
  ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1535
18
  // Replace ')' in for '(' type elem in collection ')' with ';'
1536
18
  SourceLocation rightParenLoc = S->getRParenLoc();
1537
18
  const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1538
18
  SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1539
18
  buf = ";\n\t";
1540
18
1541
18
  // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1542
18
  //                                   objects:__rw_items count:16];
1543
18
  // which is synthesized into:
1544
18
  // unsigned int limit =
1545
18
  // ((unsigned int (*)
1546
18
  //  (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1547
18
  //  (void *)objc_msgSend)((id)l_collection,
1548
18
  //                        sel_registerName(
1549
18
  //                          "countByEnumeratingWithState:objects:count:"),
1550
18
  //                        (struct __objcFastEnumerationState *)&state,
1551
18
  //                        (id *)__rw_items, (unsigned int)16);
1552
18
  buf += "unsigned long limit =\n\t\t";
1553
18
  SynthCountByEnumWithState(buf);
1554
18
  buf += ";\n\t";
1555
18
  /// if (limit) {
1556
18
  ///   unsigned long startMutations = *enumState.mutationsPtr;
1557
18
  ///   do {
1558
18
  ///        unsigned long counter = 0;
1559
18
  ///        do {
1560
18
  ///             if (startMutations != *enumState.mutationsPtr)
1561
18
  ///               objc_enumerationMutation(l_collection);
1562
18
  ///             elem = (type)enumState.itemsPtr[counter++];
1563
18
  buf += "if (limit) {\n\t";
1564
18
  buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1565
18
  buf += "do {\n\t\t";
1566
18
  buf += "unsigned long counter = 0;\n\t\t";
1567
18
  buf += "do {\n\t\t\t";
1568
18
  buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1569
18
  buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1570
18
  buf += elementName;
1571
18
  buf += " = (";
1572
18
  buf += elementTypeAsString;
1573
18
  buf += ")enumState.itemsPtr[counter++];";
1574
18
  // Replace ')' in for '(' type elem in collection ')' with all of these.
1575
18
  ReplaceText(lparenLoc, 1, buf);
1576
18
1577
18
  ///            __continue_label: ;
1578
18
  ///        } while (counter < limit);
1579
18
  ///   } while (limit = [l_collection countByEnumeratingWithState:&enumState
1580
18
  ///                                  objects:__rw_items count:16]);
1581
18
  ///   elem = nil;
1582
18
  ///   __break_label: ;
1583
18
  ///  }
1584
18
  ///  else
1585
18
  ///       elem = nil;
1586
18
  ///  }
1587
18
  ///
1588
18
  buf = ";\n\t";
1589
18
  buf += "__continue_label_";
1590
18
  buf += utostr(ObjCBcLabelNo.back());
1591
18
  buf += ": ;";
1592
18
  buf += "\n\t\t";
1593
18
  buf += "} while (counter < limit);\n\t";
1594
18
  buf += "} while (limit = ";
1595
18
  SynthCountByEnumWithState(buf);
1596
18
  buf += ");\n\t";
1597
18
  buf += elementName;
1598
18
  buf += " = ((";
1599
18
  buf += elementTypeAsString;
1600
18
  buf += ")0);\n\t";
1601
18
  buf += "__break_label_";
1602
18
  buf += utostr(ObjCBcLabelNo.back());
1603
18
  buf += ": ;\n\t";
1604
18
  buf += "}\n\t";
1605
18
  buf += "else\n\t\t";
1606
18
  buf += elementName;
1607
18
  buf += " = ((";
1608
18
  buf += elementTypeAsString;
1609
18
  buf += ")0);\n\t";
1610
18
  buf += "}\n";
1611
18
1612
18
  // Insert all these *after* the statement body.
1613
18
  // FIXME: If this should support Obj-C++, support CXXTryStmt
1614
18
  if (
isa<CompoundStmt>(S->getBody())18
) {
1615
12
    SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1616
12
    InsertText(endBodyLoc, buf);
1617
18
  } else {
1618
6
    /* Need to treat single statements specially. For example:
1619
6
     *
1620
6
     *     for (A *a in b) if (stuff()) break;
1621
6
     *     for (A *a in b) xxxyy;
1622
6
     *
1623
6
     * The following code simply scans ahead to the semi to find the actual end.
1624
6
     */
1625
6
    const char *stmtBuf = SM->getCharacterData(OrigEnd);
1626
6
    const char *semiBuf = strchr(stmtBuf, ';');
1627
6
    assert(semiBuf && "Can't find ';'");
1628
6
    SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1629
6
    InsertText(endBodyLoc, buf);
1630
6
  }
1631
18
  Stmts.pop_back();
1632
18
  ObjCBcLabelNo.pop_back();
1633
18
  return nullptr;
1634
18
}
1635
1636
/// RewriteObjCSynchronizedStmt -
1637
/// This routine rewrites @synchronized(expr) stmt;
1638
/// into:
1639
/// objc_sync_enter(expr);
1640
/// @try stmt @finally { objc_sync_exit(expr); }
1641
///
1642
3
Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1643
3
  // Get the start location and compute the semi location.
1644
3
  SourceLocation startLoc = S->getLocStart();
1645
3
  const char *startBuf = SM->getCharacterData(startLoc);
1646
3
1647
3
  assert((*startBuf == '@') && "bogus @synchronized location");
1648
3
1649
3
  std::string buf;
1650
3
  buf = "objc_sync_enter((id)";
1651
3
  const char *lparenBuf = startBuf;
1652
45
  while (
*lparenBuf != '('45
)
lparenBuf++42
;
1653
3
  ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
1654
3
  // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1655
3
  // the sync expression is typically a message expression that's already
1656
3
  // been rewritten! (which implies the SourceLocation's are invalid).
1657
3
  SourceLocation endLoc = S->getSynchBody()->getLocStart();
1658
3
  const char *endBuf = SM->getCharacterData(endLoc);
1659
9
  while (
*endBuf != ')'9
)
endBuf--6
;
1660
3
  SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
1661
3
  buf = ");\n";
1662
3
  // declare a new scope with two variables, _stack and _rethrow.
1663
3
  buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1664
3
  buf += "int buf[18/*32-bit i386*/];\n";
1665
3
  buf += "char *pointers[4];} _stack;\n";
1666
3
  buf += "id volatile _rethrow = 0;\n";
1667
3
  buf += "objc_exception_try_enter(&_stack);\n";
1668
3
  buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
1669
3
  ReplaceText(rparenLoc, 1, buf);
1670
3
  startLoc = S->getSynchBody()->getLocEnd();
1671
3
  startBuf = SM->getCharacterData(startLoc);
1672
3
1673
3
  assert((*startBuf == '}') && "bogus @synchronized block");
1674
3
  SourceLocation lastCurlyLoc = startLoc;
1675
3
  buf = "}\nelse {\n";
1676
3
  buf += "  _rethrow = objc_exception_extract(&_stack);\n";
1677
3
  buf += "}\n";
1678
3
  buf += "{ /* implicit finally clause */\n";
1679
3
  buf += "  if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1680
3
  
1681
3
  std::string syncBuf;
1682
3
  syncBuf += " objc_sync_exit(";
1683
3
1684
3
  Expr *syncExpr = S->getSynchExpr();
1685
3
  CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1686
3
                  ? CK_BitCast :
1687
0
                syncExpr->getType()->isBlockPointerType()
1688
0
                  ? CK_BlockPointerToObjCPointerCast
1689
0
                  : CK_CPointerToObjCPointerCast;
1690
3
  syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1691
3
                                      CK, syncExpr);
1692
3
  std::string syncExprBufS;
1693
3
  llvm::raw_string_ostream syncExprBuf(syncExprBufS);
1694
3
  assert(syncExpr != nullptr && "Expected non-null Expr");
1695
3
  syncExpr->printPretty(syncExprBuf, nullptr, PrintingPolicy(LangOpts));
1696
3
  syncBuf += syncExprBuf.str();
1697
3
  syncBuf += ");";
1698
3
  
1699
3
  buf += syncBuf;
1700
3
  buf += "\n  if (_rethrow) objc_exception_throw(_rethrow);\n";
1701
3
  buf += "}\n";
1702
3
  buf += "}";
1703
3
1704
3
  ReplaceText(lastCurlyLoc, 1, buf);
1705
3
1706
3
  bool hasReturns = false;
1707
3
  HasReturnStmts(S->getSynchBody(), hasReturns);
1708
3
  if (hasReturns)
1709
3
    RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1710
3
1711
3
  return nullptr;
1712
3
}
1713
1714
void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1715
26
{
1716
26
  // Perform a bottom up traversal of all children.
1717
26
  for (Stmt *SubStmt : S->children())
1718
22
    
if (22
SubStmt22
)
1719
22
      WarnAboutReturnGotoStmts(SubStmt);
1720
26
1721
26
  if (
isa<ReturnStmt>(S) || 26
isa<GotoStmt>(S)25
) {
1722
1
    Diags.Report(Context->getFullLoc(S->getLocStart()),
1723
1
                 TryFinallyContainsReturnDiag);
1724
1
  }
1725
26
}
1726
1727
void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns) 
1728
23
{  
1729
23
  // Perform a bottom up traversal of all children.
1730
23
  for (Stmt *SubStmt : S->children())
1731
16
    
if (16
SubStmt16
)
1732
16
      HasReturnStmts(SubStmt, hasReturns);
1733
23
1734
23
  if (isa<ReturnStmt>(S))
1735
4
    hasReturns = true;
1736
23
}
1737
1738
2
void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1739
2
  // Perform a bottom up traversal of all children.
1740
2
  for (Stmt *SubStmt : S->children())
1741
1
    
if (1
SubStmt1
) {
1742
1
      RewriteTryReturnStmts(SubStmt);
1743
1
    }
1744
2
  if (
isa<ReturnStmt>(S)2
) {
1745
1
    SourceLocation startLoc = S->getLocStart();
1746
1
    const char *startBuf = SM->getCharacterData(startLoc);
1747
1
    const char *semiBuf = strchr(startBuf, ';');
1748
1
    assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1749
1
    SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
1750
1
1751
1
    std::string buf;
1752
1
    buf = "{ objc_exception_try_exit(&_stack); return";
1753
1
   
1754
1
    ReplaceText(startLoc, 6, buf);
1755
1
    InsertText(onePastSemiLoc, "}");
1756
1
  }
1757
2
}
1758
1759
12
void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1760
12
  // Perform a bottom up traversal of all children.
1761
12
  for (Stmt *SubStmt : S->children())
1762
9
    
if (9
SubStmt9
) {
1763
9
      RewriteSyncReturnStmts(SubStmt, syncExitBuf);
1764
9
    }
1765
12
  if (
isa<ReturnStmt>(S)12
) {
1766
3
    SourceLocation startLoc = S->getLocStart();
1767
3
    const char *startBuf = SM->getCharacterData(startLoc);
1768
3
1769
3
    const char *semiBuf = strchr(startBuf, ';');
1770
3
    assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1771
3
    SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
1772
3
1773
3
    std::string buf;
1774
3
    buf = "{ objc_exception_try_exit(&_stack);";
1775
3
    buf += syncExitBuf;
1776
3
    buf += " return";
1777
3
    
1778
3
    ReplaceText(startLoc, 6, buf);
1779
3
    InsertText(onePastSemiLoc, "}");
1780
3
  }
1781
12
}
1782
1783
8
Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
1784
8
  // Get the start location and compute the semi location.
1785
8
  SourceLocation startLoc = S->getLocStart();
1786
8
  const char *startBuf = SM->getCharacterData(startLoc);
1787
8
1788
8
  assert((*startBuf == '@') && "bogus @try location");
1789
8
1790
8
  std::string buf;
1791
8
  // declare a new scope with two variables, _stack and _rethrow.
1792
8
  buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1793
8
  buf += "int buf[18/*32-bit i386*/];\n";
1794
8
  buf += "char *pointers[4];} _stack;\n";
1795
8
  buf += "id volatile _rethrow = 0;\n";
1796
8
  buf += "objc_exception_try_enter(&_stack);\n";
1797
8
  buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
1798
8
1799
8
  ReplaceText(startLoc, 4, buf);
1800
8
1801
8
  startLoc = S->getTryBody()->getLocEnd();
1802
8
  startBuf = SM->getCharacterData(startLoc);
1803
8
1804
8
  assert((*startBuf == '}') && "bogus @try block");
1805
8
1806
8
  SourceLocation lastCurlyLoc = startLoc;
1807
8
  if (
S->getNumCatchStmts()8
) {
1808
4
    startLoc = startLoc.getLocWithOffset(1);
1809
4
    buf = " /* @catch begin */ else {\n";
1810
4
    buf += " id _caught = objc_exception_extract(&_stack);\n";
1811
4
    buf += " objc_exception_try_enter (&_stack);\n";
1812
4
    buf += " if (_setjmp(_stack.buf))\n";
1813
4
    buf += "   _rethrow = objc_exception_extract(&_stack);\n";
1814
4
    buf += " else { /* @catch continue */";
1815
4
1816
4
    InsertText(startLoc, buf);
1817
8
  } else { /* no catch list */
1818
4
    buf = "}\nelse {\n";
1819
4
    buf += "  _rethrow = objc_exception_extract(&_stack);\n";
1820
4
    buf += "}";
1821
4
    ReplaceText(lastCurlyLoc, 1, buf);
1822
4
  }
1823
8
  Stmt *lastCatchBody = nullptr;
1824
14
  for (unsigned I = 0, N = S->getNumCatchStmts(); 
I != N14
;
++I6
) {
1825
6
    ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
1826
6
    VarDecl *catchDecl = Catch->getCatchParamDecl();
1827
6
1828
6
    if (I == 0)
1829
4
      buf = "if ("; // we are generating code for the first catch clause
1830
6
    else
1831
2
      buf = "else if (";
1832
6
    startLoc = Catch->getLocStart();
1833
6
    startBuf = SM->getCharacterData(startLoc);
1834
6
1835
6
    assert((*startBuf == '@') && "bogus @catch location");
1836
6
1837
6
    const char *lParenLoc = strchr(startBuf, '(');
1838
6
1839
6
    if (
Catch->hasEllipsis()6
) {
1840
2
      // Now rewrite the body...
1841
2
      lastCatchBody = Catch->getCatchBody();
1842
2
      SourceLocation bodyLoc = lastCatchBody->getLocStart();
1843
2
      const char *bodyBuf = SM->getCharacterData(bodyLoc);
1844
2
      assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
1845
2
             "bogus @catch paren location");
1846
2
      assert((*bodyBuf == '{') && "bogus @catch body location");
1847
2
1848
2
      buf += "1) { id _tmp = _caught;";
1849
2
      Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
1850
6
    } else 
if (4
catchDecl4
) {
1851
4
      QualType t = catchDecl->getType();
1852
4
      if (
t == Context->getObjCIdType()4
) {
1853
1
        buf += "1) { ";
1854
1
        ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
1855
4
      } else 
if (const ObjCObjectPointerType *3
Ptr3
=
1856
3
                   t->getAs<ObjCObjectPointerType>()) {
1857
3
        // Should be a pointer to a class.
1858
3
        ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1859
3
        if (
IDecl3
) {
1860
3
          buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
1861
3
          buf += IDecl->getNameAsString();
1862
3
          buf += "\"), (struct objc_object *)_caught)) { ";
1863
3
          ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
1864
3
        }
1865
3
      }
1866
4
      // Now rewrite the body...
1867
4
      lastCatchBody = Catch->getCatchBody();
1868
4
      SourceLocation rParenLoc = Catch->getRParenLoc();
1869
4
      SourceLocation bodyLoc = lastCatchBody->getLocStart();
1870
4
      const char *bodyBuf = SM->getCharacterData(bodyLoc);
1871
4
      const char *rParenBuf = SM->getCharacterData(rParenLoc);
1872
4
      assert((*rParenBuf == ')') && "bogus @catch paren location");
1873
4
      assert((*bodyBuf == '{') && "bogus @catch body location");
1874
4
1875
4
      // Here we replace ") {" with "= _caught;" (which initializes and
1876
4
      // declares the @catch parameter).
1877
4
      ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
1878
0
    } else {
1879
0
      llvm_unreachable("@catch rewrite bug");
1880
4
    }
1881
6
  }
1882
8
  // Complete the catch list...
1883
8
  
if (8
lastCatchBody8
) {
1884
4
    SourceLocation bodyLoc = lastCatchBody->getLocEnd();
1885
4
    assert(*SM->getCharacterData(bodyLoc) == '}' &&
1886
4
           "bogus @catch body location");
1887
4
1888
4
    // Insert the last (implicit) else clause *before* the right curly brace.
1889
4
    bodyLoc = bodyLoc.getLocWithOffset(-1);
1890
4
    buf = "} /* last catch end */\n";
1891
4
    buf += "else {\n";
1892
4
    buf += " _rethrow = _caught;\n";
1893
4
    buf += " objc_exception_try_exit(&_stack);\n";
1894
4
    buf += "} } /* @catch end */\n";
1895
4
    if (!S->getFinallyStmt())
1896
4
      buf += "}\n";
1897
4
    InsertText(bodyLoc, buf);
1898
4
1899
4
    // Set lastCurlyLoc
1900
4
    lastCurlyLoc = lastCatchBody->getLocEnd();
1901
4
  }
1902
8
  if (ObjCAtFinallyStmt *
finalStmt8
= S->getFinallyStmt()) {
1903
4
    startLoc = finalStmt->getLocStart();
1904
4
    startBuf = SM->getCharacterData(startLoc);
1905
4
    assert((*startBuf == '@') && "bogus @finally start");
1906
4
1907
4
    ReplaceText(startLoc, 8, "/* @finally */");
1908
4
1909
4
    Stmt *body = finalStmt->getFinallyBody();
1910
4
    SourceLocation startLoc = body->getLocStart();
1911
4
    SourceLocation endLoc = body->getLocEnd();
1912
4
    assert(*SM->getCharacterData(startLoc) == '{' &&
1913
4
           "bogus @finally body location");
1914
4
    assert(*SM->getCharacterData(endLoc) == '}' &&
1915
4
           "bogus @finally body location");
1916
4
1917
4
    startLoc = startLoc.getLocWithOffset(1);
1918
4
    InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
1919
4
    endLoc = endLoc.getLocWithOffset(-1);
1920
4
    InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
1921
4
1922
4
    // Set lastCurlyLoc
1923
4
    lastCurlyLoc = body->getLocEnd();
1924
4
1925
4
    // Now check for any return/continue/go statements within the @try.
1926
4
    WarnAboutReturnGotoStmts(S->getTryBody());
1927
8
  } else { /* no finally clause - make sure we synthesize an implicit one */
1928
4
    buf = "{ /* implicit finally clause */\n";
1929
4
    buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1930
4
    buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1931
4
    buf += "}";
1932
4
    ReplaceText(lastCurlyLoc, 1, buf);
1933
4
    
1934
4
    // Now check for any return/continue/go statements within the @try.
1935
4
    // The implicit finally clause won't called if the @try contains any
1936
4
    // jump statements.
1937
4
    bool hasReturns = false;
1938
4
    HasReturnStmts(S->getTryBody(), hasReturns);
1939
4
    if (hasReturns)
1940
1
      RewriteTryReturnStmts(S->getTryBody());
1941
4
  }
1942
8
  // Now emit the final closing curly brace...
1943
8
  lastCurlyLoc = lastCurlyLoc.getLocWithOffset(1);
1944
8
  InsertText(lastCurlyLoc, " } /* @try scope end */\n");
1945
8
  return nullptr;
1946
8
}
1947
1948
// This can't be done with ReplaceStmt(S, ThrowExpr), since
1949
// the throw expression is typically a message expression that's already
1950
// been rewritten! (which implies the SourceLocation's are invalid).
1951
2
Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
1952
2
  // Get the start location and compute the semi location.
1953
2
  SourceLocation startLoc = S->getLocStart();
1954
2
  const char *startBuf = SM->getCharacterData(startLoc);
1955
2
1956
2
  assert((*startBuf == '@') && "bogus @throw location");
1957
2
1958
2
  std::string buf;
1959
2
  /* void objc_exception_throw(id) __attribute__((noreturn)); */
1960
2
  if (S->getThrowExpr())
1961
0
    buf = "objc_exception_throw(";
1962
2
  else // add an implicit argument
1963
2
    buf = "objc_exception_throw(_caught";
1964
2
1965
2
  // handle "@  throw" correctly.
1966
2
  const char *wBuf = strchr(startBuf, 'w');
1967
2
  assert((*wBuf == 'w') && "@throw: can't find 'w'");
1968
2
  ReplaceText(startLoc, wBuf-startBuf+1, buf);
1969
2
1970
2
  const char *semiBuf = strchr(startBuf, ';');
1971
2
  assert((*semiBuf == ';') && "@throw: can't find ';'");
1972
2
  SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
1973
2
  ReplaceText(semiLoc, 1, ");");
1974
2
  return nullptr;
1975
2
}
1976
1977
3
Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
1978
3
  // Create a new string expression.
1979
3
  std::string StrEncoding;
1980
3
  Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
1981
3
  Expr *Replacement = getStringLiteral(StrEncoding);
1982
3
  ReplaceStmt(Exp, Replacement);
1983
3
1984
3
  // Replace this subexpr in the parent.
1985
3
  // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1986
3
  return Replacement;
1987
3
}
1988
1989
1
Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1990
1
  if (!SelGetUidFunctionDecl)
1991
1
    SynthSelGetUidFunctionDecl();
1992
1
  assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1993
1
  // Create a call to sel_registerName("selName").
1994
1
  SmallVector<Expr*, 8> SelExprs;
1995
1
  SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
1996
1
  CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1997
1
                                                  SelExprs);
1998
1
  ReplaceStmt(Exp, SelExp);
1999
1
  // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2000
1
  return SelExp;
2001
1
}
2002
2003
CallExpr *
2004
RewriteObjC::SynthesizeCallToFunctionDecl(FunctionDecl *FD,
2005
                                          ArrayRef<Expr *> Args,
2006
                                          SourceLocation StartLoc,
2007
139
                                          SourceLocation EndLoc) {
2008
139
  // Get the type, we will need to reference it in a couple spots.
2009
139
  QualType msgSendType = FD->getType();
2010
139
2011
139
  // Create a reference to the objc_msgSend() declaration.
2012
139
  DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, msgSendType,
2013
139
                                               VK_LValue, SourceLocation());
2014
139
2015
139
  // Now, we cast the reference to a pointer to the objc_msgSend type.
2016
139
  QualType pToFunc = Context->getPointerType(msgSendType);
2017
139
  ImplicitCastExpr *ICE =
2018
139
    ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2019
139
                             DRE, nullptr, VK_RValue);
2020
139
2021
139
  const FunctionType *FT = msgSendType->getAs<FunctionType>();
2022
139
2023
139
  CallExpr *Exp = new (Context) CallExpr(*Context, ICE, Args,
2024
139
                                         FT->getCallResultType(*Context),
2025
139
                                         VK_RValue, EndLoc);
2026
139
  return Exp;
2027
139
}
2028
2029
static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2030
26
                                const char *&startRef, const char *&endRef) {
2031
360
  while (
startBuf < endBuf360
) {
2032
360
    if (*startBuf == '<')
2033
26
      startRef = startBuf; // mark the start.
2034
360
    if (
*startBuf == '>'360
) {
2035
26
      if (
startRef && 26
*startRef == '<'26
) {
2036
26
        endRef = startBuf; // mark the end.
2037
26
        return true;
2038
26
      }
2039
0
      return false;
2040
0
    }
2041
334
    startBuf++;
2042
334
  }
2043
0
  return false;
2044
26
}
2045
2046
6
static void scanToNextArgument(const char *&argRef) {
2047
6
  int angle = 0;
2048
147
  while (
*argRef != ')' && 147
(*argRef != ',' || 144
angle > 05
)) {
2049
141
    if (*argRef == '<')
2050
6
      angle++;
2051
135
    else 
if (135
*argRef == '>'135
)
2052
6
      angle--;
2053
141
    argRef++;
2054
141
  }
2055
6
  assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2056
6
}
2057
2058
371
bool RewriteObjC::needToScanForQualifiers(QualType T) {
2059
371
  if (T->isObjCQualifiedIdType())
2060
9
    return true;
2061
362
  
if (const PointerType *362
PT362
= T->getAs<PointerType>()) {
2062
37
    if (PT->getPointeeType()->isObjCQualifiedIdType())
2063
1
      return true;
2064
361
  }
2065
361
  
if (361
T->isObjCObjectPointerType()361
) {
2066
113
    T = T->getPointeeType();
2067
113
    return T->isObjCQualifiedInterfaceType();
2068
113
  }
2069
248
  
if (248
T->isArrayType()248
) {
2070
3
    QualType ElemTy = Context->getBaseElementType(T);
2071
3
    return needToScanForQualifiers(ElemTy);
2072
3
  }
2073
245
  return false;
2074
245
}
2075
2076
31
void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2077
31
  QualType Type = E->getType();
2078
31
  if (
needToScanForQualifiers(Type)31
) {
2079
7
    SourceLocation Loc, EndLoc;
2080
7
2081
7
    if (const CStyleCastExpr *
ECE7
= dyn_cast<CStyleCastExpr>(E)) {
2082
7
      Loc = ECE->getLParenLoc();
2083
7
      EndLoc = ECE->getRParenLoc();
2084
7
    } else {
2085
0
      Loc = E->getLocStart();
2086
0
      EndLoc = E->getLocEnd();
2087
0
    }
2088
7
    // This will defend against trying to rewrite synthesized expressions.
2089
7
    if (
Loc.isInvalid() || 7
EndLoc.isInvalid()7
)
2090
0
      return;
2091
7
2092
7
    const char *startBuf = SM->getCharacterData(Loc);
2093
7
    const char *endBuf = SM->getCharacterData(EndLoc);
2094
7
    const char *startRef = nullptr, *endRef = nullptr;
2095
7
    if (
scanForProtocolRefs(startBuf, endBuf, startRef, endRef)7
) {
2096
7
      // Get the locations of the startRef, endRef.
2097
7
      SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2098
7
      SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2099
7
      // Comment out the protocol references.
2100
7
      InsertText(LessLoc, "/*");
2101
7
      InsertText(GreaterLoc, "*/");
2102
7
    }
2103
7
  }
2104
31
}
2105
2106
265
void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2107
265
  SourceLocation Loc;
2108
265
  QualType Type;
2109
265
  const FunctionProtoType *proto = nullptr;
2110
265
  if (VarDecl *
VD265
= dyn_cast<VarDecl>(Dcl)) {
2111
149
    Loc = VD->getLocation();
2112
149
    Type = VD->getType();
2113
149
  }
2114
116
  else 
if (FunctionDecl *116
FD116
= dyn_cast<FunctionDecl>(Dcl)) {
2115
115
    Loc = FD->getLocation();
2116
115
    // Check for ObjC 'id' and class types that have been adorned with protocol
2117
115
    // information (id<p>, C<p>*). The protocol references need to be rewritten!
2118
115
    const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2119
115
    assert(funcType && "missing function type");
2120
115
    proto = dyn_cast<FunctionProtoType>(funcType);
2121
115
    if (!proto)
2122
23
      return;
2123
92
    Type = proto->getReturnType();
2124
92
  }
2125
1
  else 
if (FieldDecl *1
FD1
= dyn_cast<FieldDecl>(Dcl)) {
2126
1
    Loc = FD->getLocation();
2127
1
    Type = FD->getType();
2128
1
  }
2129
1
  else
2130
0
    return;
2131
242
2132
242
  
if (242
needToScanForQualifiers(Type)242
) {
2133
13
    // Since types are unique, we need to scan the buffer.
2134
13
2135
13
    const char *endBuf = SM->getCharacterData(Loc);
2136
13
    const char *startBuf = endBuf;
2137
217
    while (
*startBuf != ';' && 217
*startBuf != '<'217
&&
startBuf != MainFileStart204
)
2138
204
      startBuf--; // scan backward (from the decl location) for return type.
2139
13
    const char *startRef = nullptr, *endRef = nullptr;
2140
13
    if (
scanForProtocolRefs(startBuf, endBuf, startRef, endRef)13
) {
2141
13
      // Get the locations of the startRef, endRef.
2142
13
      SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2143
13
      SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2144
13
      // Comment out the protocol references.
2145
13
      InsertText(LessLoc, "/*");
2146
13
      InsertText(GreaterLoc, "*/");
2147
13
    }
2148
13
  }
2149
242
  if (!proto)
2150
150
      return; // most likely, was a variable
2151
92
  // Now check arguments.
2152
92
  const char *startBuf = SM->getCharacterData(Loc);
2153
92
  const char *startFuncBuf = startBuf;
2154
172
  for (unsigned i = 0; 
i < proto->getNumParams()172
;
i++80
) {
2155
80
    if (
needToScanForQualifiers(proto->getParamType(i))80
) {
2156
6
      // Since types are unique, we need to scan the buffer.
2157
6
2158
6
      const char *endBuf = startBuf;
2159
6
      // scan forward (from the decl location) for argument types.
2160
6
      scanToNextArgument(endBuf);
2161
6
      const char *startRef = nullptr, *endRef = nullptr;
2162
6
      if (
scanForProtocolRefs(startBuf, endBuf, startRef, endRef)6
) {
2163
6
        // Get the locations of the startRef, endRef.
2164
6
        SourceLocation LessLoc =
2165
6
          Loc.getLocWithOffset(startRef-startFuncBuf);
2166
6
        SourceLocation GreaterLoc =
2167
6
          Loc.getLocWithOffset(endRef-startFuncBuf+1);
2168
6
        // Comment out the protocol references.
2169
6
        InsertText(LessLoc, "/*");
2170
6
        InsertText(GreaterLoc, "*/");
2171
6
      }
2172
6
      startBuf = ++endBuf;
2173
6
    }
2174
74
    else {
2175
74
      // If the function name is derived from a macro expansion, then the
2176
74
      // argument buffer will not follow the name. Need to speak with Chris.
2177
1.26k
      while (
*startBuf && 1.26k
*startBuf != ')'1.26k
&&
*startBuf != ','1.20k
)
2178
1.18k
        startBuf++; // scan forward (from the decl location) for argument types.
2179
74
      startBuf++;
2180
74
    }
2181
80
  }
2182
265
}
2183
2184
119
void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2185
119
  QualType QT = ND->getType();
2186
119
  const Type* TypePtr = QT->getAs<Type>();
2187
119
  if (!isa<TypeOfExprType>(TypePtr))
2188
116
    return;
2189
9
  
while (3
isa<TypeOfExprType>(TypePtr)9
) {
2190
6
    const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2191
6
    QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2192
6
    TypePtr = QT->getAs<Type>();
2193
6
  }
2194
3
  // FIXME. This will not work for multiple declarators; as in:
2195
3
  // __typeof__(a) b,c,d;
2196
3
  std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2197
3
  SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2198
3
  const char *startBuf = SM->getCharacterData(DeclLoc);
2199
3
  if (
ND->getInit()3
) {
2200
2
    std::string Name(ND->getNameAsString());
2201
2
    TypeAsString += " " + Name + " = ";
2202
2
    Expr *E = ND->getInit();
2203
2
    SourceLocation startLoc;
2204
2
    if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2205
0
      startLoc = ECE->getLParenLoc();
2206
2
    else
2207
2
      startLoc = E->getLocStart();
2208
2
    startLoc = SM->getExpansionLoc(startLoc);
2209
2
    const char *endBuf = SM->getCharacterData(startLoc);
2210
2
    ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2211
2
  }
2212
1
  else {
2213
1
    SourceLocation X = ND->getLocEnd();
2214
1
    X = SM->getExpansionLoc(X);
2215
1
    const char *endBuf = SM->getCharacterData(X);
2216
1
    ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2217
1
  }
2218
119
}
2219
2220
// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2221
15
void RewriteObjC::SynthSelGetUidFunctionDecl() {
2222
15
  IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2223
15
  SmallVector<QualType, 16> ArgTys;
2224
15
  ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2225
15
  QualType getFuncType =
2226
15
    getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
2227
15
  SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2228
15
                                               SourceLocation(),
2229
15
                                               SourceLocation(),
2230
15
                                               SelGetUidIdent, getFuncType,
2231
15
                                               nullptr, SC_Extern);
2232
15
}
2233
2234
136
void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2235
136
  // declared in <objc/objc.h>
2236
136
  if (FD->getIdentifier() &&
2237
136
      
FD->getName() == "sel_registerName"136
) {
2238
21
    SelGetUidFunctionDecl = FD;
2239
21
    return;
2240
21
  }
2241
115
  RewriteObjCQualifiedInterfaceTypes(FD);
2242
115
}
2243
2244
13
void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2245
13
  std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2246
13
  const char *argPtr = TypeString.c_str();
2247
13
  if (
!strchr(argPtr, '^')13
) {
2248
6
    Str += TypeString;
2249
6
    return;
2250
6
  }
2251
105
  
while (7
*argPtr105
) {
2252
98
    Str += (*argPtr == '^' ? 
'*'7
:
*argPtr91
);
2253
98
    argPtr++;
2254
98
  }
2255
13
}
2256
2257
// FIXME. Consolidate this routine with RewriteBlockPointerType.
2258
void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2259
2
                                                  ValueDecl *VD) {
2260
2
  QualType Type = VD->getType();
2261
2
  std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2262
2
  const char *argPtr = TypeString.c_str();
2263
2
  int paren = 0;
2264
29
  while (
*argPtr29
) {
2265
27
    switch (*argPtr) {
2266
4
      case '(':
2267
4
        Str += *argPtr;
2268
4
        paren++;
2269
4
        break;
2270
4
      case ')':
2271
4
        Str += *argPtr;
2272
4
        paren--;
2273
4
        break;
2274
2
      case '^':
2275
2
        Str += '*';
2276
2
        if (paren == 1)
2277
2
          Str += VD->getNameAsString();
2278
2
        break;
2279
17
      default:
2280
17
        Str += *argPtr;
2281
17
        break;
2282
27
    }
2283
27
    argPtr++;
2284
27
  }
2285
2
}
2286
2287
30
void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2288
30
  SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2289
30
  const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2290
30
  const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2291
30
  if (!proto)
2292
8
    return;
2293
22
  QualType Type = proto->getReturnType();
2294
22
  std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2295
22
  FdStr += " ";
2296
22
  FdStr += FD->getName();
2297
22
  FdStr +=  "(";
2298
22
  unsigned numArgs = proto->getNumParams();
2299
30
  for (unsigned i = 0; 
i < numArgs30
;
i++8
) {
2300
8
    QualType ArgType = proto->getParamType(i);
2301
8
    RewriteBlockPointerType(FdStr, ArgType);
2302
8
    if (i+1 < numArgs)
2303
2
      FdStr += ", ";
2304
8
  }
2305
30
  FdStr +=  ");\n";
2306
30
  InsertText(FunLocStart, FdStr);
2307
30
  CurFunctionDeclToDeclareForBlock = nullptr;
2308
30
}
2309
2310
// SynthSuperConstructorFunctionDecl - id objc_super(id obj, id super);
2311
2
void RewriteObjC::SynthSuperConstructorFunctionDecl() {
2312
2
  if (SuperConstructorFunctionDecl)
2313
1
    return;
2314
1
  IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2315
1
  SmallVector<QualType, 16> ArgTys;
2316
1
  QualType argT = Context->getObjCIdType();
2317
1
  assert(!argT.isNull() && "Can't find 'id' type");
2318
1
  ArgTys.push_back(argT);
2319
1
  ArgTys.push_back(argT);
2320
1
  QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2321
1
                                               ArgTys);
2322
1
  SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2323
1
                                                     SourceLocation(),
2324
1
                                                     SourceLocation(),
2325
1
                                                     msgSendIdent, msgSendType,
2326
1
                                                     nullptr, SC_Extern);
2327
1
}
2328
2329
// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2330
36
void RewriteObjC::SynthMsgSendFunctionDecl() {
2331
36
  IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2332
36
  SmallVector<QualType, 16> ArgTys;
2333
36
  QualType argT = Context->getObjCIdType();
2334
36
  assert(!argT.isNull() && "Can't find 'id' type");
2335
36
  ArgTys.push_back(argT);
2336
36
  argT = Context->getObjCSelType();
2337
36
  assert(!argT.isNull() && "Can't find 'SEL' type");
2338
36
  ArgTys.push_back(argT);
2339
36
  QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2340
36
                                               ArgTys, /*isVariadic=*/true);
2341
36
  MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2342
36
                                             SourceLocation(),
2343
36
                                             SourceLocation(),
2344
36
                                             msgSendIdent, msgSendType,
2345
36
                                             nullptr, SC_Extern);
2346
36
}
2347
2348
// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
2349
36
void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
2350
36
  IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2351
36
  SmallVector<QualType, 16> ArgTys;
2352
36
  RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2353
36
                                      SourceLocation(), SourceLocation(),
2354
36
                                      &Context->Idents.get("objc_super"));
2355
36
  QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2356
36
  assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2357
36
  ArgTys.push_back(argT);
2358
36
  argT = Context->getObjCSelType();
2359
36
  assert(!argT.isNull() && "Can't find 'SEL' type");
2360
36
  ArgTys.push_back(argT);
2361
36
  QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2362
36
                                               ArgTys, /*isVariadic=*/true);
2363
36
  MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2364
36
                                                  SourceLocation(),
2365
36
                                                  SourceLocation(),
2366
36
                                                  msgSendIdent, msgSendType,
2367
36
                                                  nullptr, SC_Extern);
2368
36
}
2369
2370
// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2371
36
void RewriteObjC::SynthMsgSendStretFunctionDecl() {
2372
36
  IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2373
36
  SmallVector<QualType, 16> ArgTys;
2374
36
  QualType argT = Context->getObjCIdType();
2375
36
  assert(!argT.isNull() && "Can't find 'id' type");
2376
36
  ArgTys.push_back(argT);
2377
36
  argT = Context->getObjCSelType();
2378
36
  assert(!argT.isNull() && "Can't find 'SEL' type");
2379
36
  ArgTys.push_back(argT);
2380
36
  QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2381
36
                                               ArgTys, /*isVariadic=*/true);
2382
36
  MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2383
36
                                                  SourceLocation(),
2384
36
                                                  SourceLocation(),
2385
36
                                                  msgSendIdent, msgSendType,
2386
36
                                                  nullptr, SC_Extern);
2387
36
}
2388
2389
// SynthMsgSendSuperStretFunctionDecl -
2390
// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
2391
36
void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
2392
36
  IdentifierInfo *msgSendIdent =
2393
36
    &Context->Idents.get("objc_msgSendSuper_stret");
2394
36
  SmallVector<QualType, 16> ArgTys;
2395
36
  RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2396
36
                                      SourceLocation(), SourceLocation(),
2397
36
                                      &Context->Idents.get("objc_super"));
2398
36
  QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2399
36
  assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2400
36
  ArgTys.push_back(argT);
2401
36
  argT = Context->getObjCSelType();
2402
36
  assert(!argT.isNull() && "Can't find 'SEL' type");
2403
36
  ArgTys.push_back(argT);
2404
36
  QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2405
36
                                               ArgTys, /*isVariadic=*/true);
2406
36
  MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2407
36
                                                       SourceLocation(),
2408
36
                                                       SourceLocation(),
2409
36
                                                       msgSendIdent,
2410
36
                                                       msgSendType, nullptr,
2411
36
                                                       SC_Extern);
2412
36
}
2413
2414
// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2415
36
void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
2416
36
  IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2417
36
  SmallVector<QualType, 16> ArgTys;
2418
36
  QualType argT = Context->getObjCIdType();
2419
36
  assert(!argT.isNull() && "Can't find 'id' type");
2420
36
  ArgTys.push_back(argT);
2421
36
  argT = Context->getObjCSelType();
2422
36
  assert(!argT.isNull() && "Can't find 'SEL' type");
2423
36
  ArgTys.push_back(argT);
2424
36
  QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2425
36
                                               ArgTys, /*isVariadic=*/true);
2426
36
  MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2427
36
                                                  SourceLocation(),
2428
36
                                                  SourceLocation(),
2429
36
                                                  msgSendIdent, msgSendType,
2430
36
                                                  nullptr, SC_Extern);
2431
36
}
2432
2433
// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
2434
36
void RewriteObjC::SynthGetClassFunctionDecl() {
2435
36
  IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2436
36
  SmallVector<QualType, 16> ArgTys;
2437
36
  ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2438
36
  QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2439
36
                                                ArgTys);
2440
36
  GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2441
36
                                              SourceLocation(),
2442
36
                                              SourceLocation(),
2443
36
                                              getClassIdent, getClassType,
2444
36
                                              nullptr, SC_Extern);
2445
36
}
2446
2447
// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2448
36
void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2449
36
  IdentifierInfo *getSuperClassIdent = 
2450
36
    &Context->Idents.get("class_getSuperclass");
2451
36
  SmallVector<QualType, 16> ArgTys;
2452
36
  ArgTys.push_back(Context->getObjCClassType());
2453
36
  QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2454
36
                                                ArgTys);
2455
36
  GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2456
36
                                                   SourceLocation(),
2457
36
                                                   SourceLocation(),
2458
36
                                                   getSuperClassIdent,
2459
36
                                                   getClassType, nullptr,
2460
36
                                                   SC_Extern);
2461
36
}
2462
2463
// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
2464
36
void RewriteObjC::SynthGetMetaClassFunctionDecl() {
2465
36
  IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2466
36
  SmallVector<QualType, 16> ArgTys;
2467
36
  ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2468
36
  QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2469
36
                                                ArgTys);
2470
36
  GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2471
36
                                                  SourceLocation(),
2472
36
                                                  SourceLocation(),
2473
36
                                                  getClassIdent, getClassType,
2474
36
                                                  nullptr, SC_Extern);
2475
36
}
2476
2477
18
Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2478
18
  assert(Exp != nullptr && "Expected non-null ObjCStringLiteral");
2479
18
  QualType strType = getConstantStringStructType();
2480
18
2481
18
  std::string S = "__NSConstantStringImpl_";
2482
18
2483
18
  std::string tmpName = InFileName;
2484
18
  unsigned i;
2485
1.94k
  for (i=0; 
i < tmpName.length()1.94k
;
i++1.93k
) {
2486
1.93k
    char c = tmpName.at(i);
2487
1.93k
    // replace any non-alphanumeric characters with '_'.
2488
1.93k
    if (!isAlphanumeric(c))
2489
304
      tmpName[i] = '_';
2490
1.93k
  }
2491
18
  S += tmpName;
2492
18
  S += "_";
2493
18
  S += utostr(NumObjCStringLiterals++);
2494
18
2495
18
  Preamble += "static __NSConstantStringImpl " + S;
2496
18
  Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2497
18
  Preamble += "0x000007c8,"; // utf8_str
2498
18
  // The pretty printer for StringLiteral handles escape characters properly.
2499
18
  std::string prettyBufS;
2500
18
  llvm::raw_string_ostream prettyBuf(prettyBufS);
2501
18
  Exp->getString()->printPretty(prettyBuf, nullptr, PrintingPolicy(LangOpts));
2502
18
  Preamble += prettyBuf.str();
2503
18
  Preamble += ",";
2504
18
  Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2505
18
2506
18
  VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2507
18
                                   SourceLocation(), &Context->Idents.get(S),
2508
18
                                   strType, nullptr, SC_Static);
2509
18
  DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
2510
18
                                               SourceLocation());
2511
18
  Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2512
18
                                 Context->getPointerType(DRE->getType()),
2513
18
                                           VK_RValue, OK_Ordinary,
2514
18
                                           SourceLocation());
2515
18
  // cast to NSConstantString *
2516
18
  CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2517
18
                                            CK_CPointerToObjCPointerCast, Unop);
2518
18
  ReplaceStmt(Exp, cast);
2519
18
  // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2520
18
  return cast;
2521
18
}
2522
2523
// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
2524
6
QualType RewriteObjC::getSuperStructType() {
2525
6
  if (
!SuperStructDecl6
) {
2526
2
    SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2527
2
                                         SourceLocation(), SourceLocation(),
2528
2
                                         &Context->Idents.get("objc_super"));
2529
2
    QualType FieldTypes[2];
2530
2
2531
2
    // struct objc_object *receiver;
2532
2
    FieldTypes[0] = Context->getObjCIdType();
2533
2
    // struct objc_class *super;
2534
2
    FieldTypes[1] = Context->getObjCClassType();
2535
2
2536
2
    // Create fields
2537
6
    for (unsigned i = 0; 
i < 26
;
++i4
) {
2538
4
      SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2539
4
                                                 SourceLocation(),
2540
4
                                                 SourceLocation(), nullptr,
2541
4
                                                 FieldTypes[i], nullptr,
2542
4
                                                 /*BitWidth=*/nullptr,
2543
4
                                                 /*Mutable=*/false,
2544
4
                                                 ICIS_NoInit));
2545
4
    }
2546
2
2547
2
    SuperStructDecl->completeDefinition();
2548
2
  }
2549
6
  return Context->getTagDeclType(SuperStructDecl);
2550
6
}
2551
2552
18
QualType RewriteObjC::getConstantStringStructType() {
2553
18
  if (
!ConstantStringDecl18
) {
2554
4
    ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2555
4
                                            SourceLocation(), SourceLocation(),
2556
4
                         &Context->Idents.get("__NSConstantStringImpl"));
2557
4
    QualType FieldTypes[4];
2558
4
2559
4
    // struct objc_object *receiver;
2560
4
    FieldTypes[0] = Context->getObjCIdType();
2561
4
    // int flags;
2562
4
    FieldTypes[1] = Context->IntTy;
2563
4
    // char *str;
2564
4
    FieldTypes[2] = Context->getPointerType(Context->CharTy);
2565
4
    // long length;
2566
4
    FieldTypes[3] = Context->LongTy;
2567
4
2568
4
    // Create fields
2569
20
    for (unsigned i = 0; 
i < 420
;
++i16
) {
2570
16
      ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2571
16
                                                    ConstantStringDecl,
2572
16
                                                    SourceLocation(),
2573
16
                                                    SourceLocation(), nullptr,
2574
16
                                                    FieldTypes[i], nullptr,
2575
16
                                                    /*BitWidth=*/nullptr,
2576
16
                                                    /*Mutable=*/true,
2577
16
                                                    ICIS_NoInit));
2578
16
    }
2579
4
2580
4
    ConstantStringDecl->completeDefinition();
2581
4
  }
2582
18
  return Context->getTagDeclType(ConstantStringDecl);
2583
18
}
2584
2585
CallExpr *RewriteObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
2586
                                                QualType msgSendType, 
2587
                                                QualType returnType, 
2588
                                                SmallVectorImpl<QualType> &ArgTypes,
2589
                                                SmallVectorImpl<Expr*> &MsgExprs,
2590
1
                                                ObjCMethodDecl *Method) {
2591
1
  // Create a reference to the objc_msgSend_stret() declaration.
2592
1
  DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
2593
1
                                                 false, msgSendType,
2594
1
                                                 VK_LValue, SourceLocation());
2595
1
  // Need to cast objc_msgSend_stret to "void *" (see above comment).
2596
1
  CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2597
1
                                  Context->getPointerType(Context->VoidTy),
2598
1
                                  CK_BitCast, STDRE);
2599
1
  // Now do the "normal" pointer to function cast.
2600
1
  QualType castType = getSimpleFunctionType(returnType, ArgTypes,
2601
1
                                            Method ? Method->isVariadic()
2602
0
                                                   : false);
2603
1
  castType = Context->getPointerType(castType);
2604
1
  cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2605
1
                                            cast);
2606
1
  
2607
1
  // Don't forget the parens to enforce the proper binding.
2608
1
  ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
2609
1
  
2610
1
  const FunctionType *FT = msgSendType->getAs<FunctionType>();
2611
1
  CallExpr *STCE = new (Context) CallExpr(
2612
1
      *Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, SourceLocation());
2613
1
  return STCE;
2614
1
}
2615
2616
Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2617
                                    SourceLocation StartLoc,
2618
115
                                    SourceLocation EndLoc) {
2619
115
  if (!SelGetUidFunctionDecl)
2620
14
    SynthSelGetUidFunctionDecl();
2621
115
  if (!MsgSendFunctionDecl)
2622
36
    SynthMsgSendFunctionDecl();
2623
115
  if (!MsgSendSuperFunctionDecl)
2624
36
    SynthMsgSendSuperFunctionDecl();
2625
115
  if (!MsgSendStretFunctionDecl)
2626
36
    SynthMsgSendStretFunctionDecl();
2627
115
  if (!MsgSendSuperStretFunctionDecl)
2628
36
    SynthMsgSendSuperStretFunctionDecl();
2629
115
  if (!MsgSendFpretFunctionDecl)
2630
36
    SynthMsgSendFpretFunctionDecl();
2631
115
  if (!GetClassFunctionDecl)
2632
36
    SynthGetClassFunctionDecl();
2633
115
  if (!GetSuperClassFunctionDecl)
2634
36
    SynthGetSuperClassFunctionDecl();
2635
115
  if (!GetMetaClassFunctionDecl)
2636
36
    SynthGetMetaClassFunctionDecl();
2637
115
2638
115
  // default to objc_msgSend().
2639
115
  FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2640
115
  // May need to use objc_msgSend_stret() as well.
2641
115
  FunctionDecl *MsgSendStretFlavor = nullptr;
2642
115
  if (ObjCMethodDecl *
mDecl115
= Exp->getMethodDecl()) {
2643
103
    QualType resultType = mDecl->getReturnType();
2644
103
    if (resultType->isRecordType())
2645
1
      MsgSendStretFlavor = MsgSendStretFunctionDecl;
2646
102
    else 
if (102
resultType->isRealFloatingType()102
)
2647
0
      MsgSendFlavor = MsgSendFpretFunctionDecl;
2648
103
  }
2649
115
2650
115
  // Synthesize a call to objc_msgSend().
2651
115
  SmallVector<Expr*, 8> MsgExprs;
2652
115
  switch (Exp->getReceiverKind()) {
2653
1
  case ObjCMessageExpr::SuperClass: {
2654
1
    MsgSendFlavor = MsgSendSuperFunctionDecl;
2655
1
    if (MsgSendStretFlavor)
2656
0
      MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2657
1
    assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2658
1
2659
1
    ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2660
1
2661
1
    SmallVector<Expr*, 4> InitExprs;
2662
1
2663
1
    // set the receiver to self, the first argument to all methods.
2664
1
    InitExprs.push_back(
2665
1
      NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2666
1
                               CK_BitCast,
2667
1
                   new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2668
1
                                             false,
2669
1
                                             Context->getObjCIdType(),
2670
1
                                             VK_RValue,
2671
1
                                             SourceLocation()))
2672
1
                        ); // set the 'receiver'.
2673
1
2674
1
    // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2675
1
    SmallVector<Expr*, 8> ClsExprs;
2676
1
    ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
2677
1
    CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2678
1
                                                 ClsExprs, StartLoc, EndLoc);
2679
1
    // (Class)objc_getClass("CurrentClass")
2680
1
    CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2681
1
                                             Context->getObjCClassType(),
2682
1
                                             CK_BitCast, Cls);
2683
1
    ClsExprs.clear();
2684
1
    ClsExprs.push_back(ArgExpr);
2685
1
    Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
2686
1
                                       StartLoc, EndLoc);
2687
1
    // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2688
1
    // To turn off a warning, type-cast to 'id'
2689
1
    InitExprs.push_back( // set 'super class', using class_getSuperclass().
2690
1
                        NoTypeInfoCStyleCastExpr(Context,
2691
1
                                                 Context->getObjCIdType(),
2692
1
                                                 CK_BitCast, Cls));
2693
1
    // struct objc_super
2694
1
    QualType superType = getSuperStructType();
2695
1
    Expr *SuperRep;
2696
1
2697
1
    if (
LangOpts.MicrosoftExt1
) {
2698
1
      SynthSuperConstructorFunctionDecl();
2699
1
      // Simulate a constructor call...
2700
1
      DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
2701
1
                                                   false, superType, VK_LValue,
2702
1
                                                   SourceLocation());
2703
1
      SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
2704
1
                                        superType, VK_LValue,
2705
1
                                        SourceLocation());
2706
1
      // The code for super is a little tricky to prevent collision with
2707
1
      // the structure definition in the header. The rewriter has it's own
2708
1
      // internal definition (__rw_objc_super) that is uses. This is why
2709
1
      // we need the cast below. For example:
2710
1
      // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2711
1
      //
2712
1
      SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2713
1
                               Context->getPointerType(SuperRep->getType()),
2714
1
                                             VK_RValue, OK_Ordinary,
2715
1
                                             SourceLocation());
2716
1
      SuperRep = NoTypeInfoCStyleCastExpr(Context,
2717
1
                                          Context->getPointerType(superType),
2718
1
                                          CK_BitCast, SuperRep);
2719
1
    } else {
2720
0
      // (struct objc_super) { <exprs from above> }
2721
0
      InitListExpr *ILE =
2722
0
        new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
2723
0
                                   SourceLocation());
2724
0
      TypeSourceInfo *superTInfo
2725
0
        = Context->getTrivialTypeSourceInfo(superType);
2726
0
      SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2727
0
                                                   superType, VK_LValue,
2728
0
                                                   ILE, false);
2729
0
      // struct objc_super *
2730
0
      SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2731
0
                               Context->getPointerType(SuperRep->getType()),
2732
0
                                             VK_RValue, OK_Ordinary,
2733
0
                                             SourceLocation());
2734
0
    }
2735
1
    MsgExprs.push_back(SuperRep);
2736
1
    break;
2737
115
  }
2738
115
2739
17
  case ObjCMessageExpr::Class: {
2740
17
    SmallVector<Expr*, 8> ClsExprs;
2741
17
    ObjCInterfaceDecl *Class
2742
17
      = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
2743
17
    IdentifierInfo *clsName = Class->getIdentifier();
2744
17
    ClsExprs.push_back(getStringLiteral(clsName->getName()));
2745
17
    CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
2746
17
                                                 StartLoc, EndLoc);
2747
17
    MsgExprs.push_back(Cls);
2748
17
    break;
2749
115
  }
2750
115
2751
2
  case ObjCMessageExpr::SuperInstance:{
2752
2
    MsgSendFlavor = MsgSendSuperFunctionDecl;
2753
2
    if (MsgSendStretFlavor)
2754
0
      MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2755
2
    assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2756
2
    ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2757
2
    SmallVector<Expr*, 4> InitExprs;
2758
2
2759
2
    InitExprs.push_back(
2760
2
      NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2761
2
                               CK_BitCast,
2762
2
                   new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2763
2
                                             false,
2764
2
                                             Context->getObjCIdType(),
2765
2
                                             VK_RValue, SourceLocation()))
2766
2
                        ); // set the 'receiver'.
2767
2
    
2768
2
    // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2769
2
    SmallVector<Expr*, 8> ClsExprs;
2770
2
    ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
2771
2
    CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
2772
2
                                                 StartLoc, EndLoc);
2773
2
    // (Class)objc_getClass("CurrentClass")
2774
2
    CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2775
2
                                                 Context->getObjCClassType(),
2776
2
                                                 CK_BitCast, Cls);
2777
2
    ClsExprs.clear();
2778
2
    ClsExprs.push_back(ArgExpr);
2779
2
    Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
2780
2
                                       StartLoc, EndLoc);
2781
2
    
2782
2
    // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2783
2
    // To turn off a warning, type-cast to 'id'
2784
2
    InitExprs.push_back(
2785
2
      // set 'super class', using class_getSuperclass().
2786
2
      NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2787
2
                               CK_BitCast, Cls));
2788
2
    // struct objc_super
2789
2
    QualType superType = getSuperStructType();
2790
2
    Expr *SuperRep;
2791
2
2792
2
    if (
LangOpts.MicrosoftExt2
) {
2793
1
      SynthSuperConstructorFunctionDecl();
2794
1
      // Simulate a constructor call...
2795
1
      DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
2796
1
                                                   false, superType, VK_LValue,
2797
1
                                                   SourceLocation());
2798
1
      SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
2799
1
                                        superType, VK_LValue, SourceLocation());
2800
1
      // The code for super is a little tricky to prevent collision with
2801
1
      // the structure definition in the header. The rewriter has it's own
2802
1
      // internal definition (__rw_objc_super) that is uses. This is why
2803
1
      // we need the cast below. For example:
2804
1
      // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2805
1
      //
2806
1
      SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2807
1
                               Context->getPointerType(SuperRep->getType()),
2808
1
                               VK_RValue, OK_Ordinary,
2809
1
                               SourceLocation());
2810
1
      SuperRep = NoTypeInfoCStyleCastExpr(Context,
2811
1
                               Context->getPointerType(superType),
2812
1
                               CK_BitCast, SuperRep);
2813
2
    } else {
2814
1
      // (struct objc_super) { <exprs from above> }
2815
1
      InitListExpr *ILE =
2816
1
        new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
2817
1
                                   SourceLocation());
2818
1
      TypeSourceInfo *superTInfo
2819
1
        = Context->getTrivialTypeSourceInfo(superType);
2820
1
      SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2821
1
                                                   superType, VK_RValue, ILE,
2822
1
                                                   false);
2823
1
    }
2824
2
    MsgExprs.push_back(SuperRep);
2825
2
    break;
2826
115
  }
2827
115
2828
95
  case ObjCMessageExpr::Instance: {
2829
95
    // Remove all type-casts because it may contain objc-style types; e.g.
2830
95
    // Foo<Proto> *.
2831
95
    Expr *recExpr = Exp->getInstanceReceiver();
2832
99
    while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2833
4
      recExpr = CE->getSubExpr();
2834
95
    CastKind CK = recExpr->getType()->isObjCObjectPointerType()
2835
95
                    ? 
CK_BitCast95
: recExpr->getType()->isBlockPointerType()
2836
0
                                     ? CK_BlockPointerToObjCPointerCast
2837
0
                                     : CK_CPointerToObjCPointerCast;
2838
95
2839
95
    recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2840
95
                                       CK, recExpr);
2841
95
    MsgExprs.push_back(recExpr);
2842
95
    break;
2843
115
  }
2844
115
  }
2845
115
2846
115
  // Create a call to sel_registerName("selName"), it will be the 2nd argument.
2847
115
  SmallVector<Expr*, 8> SelExprs;
2848
115
  SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
2849
115
  CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2850
115
                                                  SelExprs, StartLoc, EndLoc);
2851
115
  MsgExprs.push_back(SelExp);
2852
115
2853
115
  // Now push any user supplied arguments.
2854
166
  for (unsigned i = 0; 
i < Exp->getNumArgs()166
;
i++51
) {
2855
51
    Expr *userExpr = Exp->getArg(i);
2856
51
    // Make all implicit casts explicit...ICE comes in handy:-)
2857
51
    if (ImplicitCastExpr *
ICE51
= dyn_cast<ImplicitCastExpr>(userExpr)) {
2858
15
      // Reuse the ICE type, it is exactly what the doctor ordered.
2859
15
      QualType type = ICE->getType();
2860
15
      if (needToScanForQualifiers(type))
2861
1
        type = Context->getObjCIdType();
2862
15
      // Make sure we convert "type (^)(...)" to "type (*)(...)".
2863
15
      (void)convertBlockPointerToFunctionPointer(type);
2864
15
      const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2865
15
      CastKind CK;
2866
15
      if (SubExpr->getType()->isIntegralType(*Context) && 
2867
15
          
type->isBooleanType()6
) {
2868
1
        CK = CK_IntegralToBoolean;
2869
15
      } else 
if (14
type->isObjCObjectPointerType()14
) {
2870
7
        if (
SubExpr->getType()->isBlockPointerType()7
) {
2871
0
          CK = CK_BlockPointerToObjCPointerCast;
2872
7
        } else 
if (7
SubExpr->getType()->isPointerType()7
) {
2873
0
          CK = CK_CPointerToObjCPointerCast;
2874
7
        } else {
2875
7
          CK = CK_BitCast;
2876
7
        }
2877
14
      } else {
2878
7
        CK = CK_BitCast;
2879
7
      }
2880
15
2881
15
      userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
2882
15
    }
2883
51
    // Make id<P...> cast into an 'id' cast.
2884
36
    else 
if (CStyleCastExpr *36
CE36
= dyn_cast<CStyleCastExpr>(userExpr)) {
2885
20
      if (
CE->getType()->isObjCQualifiedIdType()20
) {
2886
2
        while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
2887
1
          userExpr = CE->getSubExpr();
2888
1
        CastKind CK;
2889
1
        if (
userExpr->getType()->isIntegralType(*Context)1
) {
2890
1
          CK = CK_IntegralToPointer;
2891
1
        } else 
if (0
userExpr->getType()->isBlockPointerType()0
) {
2892
0
          CK = CK_BlockPointerToObjCPointerCast;
2893
0
        } else 
if (0
userExpr->getType()->isPointerType()0
) {
2894
0
          CK = CK_CPointerToObjCPointerCast;
2895
0
        } else {
2896
0
          CK = CK_BitCast;
2897
0
        }
2898
1
        userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2899
1
                                            CK, userExpr);
2900
1
      }
2901
36
    }
2902
51
    MsgExprs.push_back(userExpr);
2903
51
    // We've transferred the ownership to MsgExprs. For now, we *don't* null
2904
51
    // out the argument in the original expression (since we aren't deleting
2905
51
    // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
2906
51
    //Exp->setArg(i, 0);
2907
51
  }
2908
115
  // Generate the funky cast.
2909
115
  CastExpr *cast;
2910
115
  SmallVector<QualType, 8> ArgTypes;
2911
115
  QualType returnType;
2912
115
2913
115
  // Push 'id' and 'SEL', the 2 implicit arguments.
2914
115
  if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2915
3
    ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2916
115
  else
2917
112
    ArgTypes.push_back(Context->getObjCIdType());
2918
115
  ArgTypes.push_back(Context->getObjCSelType());
2919
115
  if (ObjCMethodDecl *
OMD115
= Exp->getMethodDecl()) {
2920
103
    // Push any user argument types.
2921
35
    for (const auto *PI : OMD->parameters()) {
2922
35
      QualType t = PI->getType()->isObjCQualifiedIdType()
2923
1
                     ? Context->getObjCIdType()
2924
34
                     : PI->getType();
2925
35
      // Make sure we convert "t (^)(...)" to "t (*)(...)".
2926
35
      (void)convertBlockPointerToFunctionPointer(t);
2927
35
      ArgTypes.push_back(t);
2928
35
    }
2929
103
    returnType = Exp->getType();
2930
103
    convertToUnqualifiedObjCType(returnType);
2931
103
    (void)convertBlockPointerToFunctionPointer(returnType);
2932
115
  } else {
2933
12
    returnType = Context->getObjCIdType();
2934
12
  }
2935
115
  // Get the type, we will need to reference it in a couple spots.
2936
115
  QualType msgSendType = MsgSendFlavor->getType();
2937
115
2938
115
  // Create a reference to the objc_msgSend() declaration.
2939
115
  DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2940
115
                                               VK_LValue, SourceLocation());
2941
115
2942
115
  // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2943
115
  // If we don't do this cast, we get the following bizarre warning/note:
2944
115
  // xx.m:13: warning: function called through a non-compatible type
2945
115
  // xx.m:13: note: if this code is reached, the program will abort
2946
115
  cast = NoTypeInfoCStyleCastExpr(Context,
2947
115
                                  Context->getPointerType(Context->VoidTy),
2948
115
                                  CK_BitCast, DRE);
2949
115
2950
115
  // Now do the "normal" pointer to function cast.
2951
115
  // If we don't have a method decl, force a variadic cast.
2952
115
  const ObjCMethodDecl *MD = Exp->getMethodDecl();
2953
115
  QualType castType =
2954
115
    getSimpleFunctionType(returnType, ArgTypes, MD ? 
MD->isVariadic()103
:
true12
);
2955
115
  castType = Context->getPointerType(castType);
2956
115
  cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2957
115
                                  cast);
2958
115
2959
115
  // Don't forget the parens to enforce the proper binding.
2960
115
  ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2961
115
2962
115
  const FunctionType *FT = msgSendType->getAs<FunctionType>();
2963
115
  CallExpr *CE = new (Context)
2964
115
      CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
2965
115
  Stmt *ReplacingStmt = CE;
2966
115
  if (
MsgSendStretFlavor115
) {
2967
1
    // We have the method which returns a struct/union. Must also generate
2968
1
    // call to objc_msgSend_stret and hang both varieties on a conditional
2969
1
    // expression which dictate which one to envoke depending on size of
2970
1
    // method's return type.
2971
1
    
2972
1
    CallExpr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor, 
2973
1
                                               msgSendType, returnType, 
2974
1
                                               ArgTypes, MsgExprs,
2975
1
                                               Exp->getMethodDecl());
2976
1
2977
1
    // Build sizeof(returnType)
2978
1
    UnaryExprOrTypeTraitExpr *sizeofExpr =
2979
1
       new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
2980
1
                                 Context->getTrivialTypeSourceInfo(returnType),
2981
1
                                 Context->getSizeType(), SourceLocation(),
2982
1
                                 SourceLocation());
2983
1
    // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2984
1
    // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2985
1
    // For X86 it is more complicated and some kind of target specific routine
2986
1
    // is needed to decide what to do.
2987
1
    unsigned IntSize =
2988
1
      static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2989
1
    IntegerLiteral *limit = IntegerLiteral::Create(*Context,
2990
1
                                                   llvm::APInt(IntSize, 8),
2991
1
                                                   Context->IntTy,
2992
1
                                                   SourceLocation());
2993
1
    BinaryOperator *lessThanExpr = 
2994
1
      new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
2995
1
                                   VK_RValue, OK_Ordinary, SourceLocation(),
2996
1
                                   FPOptions());
2997
1
    // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2998
1
    ConditionalOperator *CondExpr =
2999
1
      new (Context) ConditionalOperator(lessThanExpr,
3000
1
                                        SourceLocation(), CE,
3001
1
                                        SourceLocation(), STCE,
3002
1
                                        returnType, VK_RValue, OK_Ordinary);
3003
1
    ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), 
3004
1
                                            CondExpr);
3005
1
  }
3006
115
  // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3007
115
  return ReplacingStmt;
3008
115
}
3009
3010
79
Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3011
79
  Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3012
79
                                         Exp->getLocEnd());
3013
79
3014
79
  // Now do the actual rewrite.
3015
79
  ReplaceStmt(Exp, ReplacingStmt);
3016
79
3017
79
  // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3018
79
  return ReplacingStmt;
3019
79
}
3020
3021
// typedef struct objc_object Protocol;
3022
0
QualType RewriteObjC::getProtocolType() {
3023
0
  if (
!ProtocolTypeDecl0
) {
3024
0
    TypeSourceInfo *TInfo
3025
0
      = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3026
0
    ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3027
0
                                           SourceLocation(), SourceLocation(),
3028
0
                                           &Context->Idents.get("Protocol"),
3029
0
                                           TInfo);
3030
0
  }
3031
0
  return Context->getTypeDeclType(ProtocolTypeDecl);
3032
0
}
3033
3034
/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3035
/// a synthesized/forward data reference (to the protocol's metadata).
3036
/// The forward references (and metadata) are generated in
3037
/// RewriteObjC::HandleTranslationUnit().
3038
0
Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
3039
0
  std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3040
0
  IdentifierInfo *ID = &Context->Idents.get(Name);
3041
0
  VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3042
0
                                SourceLocation(), ID, getProtocolType(),
3043
0
                                nullptr, SC_Extern);
3044
0
  DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3045
0
                                               VK_LValue, SourceLocation());
3046
0
  Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3047
0
                             Context->getPointerType(DRE->getType()),
3048
0
                             VK_RValue, OK_Ordinary, SourceLocation());
3049
0
  CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3050
0
                                                CK_BitCast,
3051
0
                                                DerefExpr);
3052
0
  ReplaceStmt(Exp, castExpr);
3053
0
  ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3054
0
  // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3055
0
  return castExpr;
3056
0
}
3057
3058
bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
3059
39
                                             const char *endBuf) {
3060
878
  while (
startBuf < endBuf878
) {
3061
839
    if (
*startBuf == '#'839
) {
3062
0
      // Skip whitespace.
3063
0
      for (++startBuf; 
startBuf[0] == ' ' || 0
startBuf[0] == '\t'0
;
++startBuf0
)
3064
0
        ;
3065
0
      if (!strncmp(startBuf, "if", strlen("if")) ||
3066
0
          !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3067
0
          !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3068
0
          !strncmp(startBuf, "define", strlen("define")) ||
3069
0
          !strncmp(startBuf, "undef", strlen("undef")) ||
3070
0
          !strncmp(startBuf, "else", strlen("else")) ||
3071
0
          !strncmp(startBuf, "elif", strlen("elif")) ||
3072
0
          !strncmp(startBuf, "endif", strlen("endif")) ||
3073
0
          !strncmp(startBuf, "pragma", strlen("pragma")) ||
3074
0
          !strncmp(startBuf, "include", strlen("include")) ||
3075
0
          !strncmp(startBuf, "import", strlen("import")) ||
3076
0
          !strncmp(startBuf, "include_next", strlen("include_next")))
3077
0
        return true;
3078
839
    }
3079
839
    startBuf++;
3080
839
  }
3081
39
  return false;
3082
39
}
3083
3084
/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3085
/// an objective-c class with ivars.
3086
void RewriteObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3087
120
                                               std::string &Result) {
3088
120
  assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3089
120
  assert(CDecl->getName() != "" &&
3090
120
         "Name missing in SynthesizeObjCInternalStruct");
3091
120
  // Do not synthesize more than once.
3092
120
  if (ObjCSynthesizedStructs.count(CDecl))
3093
0
    return;
3094
120
  ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
3095
120
  int NumIvars = CDecl->ivar_size();
3096
120
  SourceLocation LocStart = CDecl->getLocStart();
3097
120
  SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
3098
120
3099
120
  const char *startBuf = SM->getCharacterData(LocStart);
3100
120
  const char *endBuf = SM->getCharacterData(LocEnd);
3101
120
3102
120
  // If no ivars and no root or if its root, directly or indirectly,
3103
120
  // have no ivars (thus not synthesized) then no need to synthesize this class.
3104
120
  if (
(!CDecl->isThisDeclarationADefinition() || 120
NumIvars == 0120
) &&
3105
120
      
(!RCDecl || 81
!ObjCSynthesizedStructs.count(RCDecl)10
)) {
3106
80
    endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3107
80
    ReplaceText(LocStart, endBuf-startBuf, Result);
3108
80
    return;
3109
80
  }
3110
40
3111
40
  // FIXME: This has potential of causing problem. If
3112
40
  // SynthesizeObjCInternalStruct is ever called recursively.
3113
40
  Result += "\nstruct ";
3114
40
  Result += CDecl->getNameAsString();
3115
40
  if (LangOpts.MicrosoftExt)
3116
30
    Result += "_IMPL";
3117
40
3118
40
  if (
NumIvars > 040
) {
3119
39
    const char *cursor = strchr(startBuf, '{');
3120
39
    assert((cursor && endBuf)
3121
39
           && "SynthesizeObjCInternalStruct - malformed @interface");
3122
39
    // If the buffer contains preprocessor directives, we do more fine-grained
3123
39
    // rewrites. This is intended to fix code that looks like (which occurs in
3124
39
    // NSURL.h, for example):
3125
39
    //
3126
39
    // #ifdef XYZ
3127
39
    // @interface Foo : NSObject
3128
39
    // #else
3129
39
    // @interface FooBar : NSObject
3130
39
    // #endif
3131
39
    // {
3132
39
    //    int i;
3133
39
    // }
3134
39
    // @end
3135
39
    //
3136
39
    // This clause is segregated to avoid breaking the common case.
3137
39
    if (
BufferContainsPPDirectives(startBuf, cursor)39
) {
3138
0
      SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
3139
0
                                  CDecl->getAtStartLoc();
3140
0
      const char *endHeader = SM->getCharacterData(L);
3141
0
      endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
3142
0
3143
0
      if (
CDecl->protocol_begin() != CDecl->protocol_end()0
) {
3144
0
        // advance to the end of the referenced protocols.
3145
0
        while (
endHeader < cursor && 0
*endHeader != '>'0
)
endHeader++0
;
3146
0
        endHeader++;
3147
0
      }
3148
0
      // rewrite the original header
3149
0
      ReplaceText(LocStart, endHeader-startBuf, Result);
3150
39
    } else {
3151
39
      // rewrite the original header *without* disturbing the '{'
3152
39
      ReplaceText(LocStart, cursor-startBuf, Result);
3153
39
    }
3154
39
    if (
RCDecl && 39
ObjCSynthesizedStructs.count(RCDecl)6
) {
3155
1
      Result = "\n    struct ";
3156
1
      Result += RCDecl->getNameAsString();
3157
1
      Result += "_IMPL ";
3158
1
      Result += RCDecl->getNameAsString();
3159
1
      Result += "_IVARS;\n";
3160
1
3161
1
      // insert the super class structure definition.
3162
1
      SourceLocation OnePastCurly =
3163
1
        LocStart.getLocWithOffset(cursor-startBuf+1);
3164
1
      InsertText(OnePastCurly, Result);
3165
1
    }
3166
39
    cursor++; // past '{'
3167
39
3168
39
    // Now comment out any visibility specifiers.
3169
1.11k
    while (
cursor < endBuf1.11k
) {
3170
1.07k
      if (
*cursor == '@'1.07k
) {
3171
12
        SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
3172
12
        // Skip whitespace.
3173
12
        for (++cursor; 
cursor[0] == ' ' || 12
cursor[0] == '\t'12
;
++cursor0
)
3174
0
          /*scan*/;
3175
12
3176
12
        // FIXME: presence of @public, etc. inside comment results in
3177
12
        // this transformation as well, which is still correct c-code.
3178
12
        if (!strncmp(cursor, "public", strlen("public")) ||
3179
4
            !strncmp(cursor, "private", strlen("private")) ||
3180
0
            !strncmp(cursor, "package", strlen("package")) ||
3181
0
            !strncmp(cursor, "protected", strlen("protected")))
3182
12
          InsertText(atLoc, "// ");
3183
12
      }
3184
1.07k
      // FIXME: If there are cases where '<' is used in ivar declaration part
3185
1.07k
      // of user code, then scan the ivar list and use needToScanForQualifiers
3186
1.07k
      // for type checking.
3187
1.06k
      else 
if (1.06k
*cursor == '<'1.06k
) {
3188
4
        SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
3189
4
        InsertText(atLoc, "/* ");
3190
4
        cursor = strchr(cursor, '>');
3191
4
        cursor++;
3192
4
        atLoc = LocStart.getLocWithOffset(cursor-startBuf);
3193
4
        InsertText(atLoc, " */");
3194
1.06k
      } else 
if (1.06k
*cursor == '^'1.06k
) { // rewrite block specifier.
3195
1
        SourceLocation caretLoc = LocStart.getLocWithOffset(cursor-startBuf);
3196
1
        ReplaceText(caretLoc, 1, "*");
3197
1
      }
3198
1.07k
      cursor++;
3199
1.07k
    }
3200
39
    // Don't forget to add a ';'!!
3201
39
    InsertText(LocEnd.getLocWithOffset(1), ";");
3202
40
  } else { // we don't have any instance variables - insert super struct.
3203
1
    endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3204
1
    Result += " {\n    struct ";
3205
1
    Result += RCDecl->getNameAsString();
3206
1
    Result += "_IMPL ";
3207
1
    Result += RCDecl->getNameAsString();
3208
1
    Result += "_IVARS;\n};\n";
3209
1
    ReplaceText(LocStart, endBuf-startBuf, Result);
3210
1
  }
3211
40
  // Mark this struct as having been generated.
3212
40
  if (!ObjCSynthesizedStructs.insert(CDecl).second)
3213
0
    llvm_unreachable("struct already synthesize- SynthesizeObjCInternalStruct");
3214
120
}
3215
3216
//===----------------------------------------------------------------------===//
3217
// Meta Data Emission
3218
//===----------------------------------------------------------------------===//
3219
3220
/// RewriteImplementations - This routine rewrites all method implementations
3221
/// and emits meta-data.
3222
3223
53
void RewriteObjC::RewriteImplementations() {
3224
53
  int ClsDefCount = ClassImplementation.size();
3225
53
  int CatDefCount = CategoryImplementation.size();
3226
53
3227
53
  // Rewrite implemented methods
3228
117
  for (int i = 0; 
i < ClsDefCount117
;
i++64
)
3229
64
    RewriteImplementationDecl(ClassImplementation[i]);
3230
53
3231
59
  for (int i = 0; 
i < CatDefCount59
;
i++6
)
3232
6
    RewriteImplementationDecl(CategoryImplementation[i]);
3233
53
}
3234
3235
void RewriteObjC::RewriteByRefString(std::string &ResultStr, 
3236
                                     const std::string &Name,
3237
208
                                     ValueDecl *VD, bool def) {
3238
208
  assert(BlockByRefDeclNo.count(VD) && 
3239
208
         "RewriteByRefString: ByRef decl missing");
3240
208
  if (def)
3241
61
    ResultStr += "struct ";
3242
208
  ResultStr += "__Block_byref_" + Name + 
3243
208
    "_" + utostr(BlockByRefDeclNo[VD]) ;
3244
208
}
3245
3246
825
static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3247
825
  if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3248
430
    
return (Var->isFunctionOrMethodVarDecl() && 430
!Var->hasLocalStorage()233
);
3249
395
  return false;
3250
395
}
3251
3252
std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3253
                                                   StringRef funcName,
3254
68
                                                   std::string Tag) {
3255
68
  const FunctionType *AFT = CE->getFunctionType();
3256
68
  QualType RT = AFT->getReturnType();
3257
68
  std::string StructRef = "struct " + Tag;
3258
68
  std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
3259
68
                  funcName.str() + "_" + "block_func_" + utostr(i);
3260
68
3261
68
  BlockDecl *BD = CE->getBlockDecl();
3262
68
3263
68
  if (
isa<FunctionNoProtoType>(AFT)68
) {
3264
0
    // No user-supplied arguments. Still need to pass in a pointer to the
3265
0
    // block (to reference imported block decl refs).
3266
0
    S += "(" + StructRef + " *__cself)";
3267
68
  } else 
if (68
BD->param_empty()68
) {
3268
58
    S += "(" + StructRef + " *__cself)";
3269
68
  } else {
3270
10
    const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
3271
10
    assert(FT && "SynthesizeBlockFunc: No function proto");
3272
10
    S += '(';
3273
10
    // first add the implicit argument.
3274
10
    S += StructRef + " *__cself, ";
3275
10
    std::string ParamStr;
3276
10
    for (BlockDecl::param_iterator AI = BD->param_begin(),
3277
23
         E = BD->param_end(); 
AI != E23
;
++AI13
) {
3278
13
      if (
AI != BD->param_begin()13
)
S += ", "3
;
3279
13
      ParamStr = (*AI)->getNameAsString();
3280
13
      QualType QT = (*AI)->getType();
3281
13
      (void)convertBlockPointerToFunctionPointer(QT);
3282
13
      QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
3283
13
      S += ParamStr;
3284
13
    }
3285
10
    if (
FT->isVariadic()10
) {
3286
0
      if (
!BD->param_empty()0
)
S += ", "0
;
3287
0
      S += "...";
3288
0
    }
3289
68
    S += ')';
3290
68
  }
3291
68
  S += " {\n";
3292
68
3293
68
  // Create local declarations to avoid rewriting all closure decl ref exprs.
3294
68
  // First, emit a declaration for all "by ref" decls.
3295
68
  for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
3296
104
       E = BlockByRefDecls.end(); 
I != E104
;
++I36
) {
3297
36
    S += "  ";
3298
36
    std::string Name = (*I)->getNameAsString();
3299
36
    std::string TypeString;
3300
36
    RewriteByRefString(TypeString, Name, (*I));
3301
36
    TypeString += " *";
3302
36
    Name = TypeString + Name;
3303
36
    S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
3304
36
  }
3305
68
  // Next, emit a declaration for all "by copy" declarations.
3306
68
  for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
3307
110
       E = BlockByCopyDecls.end(); 
I != E110
;
++I42
) {
3308
42
    S += "  ";
3309
42
    // Handle nested closure invocation. For example:
3310
42
    //
3311
42
    //   void (^myImportedClosure)(void);
3312
42
    //   myImportedClosure  = ^(void) { setGlobalInt(x + y); };
3313
42
    //
3314
42
    //   void (^anotherClosure)(void);
3315
42
    //   anotherClosure = ^(void) {
3316
42
    //     myImportedClosure(); // import and invoke the closure
3317
42
    //   };
3318
42
    //
3319
42
    if (
isTopLevelBlockPointerType((*I)->getType())42
) {
3320
2
      RewriteBlockPointerTypeVariable(S, (*I));
3321
2
      S += " = (";
3322
2
      RewriteBlockPointerType(S, (*I)->getType());
3323
2
      S += ")";
3324
2
      S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3325
2
    }
3326
40
    else {
3327
40
      std::string Name = (*I)->getNameAsString();
3328
40
      QualType QT = (*I)->getType();
3329
40
      if (HasLocalVariableExternalStorage(*I))
3330
2
        QT = Context->getPointerType(QT);
3331
40
      QT.getAsStringInternal(Name, Context->getPrintingPolicy());
3332
40
      S += Name + " = __cself->" + 
3333
40
                              (*I)->getNameAsString() + "; // bound by copy\n";
3334
40
    }
3335
42
  }
3336
68
  std::string RewrittenStr = RewrittenBlockExprs[CE];
3337
68
  const char *cstr = RewrittenStr.c_str();
3338
341
  while (
*cstr++ != '{'341
)
;273
3339
68
  S += cstr;
3340
68
  S += "\n";
3341
68
  return S;
3342
68
}
3343
3344
std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3345
                                                   StringRef funcName,
3346
41
                                                   std::string Tag) {
3347
41
  std::string StructRef = "struct " + Tag;
3348
41
  std::string S = "static void __";
3349
41
3350
41
  S += funcName;
3351
41
  S += "_block_copy_" + utostr(i);
3352
41
  S += "(" + StructRef;
3353
41
  S += "*dst, " + StructRef;
3354
41
  S += "*src) {";
3355
69
  for (ValueDecl *VD : ImportedBlockDecls) {
3356
69
    S += "_Block_object_assign((void*)&dst->";
3357
69
    S += VD->getNameAsString();
3358
69
    S += ", (void*)src->";
3359
69
    S += VD->getNameAsString();
3360
69
    if (BlockByRefDeclsPtrSet.count(VD))
3361
36
      S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3362
33
    else 
if (33
VD->getType()->isBlockPointerType()33
)
3363
3
      S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3364
33
    else
3365
30
      S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3366
69
  }
3367
41
  S += "}\n";
3368
41
  
3369
41
  S += "\nstatic void __";
3370
41
  S += funcName;
3371
41
  S += "_block_dispose_" + utostr(i);
3372
41
  S += "(" + StructRef;
3373
41
  S += "*src) {";
3374
69
  for (ValueDecl *VD : ImportedBlockDecls) {
3375
69
    S += "_Block_object_dispose((void*)src->";
3376
69
    S += VD->getNameAsString();
3377
69
    if (BlockByRefDeclsPtrSet.count(VD))
3378
36
      S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3379
33
    else 
if (33
VD->getType()->isBlockPointerType()33
)
3380
3
      S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3381
33
    else
3382
30
      S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3383
69
  }
3384
41
  S += "}\n";
3385
41
  return S;
3386
41
}
3387
3388
std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag, 
3389
68
                                             std::string Desc) {
3390
68
  std::string S = "\nstruct " + Tag;
3391
68
  std::string Constructor = "  " + Tag;
3392
68
3393
68
  S += " {\n  struct __block_impl impl;\n";
3394
68
  S += "  struct " + Desc;
3395
68
  S += "* Desc;\n";
3396
68
3397
68
  Constructor += "(void *fp, "; // Invoke function pointer.
3398
68
  Constructor += "struct " + Desc; // Descriptor pointer.
3399
68
  Constructor += " *desc";
3400
68
3401
68
  if (
BlockDeclRefs.size()68
) {
3402
47
    // Output all "by copy" declarations.
3403
47
    for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
3404
89
         E = BlockByCopyDecls.end(); 
I != E89
;
++I42
) {
3405
42
      S += "  ";
3406
42
      std::string FieldName = (*I)->getNameAsString();
3407
42
      std::string ArgName = "_" + FieldName;
3408
42
      // Handle nested closure invocation. For example:
3409
42
      //
3410
42
      //   void (^myImportedBlock)(void);
3411
42
      //   myImportedBlock  = ^(void) { setGlobalInt(x + y); };
3412
42
      //
3413
42
      //   void (^anotherBlock)(void);
3414
42
      //   anotherBlock = ^(void) {
3415
42
      //     myImportedBlock(); // import and invoke the closure
3416
42
      //   };
3417
42
      //
3418
42
      if (
isTopLevelBlockPointerType((*I)->getType())42
) {
3419
2
        S += "struct __block_impl *";
3420
2
        Constructor += ", void *" + ArgName;
3421
42
      } else {
3422
40
        QualType QT = (*I)->getType();
3423
40
        if (HasLocalVariableExternalStorage(*I))
3424
2
          QT = Context->getPointerType(QT);
3425
40
        QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3426
40
        QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
3427
40
        Constructor += ", " + ArgName;
3428
40
      }
3429
42
      S += FieldName + ";\n";
3430
42
    }
3431
47
    // Output all "by ref" declarations.
3432
47
    for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
3433
83
         E = BlockByRefDecls.end(); 
I != E83
;
++I36
) {
3434
36
      S += "  ";
3435
36
      std::string FieldName = (*I)->getNameAsString();
3436
36
      std::string ArgName = "_" + FieldName;
3437
36
      {
3438
36
        std::string TypeString;
3439
36
        RewriteByRefString(TypeString, FieldName, (*I));
3440
36
        TypeString += " *";
3441
36
        FieldName = TypeString + FieldName;
3442
36
        ArgName = TypeString + ArgName;
3443
36
        Constructor += ", " + ArgName;
3444
36
      }
3445
36
      S += FieldName + "; // by ref\n";
3446
36
    }
3447
47
    // Finish writing the constructor.
3448
47
    Constructor += ", int flags=0)";
3449
47
    // Initialize all "by copy" arguments.
3450
47
    bool firsTime = true;
3451
47
    for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
3452
89
         E = BlockByCopyDecls.end(); 
I != E89
;
++I42
) {
3453
42
      std::string Name = (*I)->getNameAsString();
3454
42
        if (
firsTime42
) {
3455
29
          Constructor += " : ";
3456
29
          firsTime = false;
3457
29
        }
3458
42
        else
3459
13
          Constructor += ", ";
3460
42
        if (isTopLevelBlockPointerType((*I)->getType()))
3461
2
          Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3462
42
        else
3463
40
          Constructor += Name + "(_" + Name + ")";
3464
42
    }
3465
47
    // Initialize all "by ref" arguments.
3466
47
    for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
3467
83
         E = BlockByRefDecls.end(); 
I != E83
;
++I36
) {
3468
36
      std::string Name = (*I)->getNameAsString();
3469
36
      if (
firsTime36
) {
3470
18
        Constructor += " : ";
3471
18
        firsTime = false;
3472
18
      }
3473
36
      else
3474
18
        Constructor += ", ";
3475
36
      Constructor += Name + "(_" + Name + "->__forwarding)";
3476
36
    }
3477
47
    
3478
47
    Constructor += " {\n";
3479
47
    if (GlobalVarDecl)
3480
0
      Constructor += "    impl.isa = &_NSConcreteGlobalBlock;\n";
3481
47
    else
3482
47
      Constructor += "    impl.isa = &_NSConcreteStackBlock;\n";
3483
47
    Constructor += "    impl.Flags = flags;\n    impl.FuncPtr = fp;\n";
3484
47
3485
47
    Constructor += "    Desc = desc;\n";
3486
68
  } else {
3487
21
    // Finish writing the constructor.
3488
21
    Constructor += ", int flags=0) {\n";
3489
21
    if (GlobalVarDecl)
3490
4
      Constructor += "    impl.isa = &_NSConcreteGlobalBlock;\n";
3491
21
    else
3492
17
      Constructor += "    impl.isa = &_NSConcreteStackBlock;\n";
3493
21
    Constructor += "    impl.Flags = flags;\n    impl.FuncPtr = fp;\n";
3494
21
    Constructor += "    Desc = desc;\n";
3495
21
  }
3496
68
  Constructor += "  ";
3497
68
  Constructor += "}\n";
3498
68
  S += Constructor;
3499
68
  S += "};\n";
3500
68
  return S;
3501
68
}
3502
3503
std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag, 
3504
                                                   std::string ImplTag, int i,
3505
                                                   StringRef FunName,
3506
68
                                                   unsigned hasCopy) {
3507
68
  std::string S = "\nstatic struct " + DescTag;
3508
68
  
3509
68
  S += " {\n  unsigned long reserved;\n";
3510
68
  S += "  unsigned long Block_size;\n";
3511
68
  if (
hasCopy68
) {
3512
41
    S += "  void (*copy)(struct ";
3513
41
    S += ImplTag; S += "*, struct ";
3514
41
    S += ImplTag; S += "*);\n";
3515
41
    
3516
41
    S += "  void (*dispose)(struct ";
3517
41
    S += ImplTag; S += "*);\n";
3518
41
  }
3519
68
  S += "} ";
3520
68
3521
68
  S += DescTag + "_DATA = { 0, sizeof(struct ";
3522
68
  S += ImplTag + ")";
3523
68
  if (
hasCopy68
) {
3524
41
    S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3525
41
    S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
3526
41
  }
3527
68
  S += "};\n";
3528
68
  return S;
3529
68
}
3530
3531
void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3532
150
                                          StringRef FunName) {
3533
150
  // Insert declaration for the function in which block literal is used.
3534
150
  if (
CurFunctionDeclToDeclareForBlock && 150
!Blocks.empty()54
)
3535
15
    RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
3536
150
  bool RewriteSC = (GlobalVarDecl &&
3537
9
                    !Blocks.empty() &&
3538
4
                    GlobalVarDecl->getStorageClass() == SC_Static &&
3539
3
                    GlobalVarDecl->getType().getCVRQualifiers());
3540
150
  if (
RewriteSC150
) {
3541
3
    std::string SC(" void __");
3542
3
    SC += GlobalVarDecl->getNameAsString();
3543
3
    SC += "() {}";
3544
3
    InsertText(FunLocStart, SC);
3545
3
  }
3546
150
  
3547
150
  // Insert closures that were part of the function.
3548
218
  for (unsigned i = 0, count=0; 
i < Blocks.size()218
;
i++68
) {
3549
68
    CollectBlockDeclRefInfo(Blocks[i]);
3550
68
    // Need to copy-in the inner copied-in variables not actually used in this
3551
68
    // block.
3552
89
    for (int j = 0; 
j < InnerDeclRefsCount[i]89
;
j++21
) {
3553
21
      DeclRefExpr *Exp = InnerDeclRefs[count++];
3554
21
      ValueDecl *VD = Exp->getDecl();
3555
21
      BlockDeclRefs.push_back(Exp);
3556
21
      if (
!VD->hasAttr<BlocksAttr>() && 21
!BlockByCopyDeclsPtrSet.count(VD)12
) {
3557
12
        BlockByCopyDeclsPtrSet.insert(VD);
3558
12
        BlockByCopyDecls.push_back(VD);
3559
12
      }
3560
21
      if (
VD->hasAttr<BlocksAttr>() && 21
!BlockByRefDeclsPtrSet.count(VD)9
) {
3561
9
        BlockByRefDeclsPtrSet.insert(VD);
3562
9
        BlockByRefDecls.push_back(VD);
3563
9
      }
3564
21
      // imported objects in the inner blocks not used in the outer
3565
21
      // blocks must be copied/disposed in the outer block as well.
3566
21
      if (VD->hasAttr<BlocksAttr>() ||
3567
12
          VD->getType()->isObjCObjectPointerType() || 
3568
1
          VD->getType()->isBlockPointerType())
3569
20
        ImportedBlockDecls.insert(VD);
3570
21
    }
3571
68
3572
68
    std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3573
68
    std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
3574
68
3575
68
    std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
3576
68
3577
68
    InsertText(FunLocStart, CI);
3578
68
3579
68
    std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
3580
68
3581
68
    InsertText(FunLocStart, CF);
3582
68
3583
68
    if (
ImportedBlockDecls.size()68
) {
3584
41
      std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
3585
41
      InsertText(FunLocStart, HF);
3586
41
    }
3587
68
    std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3588
68
                                               ImportedBlockDecls.size() > 0);
3589
68
    InsertText(FunLocStart, BD);
3590
68
3591
68
    BlockDeclRefs.clear();
3592
68
    BlockByRefDecls.clear();
3593
68
    BlockByRefDeclsPtrSet.clear();
3594
68
    BlockByCopyDecls.clear();
3595
68
    BlockByCopyDeclsPtrSet.clear();
3596
68
    ImportedBlockDecls.clear();
3597
68
  }
3598
150
  if (
RewriteSC150
) {
3599
3
    // Must insert any 'const/volatile/static here. Since it has been
3600
3
    // removed as result of rewriting of block literals.
3601
3
    std::string SC;
3602
3
    if (GlobalVarDecl->getStorageClass() == SC_Static)
3603
3
      SC = "static ";
3604
3
    if (GlobalVarDecl->getType().isConstQualified())
3605
3
      SC += "const ";
3606
3
    if (GlobalVarDecl->getType().isVolatileQualified())
3607
0
      SC += "volatile ";
3608
3
    if (GlobalVarDecl->getType().isRestrictQualified())
3609
0
      SC += "restrict ";
3610
3
    InsertText(FunLocStart, SC);
3611
3
  }
3612
150
  
3613
150
  Blocks.clear();
3614
150
  InnerDeclRefsCount.clear();
3615
150
  InnerDeclRefs.clear();
3616
150
  RewrittenBlockExprs.clear();
3617
150
}
3618
3619
64
void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3620
64
  SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
3621
64
  StringRef FuncName = FD->getName();
3622
64
3623
64
  SynthesizeBlockLiterals(FunLocStart, FuncName);
3624
64
}
3625
3626
static void BuildUniqueMethodName(std::string &Name,
3627
99
                                  ObjCMethodDecl *MD) {
3628
99
  ObjCInterfaceDecl *IFace = MD->getClassInterface();
3629
99
  Name = IFace->getName();
3630
99
  Name += "__" + MD->getSelector().getAsString();
3631
99
  // Convert colons to underscores.
3632
99
  std::string::size_type loc = 0;
3633
142
  while ((loc = Name.find(':', loc)) != std::string::npos)
3634
43
    Name.replace(loc, 1, "_");
3635
99
}
3636
3637
77
void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
3638
77
  //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3639
77
  //SourceLocation FunLocStart = MD->getLocStart();
3640
77
  SourceLocation FunLocStart = MD->getLocStart();
3641
77
  std::string FuncName;
3642
77
  BuildUniqueMethodName(FuncName, MD);
3643
77
  SynthesizeBlockLiterals(FunLocStart, FuncName);
3644
77
}
3645
3646
1.85k
void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3647
1.85k
  for (Stmt *SubStmt : S->children())
3648
1.72k
    
if (1.72k
SubStmt1.72k
) {
3649
1.71k
      if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt))
3650
0
        GetBlockDeclRefExprs(CBE->getBody());
3651
1.71k
      else
3652
1.71k
        GetBlockDeclRefExprs(SubStmt);
3653
1.72k
    }
3654
1.85k
  // Handle specific things.
3655
1.85k
  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
3656
426
    
if (426
DRE->refersToEnclosingVariableOrCapture() ||
3657
304
        HasLocalVariableExternalStorage(DRE->getDecl()))
3658
426
      // FIXME: Handle enums.
3659
140
      BlockDeclRefs.push_back(DRE);
3660
1.85k
}
3661
3662
void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
3663
                SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
3664
643
                llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts) {
3665
643
  for (Stmt *SubStmt : S->children())
3666
576
    
if (576
SubStmt576
) {
3667
575
      if (BlockExpr *
CBE575
= dyn_cast<BlockExpr>(SubStmt)) {
3668
15
        InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
3669
15
        GetInnerBlockDeclRefExprs(CBE->getBody(),
3670
15
                                  InnerBlockDeclRefs,
3671
15
                                  InnerContexts);
3672
15
      }
3673
575
      else
3674
560
        GetInnerBlockDeclRefExprs(SubStmt, InnerBlockDeclRefs, InnerContexts);
3675
576
    }
3676
643
  // Handle specific things.
3677
643
  if (DeclRefExpr *
DRE643
= dyn_cast<DeclRefExpr>(S)) {
3678
141
    if (DRE->refersToEnclosingVariableOrCapture() ||
3679
141
        
HasLocalVariableExternalStorage(DRE->getDecl())59
) {
3680
91
      if (!InnerContexts.count(DRE->getDecl()->getDeclContext()))
3681
90
        InnerBlockDeclRefs.push_back(DRE);
3682
91
      if (VarDecl *Var = cast<VarDecl>(DRE->getDecl()))
3683
91
        
if (91
Var->isFunctionOrMethodVarDecl()91
)
3684
72
          ImportedLocalExternalDecls.insert(Var);
3685
91
    }
3686
141
  }
3687
643
}
3688
3689
/// convertFunctionTypeOfBlocks - This routine converts a function type
3690
/// whose result type may be a block pointer or whose argument type(s)
3691
/// might be block pointers to an equivalent function type replacing
3692
/// all block pointers to function pointers.
3693
68
QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3694
68
  const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3695
68
  // FTP will be null for closures that don't take arguments.
3696
68
  // Generate a funky cast.
3697
68
  SmallVector<QualType, 8> ArgTypes;
3698
68
  QualType Res = FT->getReturnType();
3699
68
  bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
3700
68
  
3701
68
  if (
FTP68
) {
3702
13
    for (auto &I : FTP->param_types()) {
3703
13
      QualType t = I;
3704
13
      // Make sure we convert "t (^)(...)" to "t (*)(...)".
3705
13
      if (convertBlockPointerToFunctionPointer(t))
3706
1
        HasBlockType = true;
3707
13
      ArgTypes.push_back(t);
3708
13
    }
3709
68
  }
3710
68
  QualType FuncType;
3711
68
  // FIXME. Does this work if block takes no argument but has a return type
3712
68
  // which is of block type?
3713
68
  if (HasBlockType)
3714
1
    FuncType = getSimpleFunctionType(Res, ArgTypes);
3715
67
  else FuncType = QualType(FT, 0);
3716
68
  return FuncType;
3717
68
}
3718
3719
14
Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
3720
14
  // Navigate to relevant type information.
3721
14
  const BlockPointerType *CPT = nullptr;
3722
14
3723
14
  if (const DeclRefExpr *
DRE14
= dyn_cast<DeclRefExpr>(BlockExp)) {
3724
0
    CPT = DRE->getType()->getAs<BlockPointerType>();
3725
14
  } else 
if (const MemberExpr *14
MExpr14
= dyn_cast<MemberExpr>(BlockExp)) {
3726
0
    CPT = MExpr->getType()->getAs<BlockPointerType>();
3727
0
  } 
3728
14
  else 
if (const ParenExpr *14
PRE14
= dyn_cast<ParenExpr>(BlockExp)) {
3729
0
    return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3730
0
  }
3731
14
  else 
if (const ImplicitCastExpr *14
IEXPR14
= dyn_cast<ImplicitCastExpr>(BlockExp))
3732
14
    CPT = IEXPR->getType()->getAs<BlockPointerType>();
3733
0
  else 
if (const ConditionalOperator *0
CEXPR0
=
3734
0
            dyn_cast<ConditionalOperator>(BlockExp)) {
3735
0
    Expr *LHSExp = CEXPR->getLHS();
3736
0
    Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3737
0
    Expr *RHSExp = CEXPR->getRHS();
3738
0
    Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3739
0
    Expr *CONDExp = CEXPR->getCond();
3740
0
    ConditionalOperator *CondExpr =
3741
0
      new (Context) ConditionalOperator(CONDExp,
3742
0
                                      SourceLocation(), cast<Expr>(LHSStmt),
3743
0
                                      SourceLocation(), cast<Expr>(RHSStmt),
3744
0
                                      Exp->getType(), VK_RValue, OK_Ordinary);
3745
0
    return CondExpr;
3746
0
  } else 
if (const ObjCIvarRefExpr *0
IRE0
= dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3747
0
    CPT = IRE->getType()->getAs<BlockPointerType>();
3748
0
  } else 
if (const PseudoObjectExpr *0
POE0
3749
0
               = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3750
0
    CPT = POE->getType()->castAs<BlockPointerType>();
3751
0
  } else {
3752
0
    assert(false && "RewriteBlockClass: Bad type");
3753
0
  }
3754
14
  assert(CPT && "RewriteBlockClass: Bad type");
3755
14
  const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
3756
14
  assert(FT && "RewriteBlockClass: Bad type");
3757
14
  const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3758
14
  // FTP will be null for closures that don't take arguments.
3759
14
3760
14
  RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3761
14
                                      SourceLocation(), SourceLocation(),
3762
14
                                      &Context->Idents.get("__block_impl"));
3763
14
  QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
3764
14
3765
14
  // Generate a funky cast.
3766
14
  SmallVector<QualType, 8> ArgTypes;
3767
14
3768
14
  // Push the block argument type.
3769
14
  ArgTypes.push_back(PtrBlock);
3770
14
  if (
FTP14
) {
3771
6
    for (auto &I : FTP->param_types()) {
3772
6
      QualType t = I;
3773
6
      // Make sure we convert "t (^)(...)" to "t (*)(...)".
3774
6
      if (!convertBlockPointerToFunctionPointer(t))
3775
6
        convertToUnqualifiedObjCType(t);
3776
6
      ArgTypes.push_back(t);
3777
6
    }
3778
14
  }
3779
14
  // Now do the pointer to function cast.
3780
14
  QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
3781
14
3782
14
  PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
3783
14
3784
14
  CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
3785
14
                                               CK_BitCast,
3786
14
                                               const_cast<Expr*>(BlockExp));
3787
14
  // Don't forget the parens to enforce the proper binding.
3788
14
  ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3789
14
                                          BlkCast);
3790
14
  //PE->dump();
3791
14
3792
14
  FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
3793
14
                                    SourceLocation(),
3794
14
                                    &Context->Idents.get("FuncPtr"),
3795
14
                                    Context->VoidPtrTy, nullptr,
3796
14
                                    /*BitWidth=*/nullptr, /*Mutable=*/true,
3797
14
                                    ICIS_NoInit);
3798
14
  MemberExpr *ME =
3799
14
      new (Context) MemberExpr(PE, true, SourceLocation(), FD, SourceLocation(),
3800
14
                               FD->getType(), VK_LValue, OK_Ordinary);
3801
14
3802
14
  CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
3803
14
                                                CK_BitCast, ME);
3804
14
  PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3805
14
3806
14
  SmallVector<Expr*, 8> BlkExprs;
3807
14
  // Add the implicit argument.
3808
14
  BlkExprs.push_back(BlkCast);
3809
14
  // Add the user arguments.
3810
14
  for (CallExpr::arg_iterator I = Exp->arg_begin(),
3811
20
       E = Exp->arg_end(); 
I != E20
;
++I6
) {
3812
6
    BlkExprs.push_back(*I);
3813
6
  }
3814
14
  CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
3815
14
                                        Exp->getType(), VK_RValue,
3816
14
                                        SourceLocation());
3817
14
  return CE;
3818
14
}
3819
3820
// We need to return the rewritten expression to handle cases where the
3821
// BlockDeclRefExpr is embedded in another expression being rewritten.
3822
// For example:
3823
//
3824
// int main() {
3825
//    __block Foo *f;
3826
//    __block int i;
3827
//
3828
//    void (^myblock)() = ^() {
3829
//        [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
3830
//        i = 77;
3831
//    };
3832
//}
3833
35
Stmt *RewriteObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
3834
35
  // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR 
3835
35
  // for each DeclRefExp where BYREFVAR is name of the variable.
3836
35
  ValueDecl *VD = DeclRefExp->getDecl();
3837
35
  bool isArrow = DeclRefExp->refersToEnclosingVariableOrCapture() ||
3838
8
                 HasLocalVariableExternalStorage(DeclRefExp->getDecl());
3839
35
3840
35
  FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
3841
35
                                    SourceLocation(),
3842
35
                                    &Context->Idents.get("__forwarding"), 
3843
35
                                    Context->VoidPtrTy, nullptr,
3844
35
                                    /*BitWidth=*/nullptr, /*Mutable=*/true,
3845
35
                                    ICIS_NoInit);
3846
35
  MemberExpr *ME = new (Context)
3847
35
      MemberExpr(DeclRefExp, isArrow, SourceLocation(), FD, SourceLocation(),
3848
35
                 FD->getType(), VK_LValue, OK_Ordinary);
3849
35
3850
35
  StringRef Name = VD->getName();
3851
35
  FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(),
3852
35
                         &Context->Idents.get(Name), 
3853
35
                         Context->VoidPtrTy, nullptr,
3854
35
                         /*BitWidth=*/nullptr, /*Mutable=*/true,
3855
35
                         ICIS_NoInit);
3856
35
  ME =
3857
35
      new (Context) MemberExpr(ME, true, SourceLocation(), FD, SourceLocation(),
3858
35
                               DeclRefExp->getType(), VK_LValue, OK_Ordinary);
3859
35
3860
35
  // Need parens to enforce precedence.
3861
35
  ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(), 
3862
35
                                          DeclRefExp->getExprLoc(), 
3863
35
                                          ME);
3864
35
  ReplaceStmt(DeclRefExp, PE);
3865
35
  return PE;
3866
35
}
3867
3868
// Rewrites the imported local variable V with external storage 
3869
// (static, extern, etc.) as *V
3870
//
3871
15
Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
3872
15
  ValueDecl *VD = DRE->getDecl();
3873
15
  if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3874
15
    
if (15
!ImportedLocalExternalDecls.count(Var)15
)
3875
6
      return DRE;
3876
9
  Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
3877
9
                                          VK_LValue, OK_Ordinary,
3878
9
                                          DRE->getLocation());
3879
9
  // Need parens to enforce precedence.
3880
9
  ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), 
3881
9
                                          Exp);
3882
9
  ReplaceStmt(DRE, PE);
3883
9
  return PE;
3884
9
}
3885
3886
31
void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3887
31
  SourceLocation LocStart = CE->getLParenLoc();
3888
31
  SourceLocation LocEnd = CE->getRParenLoc();
3889
31
3890
31
  // Need to avoid trying to rewrite synthesized casts.
3891
31
  if (LocStart.isInvalid())
3892
0
    return;
3893
31
  // Need to avoid trying to rewrite casts contained in macros.
3894
31
  
if (31
!Rewriter::isRewritable(LocStart) || 31
!Rewriter::isRewritable(LocEnd)31
)
3895
0
    return;
3896
31
3897
31
  const char *startBuf = SM->getCharacterData(LocStart);
3898
31
  const char *endBuf = SM->getCharacterData(LocEnd);
3899
31
  QualType QT = CE->getType();
3900
31
  const Type* TypePtr = QT->getAs<Type>();
3901
31
  if (
isa<TypeOfExprType>(TypePtr)31
) {
3902
3
    const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
3903
3
    QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
3904
3
    std::string TypeAsString = "(";
3905
3
    RewriteBlockPointerType(TypeAsString, QT);
3906
3
    TypeAsString += ")";
3907
3
    ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
3908
3
    return;
3909
3
  }
3910
28
  // advance the location to startArgList.
3911
28
  const char *argPtr = startBuf;
3912
28
3913
249
  while (
*argPtr++ && 249
(argPtr < endBuf)249
) {
3914
221
    switch (*argPtr) {
3915
0
    case '^':
3916
0
      // Replace the '^' with '*'.
3917
0
      LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
3918
0
      ReplaceText(LocStart, 1, "*");
3919
0
      break;
3920
221
    }
3921
221
  }
3922
31
}
3923
3924
20
void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3925
20
  SourceLocation DeclLoc = FD->getLocation();
3926
20
  unsigned parenCount = 0;
3927
20
3928
20
  // We have 1 or more arguments that have closure pointers.
3929
20
  const char *startBuf = SM->getCharacterData(DeclLoc);
3930
20
  const char *startArgList = strchr(startBuf, '(');
3931
20
3932
20
  assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3933
20
3934
20
  parenCount++;
3935
20
  // advance the location to startArgList.
3936
20
  DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
3937
20
  assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3938
20
3939
20
  const char *argPtr = startArgList;
3940
20
3941
390
  while (
*argPtr++ && 390
parenCount390
) {
3942
370
    switch (*argPtr) {
3943
20
    case '^':
3944
20
      // Replace the '^' with '*'.
3945
20
      DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
3946
20
      ReplaceText(DeclLoc, 1, "*");
3947
20
      break;
3948
40
    case '(':
3949
40
      parenCount++;
3950
40
      break;
3951
60
    case ')':
3952
60
      parenCount--;
3953
60
      break;
3954
370
    }
3955
370
  }
3956
20
}
3957
3958
46
bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
3959
46
  const FunctionProtoType *FTP;
3960
46
  const PointerType *PT = QT->getAs<PointerType>();
3961
46
  if (
PT46
) {
3962
1
    FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
3963
46
  } else {
3964
45
    const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
3965
45
    assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3966
45
    FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
3967
45
  }
3968
46
  if (
FTP46
) {
3969
44
    for (const auto &I : FTP->param_types())
3970
30
      
if (30
isTopLevelBlockPointerType(I)30
)
3971
3
        return true;
3972
43
  }
3973
43
  return false;
3974
43
}
3975
3976
42
bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
3977
42
  const FunctionProtoType *FTP;
3978
42
  const PointerType *PT = QT->getAs<PointerType>();
3979
42
  if (
PT42
) {
3980
0
    FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
3981
42
  } else {
3982
42
    const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
3983
42
    assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3984
42
    FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
3985
42
  }
3986
42
  if (
FTP42
) {
3987
16
    for (const auto &I : FTP->param_types()) {
3988
16
      if (I->isObjCQualifiedIdType())
3989
5
        return true;
3990
11
      
if (11
I->isObjCObjectPointerType() &&
3991
4
          I->getPointeeType()->isObjCQualifiedInterfaceType())
3992
1
        return true;
3993
36
    }
3994
40
        
3995
40
  }
3996
36
  return false;
3997
36
}
3998
3999
void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4000
9
                                     const char *&RParen) {
4001
9
  const char *argPtr = strchr(Name, '(');
4002
9
  assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4003
9
4004
9
  LParen = argPtr; // output the start.
4005
9
  argPtr++; // skip past the left paren.
4006
9
  unsigned parenCount = 1;
4007
9
4008
884
  while (
*argPtr && 884
parenCount884
) {
4009
875
    switch (*argPtr) {
4010
10
    case '(': parenCount++; break;
4011
19
    case ')': parenCount--; break;
4012
846
    default: break;
4013
875
    }
4014
875
    
if (875
parenCount875
)
argPtr++866
;
4015
875
  }
4016
9
  assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4017
9
  RParen = argPtr; // output the end
4018
9
}
4019
4020
65
void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4021
65
  if (FunctionDecl *
FD65
= dyn_cast<FunctionDecl>(ND)) {
4022
20
    RewriteBlockPointerFunctionArgs(FD);
4023
20
    return;
4024
20
  }
4025
45
  // Handle Variables and Typedefs.
4026
45
  SourceLocation DeclLoc = ND->getLocation();
4027
45
  QualType DeclT;
4028
45
  if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4029
25
    DeclT = VD->getType();
4030
20
  else 
if (TypedefNameDecl *20
TDD20
= dyn_cast<TypedefNameDecl>(ND))
4031
20
    DeclT = TDD->getUnderlyingType();
4032
0
  else 
if (FieldDecl *0
FD0
= dyn_cast<FieldDecl>(ND))
4033
0
    DeclT = FD->getType();
4034
0
  else
4035
0
    llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4036
45
4037
45
  const char *startBuf = SM->getCharacterData(DeclLoc);
4038
45
  const char *endBuf = startBuf;
4039
45
  // scan backward (from the decl location) for the end of the previous decl.
4040
92
  while (
*startBuf != '^' && 92
*startBuf != ';'47
&&
startBuf != MainFileStart47
)
4041
47
    startBuf--;
4042
45
  SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4043
45
  std::string buf;
4044
45
  unsigned OrigLength=0;
4045
45
  // *startBuf != '^' if we are dealing with a pointer to function that
4046
45
  // may take block argument types (which will be handled below).
4047
45
  if (
*startBuf == '^'45
) {
4048
45
    // Replace the '^' with '*', computing a negative offset.
4049
45
    buf = '*';
4050
45
    startBuf++;
4051
45
    OrigLength++;
4052
45
  }
4053
440
  while (
*startBuf != ')'440
) {
4054
395
    buf += *startBuf;
4055
395
    startBuf++;
4056
395
    OrigLength++;
4057
395
  }
4058
45
  buf += ')';
4059
45
  OrigLength++;
4060
45
  
4061
45
  if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4062
45
      
PointerTypeTakesAnyObjCQualifiedType(DeclT)42
) {
4063
9
    // Replace the '^' with '*' for arguments.
4064
9
    // Replace id<P> with id/*<>*/
4065
9
    DeclLoc = ND->getLocation();
4066
9
    startBuf = SM->getCharacterData(DeclLoc);
4067
9
    const char *argListBegin, *argListEnd;
4068
9
    GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4069
453
    while (
argListBegin < argListEnd453
) {
4070
444
      if (*argListBegin == '^')
4071
5
        buf += '*';
4072
439
      else 
if (439
*argListBegin == '<'439
) {
4073
17
        buf += "/*"; 
4074
17
        buf += *argListBegin++;
4075
17
        OrigLength++;
4076
431
        while (
*argListBegin != '>'431
) {
4077
414
          buf += *argListBegin++;
4078
414
          OrigLength++;
4079
414
        }
4080
17
        buf += *argListBegin;
4081
17
        buf += "*/";
4082
17
      }
4083
439
      else
4084
422
        buf += *argListBegin;
4085
444
      argListBegin++;
4086
444
      OrigLength++;
4087
444
    }
4088
9
    buf += ')';
4089
9
    OrigLength++;
4090
9
  }
4091
65
  ReplaceText(Start, OrigLength, buf);
4092
65
}
4093
4094
/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4095
/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4096
///                    struct Block_byref_id_object *src) {
4097
///  _Block_object_assign (&_dest->object, _src->object, 
4098
///                        BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4099
///                        [|BLOCK_FIELD_IS_WEAK]) // object
4100
///  _Block_object_assign(&_dest->object, _src->object, 
4101
///                       BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4102
///                       [|BLOCK_FIELD_IS_WEAK]) // block
4103
/// }
4104
/// And:
4105
/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4106
///  _Block_object_dispose(_src->object, 
4107
///                        BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4108
///                        [|BLOCK_FIELD_IS_WEAK]) // object
4109
///  _Block_object_dispose(_src->object, 
4110
///                         BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4111
///                         [|BLOCK_FIELD_IS_WEAK]) // block
4112
/// }
4113
4114
std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4115
8
                                                          int flag) {
4116
8
  std::string S;
4117
8
  if (CopyDestroyCache.count(flag))
4118
3
    return S;
4119
5
  CopyDestroyCache.insert(flag);
4120
5
  S = "static void __Block_byref_id_object_copy_";
4121
5
  S += utostr(flag);
4122
5
  S += "(void *dst, void *src) {\n";
4123
5
  
4124
5
  // offset into the object pointer is computed as:
4125
5
  // void * + void* + int + int + void* + void *
4126
5
  unsigned IntSize = 
4127
5
  static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4128
5
  unsigned VoidPtrSize = 
4129
5
  static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4130
5
  
4131
5
  unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4132
5
  S += " _Block_object_assign((char*)dst + ";
4133
5
  S += utostr(offset);
4134
5
  S += ", *(void * *) ((char*)src + ";
4135
5
  S += utostr(offset);
4136
5
  S += "), ";
4137
5
  S += utostr(flag);
4138
5
  S += ");\n}\n";
4139
5
  
4140
5
  S += "static void __Block_byref_id_object_dispose_";
4141
5
  S += utostr(flag);
4142
5
  S += "(void *src) {\n";
4143
5
  S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4144
5
  S += utostr(offset);
4145
5
  S += "), ";
4146
5
  S += utostr(flag);
4147
5
  S += ");\n}\n";
4148
5
  return S;
4149
5
}
4150
4151
/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4152
/// the declaration into:
4153
/// struct __Block_byref_ND {
4154
/// void *__isa;                  // NULL for everything except __weak pointers
4155
/// struct __Block_byref_ND *__forwarding;
4156
/// int32_t __flags;
4157
/// int32_t __size;
4158
/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4159
/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4160
/// typex ND;
4161
/// };
4162
///
4163
/// It then replaces declaration of ND variable with:
4164
/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag, 
4165
///                               __size=sizeof(struct __Block_byref_ND), 
4166
///                               ND=initializer-if-any};
4167
///
4168
///
4169
25
void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
4170
25
  // Insert declaration for the function in which block literal is
4171
25
  // used.
4172
25
  if (CurFunctionDeclToDeclareForBlock)
4173
15
    RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
4174
25
  int flag = 0;
4175
25
  int isa = 0;
4176
25
  SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4177
25
  if (DeclLoc.isInvalid())
4178
25
    // If type location is missing, it is because of missing type (a warning).
4179
25
    // Use variable's location which is good for this case.
4180
0
    DeclLoc = ND->getLocation();
4181
25
  const char *startBuf = SM->getCharacterData(DeclLoc);
4182
25
  SourceLocation X = ND->getLocEnd();
4183
25
  X = SM->getExpansionLoc(X);
4184
25
  const char *endBuf = SM->getCharacterData(X);
4185
25
  std::string Name(ND->getNameAsString());
4186
25
  std::string ByrefType;
4187
25
  RewriteByRefString(ByrefType, Name, ND, true);
4188
25
  ByrefType += " {\n";
4189
25
  ByrefType += "  void *__isa;\n";
4190
25
  RewriteByRefString(ByrefType, Name, ND);
4191
25
  ByrefType += " *__forwarding;\n";
4192
25
  ByrefType += " int __flags;\n";
4193
25
  ByrefType += " int __size;\n";
4194
25
  // Add void *__Block_byref_id_object_copy; 
4195
25
  // void *__Block_byref_id_object_dispose; if needed.
4196
25
  QualType Ty = ND->getType();
4197
25
  bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
4198
25
  if (
HasCopyAndDispose25
) {
4199
8
    ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4200
8
    ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4201
8
  }
4202
25
4203
25
  QualType T = Ty;
4204
25
  (void)convertBlockPointerToFunctionPointer(T);
4205
25
  T.getAsStringInternal(Name, Context->getPrintingPolicy());
4206
25
    
4207
25
  ByrefType += " " + Name + ";\n";
4208
25
  ByrefType += "};\n";
4209
25
  // Insert this type in global scope. It is needed by helper function.
4210
25
  SourceLocation FunLocStart;
4211
25
  if (CurFunctionDef)
4212
17
     FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4213
8
  else {
4214
8
    assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4215
8
    FunLocStart = CurMethodDef->getLocStart();
4216
8
  }
4217
25
  InsertText(FunLocStart, ByrefType);
4218
25
  if (
Ty.isObjCGCWeak()25
) {
4219
2
    flag |= BLOCK_FIELD_IS_WEAK;
4220
2
    isa = 1;
4221
2
  }
4222
25
  
4223
25
  if (
HasCopyAndDispose25
) {
4224
8
    flag = BLOCK_BYREF_CALLER;
4225
8
    QualType Ty = ND->getType();
4226
8
    // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4227
8
    if (Ty->isBlockPointerType())
4228
2
      flag |= BLOCK_FIELD_IS_BLOCK;
4229
8
    else
4230
6
      flag |= BLOCK_FIELD_IS_OBJECT;
4231
8
    std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
4232
8
    if (!HF.empty())
4233
5
      InsertText(FunLocStart, HF);
4234
8
  }
4235
25
  
4236
25
  // struct __Block_byref_ND ND = 
4237
25
  // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND), 
4238
25
  //  initializer-if-any};
4239
25
  bool hasInit = (ND->getInit() != nullptr);
4240
25
  unsigned flags = 0;
4241
25
  if (HasCopyAndDispose)
4242
8
    flags |= BLOCK_HAS_COPY_DISPOSE;
4243
25
  Name = ND->getNameAsString();
4244
25
  ByrefType.clear();
4245
25
  RewriteByRefString(ByrefType, Name, ND);
4246
25
  std::string ForwardingCastType("(");
4247
25
  ForwardingCastType += ByrefType + " *)";
4248
25
  if (
!hasInit25
) {
4249
5
    ByrefType += " " + Name + " = {(void*)";
4250
5
    ByrefType += utostr(isa);
4251
5
    ByrefType += "," +  ForwardingCastType + "&" + Name + ", ";
4252
5
    ByrefType += utostr(flags);
4253
5
    ByrefType += ", ";
4254
5
    ByrefType += "sizeof(";
4255
5
    RewriteByRefString(ByrefType, Name, ND);
4256
5
    ByrefType += ")";
4257
5
    if (
HasCopyAndDispose5
) {
4258
2
      ByrefType += ", __Block_byref_id_object_copy_";
4259
2
      ByrefType += utostr(flag);
4260
2
      ByrefType += ", __Block_byref_id_object_dispose_";
4261
2
      ByrefType += utostr(flag);
4262
2
    }
4263
5
    ByrefType += "};\n";
4264
5
    unsigned nameSize = Name.size();
4265
5
    // for block or function pointer declaration. Name is already
4266
5
    // part of the declaration.
4267
5
    if (
Ty->isBlockPointerType() || 5
Ty->isFunctionPointerType()3
)
4268
2
      nameSize = 1;
4269
5
    ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
4270
5
  }
4271
20
  else {
4272
20
    SourceLocation startLoc;
4273
20
    Expr *E = ND->getInit();
4274
20
    if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4275
1
      startLoc = ECE->getLParenLoc();
4276
20
    else
4277
19
      startLoc = E->getLocStart();
4278
20
    startLoc = SM->getExpansionLoc(startLoc);
4279
20
    endBuf = SM->getCharacterData(startLoc);
4280
20
    ByrefType += " " + Name;
4281
20
    ByrefType += " = {(void*)";
4282
20
    ByrefType += utostr(isa);
4283
20
    ByrefType += "," +  ForwardingCastType + "&" + Name + ", ";
4284
20
    ByrefType += utostr(flags);
4285
20
    ByrefType += ", ";
4286
20
    ByrefType += "sizeof(";
4287
20
    RewriteByRefString(ByrefType, Name, ND);
4288
20
    ByrefType += "), ";
4289
20
    if (
HasCopyAndDispose20
) {
4290
6
      ByrefType += "__Block_byref_id_object_copy_";
4291
6
      ByrefType += utostr(flag);
4292
6
      ByrefType += ", __Block_byref_id_object_dispose_";
4293
6
      ByrefType += utostr(flag);
4294
6
      ByrefType += ", ";
4295
6
    }
4296
20
    ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
4297
20
    
4298
20
    // Complete the newly synthesized compound expression by inserting a right
4299
20
    // curly brace before the end of the declaration.
4300
20
    // FIXME: This approach avoids rewriting the initializer expression. It
4301
20
    // also assumes there is only one declarator. For example, the following
4302
20
    // isn't currently supported by this routine (in general):
4303
20
    // 
4304
20
    // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4305
20
    //
4306
20
    const char *startInitializerBuf = SM->getCharacterData(startLoc);
4307
20
    const char *semiBuf = strchr(startInitializerBuf, ';');
4308
20
    assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4309
20
    SourceLocation semiLoc =
4310
20
      startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
4311
20
4312
20
    InsertText(semiLoc, "}");
4313
20
  }
4314
25
}
4315
4316
136
void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4317
136
  // Add initializers for any closure decl refs.
4318
136
  GetBlockDeclRefExprs(Exp->getBody());
4319
136
  if (
BlockDeclRefs.size()136
) {
4320
80
    // Unique all "by copy" declarations.
4321
220
    for (unsigned i = 0; 
i < BlockDeclRefs.size()220
;
i++140
)
4322
140
      
if (140
!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()140
) {
4323
84
        if (
!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())84
) {
4324
60
          BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4325
60
          BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4326
60
        }
4327
140
      }
4328
80
    // Unique all "by ref" declarations.
4329
220
    for (unsigned i = 0; 
i < BlockDeclRefs.size()220
;
i++140
)
4330
140
      
if (140
BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()140
) {
4331
56
        if (
!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())56
) {
4332
54
          BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4333
54
          BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4334
54
        }
4335
140
      }
4336
80
    // Find any imported blocks...they will need special attention.
4337
220
    for (unsigned i = 0; 
i < BlockDeclRefs.size()220
;
i++140
)
4338
140
      
if (140
BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
4339
84
          BlockDeclRefs[i]->getType()->isObjCObjectPointerType() || 
4340
38
          BlockDeclRefs[i]->getType()->isBlockPointerType())
4341
110
        ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4342
80
  }
4343
136
}
4344
4345
214
FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
4346
214
  IdentifierInfo *ID = &Context->Idents.get(name);
4347
214
  QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
4348
214
  return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4349
214
                              SourceLocation(), ID, FType, nullptr, SC_Extern,
4350
214
                              false, false);
4351
214
}
4352
4353
Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
4354
68
                     const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
4355
68
  const BlockDecl *block = Exp->getBlockDecl();
4356
68
  Blocks.push_back(Exp);
4357
68
4358
68
  CollectBlockDeclRefInfo(Exp);
4359
68
  
4360
68
  // Add inner imported variables now used in current block.
4361
68
 int countOfInnerDecls = 0;
4362
68
  if (
!InnerBlockDeclRefs.empty()68
) {
4363
136
    for (unsigned i = 0; 
i < InnerBlockDeclRefs.size()136
;
i++90
) {
4364
90
      DeclRefExpr *Exp = InnerBlockDeclRefs[i];
4365
90
      ValueDecl *VD = Exp->getDecl();
4366
90
      if (
!VD->hasAttr<BlocksAttr>() && 90
!BlockByCopyDeclsPtrSet.count(VD)54
) {
4367
12
      // We need to save the copied-in variables in nested
4368
12
      // blocks because it is needed at the end for some of the API generations.
4369
12
      // See SynthesizeBlockLiterals routine.
4370
12
        InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4371
12
        BlockDeclRefs.push_back(Exp);
4372
12
        BlockByCopyDeclsPtrSet.insert(VD);
4373
12
        BlockByCopyDecls.push_back(VD);
4374
12
      }
4375
90
      if (
VD->hasAttr<BlocksAttr>() && 90
!BlockByRefDeclsPtrSet.count(VD)36
) {
4376
9
        InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4377
9
        BlockDeclRefs.push_back(Exp);
4378
9
        BlockByRefDeclsPtrSet.insert(VD);
4379
9
        BlockByRefDecls.push_back(VD);
4380
9
      }
4381
90
    }
4382
46
    // Find any imported blocks...they will need special attention.
4383
136
    for (unsigned i = 0; 
i < InnerBlockDeclRefs.size()136
;
i++90
)
4384
90
      
if (90
InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
4385
54
          InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() || 
4386
19
          InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4387
74
        ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
4388
46
  }
4389
68
  InnerDeclRefsCount.push_back(countOfInnerDecls);
4390
68
  
4391
68
  std::string FuncName;
4392
68
4393
68
  if (CurFunctionDef)
4394
42
    FuncName = CurFunctionDef->getNameAsString();
4395
26
  else 
if (26
CurMethodDef26
)
4396
22
    BuildUniqueMethodName(FuncName, CurMethodDef);
4397
4
  else 
if (4
GlobalVarDecl4
)
4398
4
    FuncName = std::string(GlobalVarDecl->getNameAsString());
4399
68
4400
68
  std::string BlockNumber = utostr(Blocks.size()-1);
4401
68
4402
68
  std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4403
68
  std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4404
68
4405
68
  // Get a pointer to the function type so we can cast appropriately.
4406
68
  QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4407
68
  QualType FType = Context->getPointerType(BFT);
4408
68
4409
68
  FunctionDecl *FD;
4410
68
  Expr *NewRep;
4411
68
4412
68
  // Simulate a constructor call...
4413
68
  FD = SynthBlockInitFunctionDecl(Tag);
4414
68
  DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
4415
68
                                               SourceLocation());
4416
68
4417
68
  SmallVector<Expr*, 4> InitExprs;
4418
68
4419
68
  // Initialize the block function.
4420
68
  FD = SynthBlockInitFunctionDecl(Func);
4421
68
  DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4422
68
                                               VK_LValue, SourceLocation());
4423
68
  CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4424
68
                                                CK_BitCast, Arg);
4425
68
  InitExprs.push_back(castExpr);
4426
68
4427
68
  // Initialize the block descriptor.
4428
68
  std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
4429
68
4430
68
  VarDecl *NewVD = VarDecl::Create(
4431
68
      *Context, TUDecl, SourceLocation(), SourceLocation(),
4432
68
      &Context->Idents.get(DescData), Context->VoidPtrTy, nullptr, SC_Static);
4433
68
  UnaryOperator *DescRefExpr =
4434
68
    new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
4435
68
                                                          Context->VoidPtrTy,
4436
68
                                                          VK_LValue,
4437
68
                                                          SourceLocation()), 
4438
68
                                UO_AddrOf,
4439
68
                                Context->getPointerType(Context->VoidPtrTy), 
4440
68
                                VK_RValue, OK_Ordinary,
4441
68
                                SourceLocation());
4442
68
  InitExprs.push_back(DescRefExpr); 
4443
68
  
4444
68
  // Add initializers for any closure decl refs.
4445
68
  if (
BlockDeclRefs.size()68
) {
4446
47
    Expr *Exp;
4447
47
    // Output all "by copy" declarations.
4448
47
    for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
4449
89
         E = BlockByCopyDecls.end(); 
I != E89
;
++I42
) {
4450
42
      if (
isObjCType((*I)->getType())42
) {
4451
7
        // FIXME: Conform to ABI ([[obj retain] autorelease]).
4452
7
        FD = SynthBlockInitFunctionDecl((*I)->getName());
4453
7
        Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
4454
7
                                        SourceLocation());
4455
7
        if (
HasLocalVariableExternalStorage(*I)7
) {
4456
1
          QualType QT = (*I)->getType();
4457
1
          QT = Context->getPointerType(QT);
4458
1
          Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4459
1
                                            OK_Ordinary, SourceLocation());
4460
1
        }
4461
42
      } else 
if (35
isTopLevelBlockPointerType((*I)->getType())35
) {
4462
2
        FD = SynthBlockInitFunctionDecl((*I)->getName());
4463
2
        Arg = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
4464
2
                                        SourceLocation());
4465
2
        Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4466
2
                                       CK_BitCast, Arg);
4467
35
      } else {
4468
33
        FD = SynthBlockInitFunctionDecl((*I)->getName());
4469
33
        Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
4470
33
                                        SourceLocation());
4471
33
        if (
HasLocalVariableExternalStorage(*I)33
) {
4472
1
          QualType QT = (*I)->getType();
4473
1
          QT = Context->getPointerType(QT);
4474
1
          Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4475
1
                                            OK_Ordinary, SourceLocation());
4476
1
        }
4477
35
      }
4478
42
      InitExprs.push_back(Exp);
4479
42
    }
4480
47
    // Output all "by ref" declarations.
4481
47
    for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
4482
83
         E = BlockByRefDecls.end(); 
I != E83
;
++I36
) {
4483
36
      ValueDecl *ND = (*I);
4484
36
      std::string Name(ND->getNameAsString());
4485
36
      std::string RecName;
4486
36
      RewriteByRefString(RecName, Name, ND, true);
4487
36
      IdentifierInfo *II = &Context->Idents.get(RecName.c_str() 
4488
36
                                                + sizeof("struct"));
4489
36
      RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4490
36
                                          SourceLocation(), SourceLocation(),
4491
36
                                          II);
4492
36
      assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4493
36
      QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4494
36
      
4495
36
      FD = SynthBlockInitFunctionDecl((*I)->getName());
4496
36
      Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
4497
36
                                      SourceLocation());
4498
36
      bool isNestedCapturedVar = false;
4499
36
      if (block)
4500
36
        
for (const auto &CI : block->captures()) 36
{
4501
77
          const VarDecl *variable = CI.getVariable();
4502
77
          if (
variable == ND && 77
CI.isNested()35
) {
4503
9
            assert (CI.isByRef() && 
4504
9
                    "SynthBlockInitExpr - captured block variable is not byref");
4505
9
            isNestedCapturedVar = true;
4506
9
            break;
4507
9
          }
4508
36
        }
4509
36
      // captured nested byref variable has its address passed. Do not take
4510
36
      // its address again.
4511
36
      if (!isNestedCapturedVar)
4512
27
          Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
4513
27
                                     Context->getPointerType(Exp->getType()),
4514
27
                                     VK_RValue, OK_Ordinary, SourceLocation());
4515
36
      Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
4516
36
      InitExprs.push_back(Exp);
4517
36
    }
4518
47
  }
4519
68
  if (
ImportedBlockDecls.size()68
) {
4520
41
    // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4521
41
    int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
4522
41
    unsigned IntSize = 
4523
41
      static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4524
41
    Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag), 
4525
41
                                           Context->IntTy, SourceLocation());
4526
41
    InitExprs.push_back(FlagExp);
4527
41
  }
4528
68
  NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
4529
68
                                  FType, VK_LValue, SourceLocation());
4530
68
  NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
4531
68
                             Context->getPointerType(NewRep->getType()),
4532
68
                             VK_RValue, OK_Ordinary, SourceLocation());
4533
68
  NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
4534
68
                                    NewRep);
4535
68
  BlockDeclRefs.clear();
4536
68
  BlockByRefDecls.clear();
4537
68
  BlockByRefDeclsPtrSet.clear();
4538
68
  BlockByCopyDecls.clear();
4539
68
  BlockByCopyDeclsPtrSet.clear();
4540
68
  ImportedBlockDecls.clear();
4541
68
  return NewRep;
4542
68
}
4543
4544
13
bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4545
13
  if (const ObjCForCollectionStmt * CS = 
4546
13
      dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4547
11
        return CS->getElement() == DS;
4548
2
  return false;
4549
2
}
4550
4551
//===----------------------------------------------------------------------===//
4552
// Function Body / Expression rewriting
4553
//===----------------------------------------------------------------------===//
4554
4555
2.13k
Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4556
2.13k
  if (
isa<SwitchStmt>(S) || 2.13k
isa<WhileStmt>(S)2.13k
||
4557
2.13k
      
isa<DoStmt>(S)2.12k
||
isa<ForStmt>(S)2.12k
)
4558
7
    Stmts.push_back(S);
4559
2.12k
  else 
if (2.12k
isa<ObjCForCollectionStmt>(S)2.12k
) {
4560
18
    Stmts.push_back(S);
4561
18
    ObjCBcLabelNo.push_back(++BcLabelCount);
4562
18
  }
4563
2.13k
4564
2.13k
  // Pseudo-object operations and ivar references need special
4565
2.13k
  // treatment because we're going to recursively rewrite them.
4566
2.13k
  if (PseudoObjectExpr *
PseudoOp2.13k
= dyn_cast<PseudoObjectExpr>(S)) {
4567
36
    if (
isa<BinaryOperator>(PseudoOp->getSyntacticForm())36
) {
4568
14
      return RewritePropertyOrImplicitSetter(PseudoOp);
4569
0
    } else {
4570
22
      return RewritePropertyOrImplicitGetter(PseudoOp);
4571
22
    }
4572
2.09k
  } else 
if (ObjCIvarRefExpr *2.09k
IvarRefExpr2.09k
= dyn_cast<ObjCIvarRefExpr>(S)) {
4573
43
    return RewriteObjCIvarRefExpr(IvarRefExpr);
4574
43
  }
4575
2.05k
4576
2.05k
  SourceRange OrigStmtRange = S->getSourceRange();
4577
2.05k
4578
2.05k
  // Perform a bottom up rewrite of all children.
4579
2.05k
  for (Stmt *&childStmt : S->children())
4580
1.88k
    
if (1.88k
childStmt1.88k
) {
4581
1.82k
      Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
4582
1.82k
      if (
newStmt1.82k
) {
4583
1.78k
        childStmt = newStmt;
4584
1.78k
      }
4585
1.88k
    }
4586
2.05k
4587
2.05k
  if (BlockExpr *
BE2.05k
= dyn_cast<BlockExpr>(S)) {
4588
68
    SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
4589
68
    llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4590
68
    InnerContexts.insert(BE->getBlockDecl());
4591
68
    ImportedLocalExternalDecls.clear();
4592
68
    GetInnerBlockDeclRefExprs(BE->getBody(),
4593
68
                              InnerBlockDeclRefs, InnerContexts);
4594
68
    // Rewrite the block body in place.
4595
68
    Stmt *SaveCurrentBody = CurrentBody;
4596
68
    CurrentBody = BE->getBody();
4597
68
    PropParentMap = nullptr;
4598
68
    // block literal on rhs of a property-dot-sytax assignment
4599
68
    // must be replaced by its synthesize ast so getRewrittenText
4600
68
    // works as expected. In this case, what actually ends up on RHS
4601
68
    // is the blockTranscribed which is the helper function for the
4602
68
    // block literal; as in: self.c = ^() {[ace ARR];};
4603
68
    bool saveDisableReplaceStmt = DisableReplaceStmt;
4604
68
    DisableReplaceStmt = false;
4605
68
    RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4606
68
    DisableReplaceStmt = saveDisableReplaceStmt;
4607
68
    CurrentBody = SaveCurrentBody;
4608
68
    PropParentMap = nullptr;
4609
68
    ImportedLocalExternalDecls.clear();
4610
68
    // Now we snarf the rewritten text and stash it away for later use.
4611
68
    std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
4612
68
    RewrittenBlockExprs[BE] = Str;
4613
68
4614
68
    Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4615
68
                            
4616
68
    //blockTranscribed->dump();
4617
68
    ReplaceStmt(S, blockTranscribed);
4618
68
    return blockTranscribed;
4619
68
  }
4620
1.98k
  // Handle specific things.
4621
1.98k
  
if (ObjCEncodeExpr *1.98k
AtEncode1.98k
= dyn_cast<ObjCEncodeExpr>(S))
4622
3
    return RewriteAtEncode(AtEncode);
4623
1.98k
4624
1.98k
  
if (ObjCSelectorExpr *1.98k
AtSelector1.98k
= dyn_cast<ObjCSelectorExpr>(S))
4625
1
    return RewriteAtSelector(AtSelector);
4626
1.98k
4627
1.98k
  
if (ObjCStringLiteral *1.98k
AtString1.98k
= dyn_cast<ObjCStringLiteral>(S))
4628
18
    return RewriteObjCStringLiteral(AtString);
4629
1.96k
4630
1.96k
  
if (ObjCMessageExpr *1.96k
MessExpr1.96k
= dyn_cast<ObjCMessageExpr>(S)) {
4631
#if 0
4632
    // Before we rewrite it, put the original message expression in a comment.
4633
    SourceLocation startLoc = MessExpr->getLocStart();
4634
    SourceLocation endLoc = MessExpr->getLocEnd();
4635
4636
    const char *startBuf = SM->getCharacterData(startLoc);
4637
    const char *endBuf = SM->getCharacterData(endLoc);
4638
4639
    std::string messString;
4640
    messString += "// ";
4641
    messString.append(startBuf, endBuf-startBuf+1);
4642
    messString += "\n";
4643
4644
    // FIXME: Missing definition of
4645
    // InsertText(clang::SourceLocation, char const*, unsigned int).
4646
    // InsertText(startLoc, messString);
4647
    // Tried this, but it didn't work either...
4648
    // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
4649
#endif
4650
    return RewriteMessageExpr(MessExpr);
4651
79
  }
4652
1.88k
4653
1.88k
  
if (ObjCAtTryStmt *1.88k
StmtTry1.88k
= dyn_cast<ObjCAtTryStmt>(S))
4654
8
    return RewriteObjCTryStmt(StmtTry);
4655
1.87k
4656
1.87k
  
if (ObjCAtSynchronizedStmt *1.87k
StmtTry1.87k
= dyn_cast<ObjCAtSynchronizedStmt>(S))
4657
3
    return RewriteObjCSynchronizedStmt(StmtTry);
4658
1.87k
4659
1.87k
  
if (ObjCAtThrowStmt *1.87k
StmtThrow1.87k
= dyn_cast<ObjCAtThrowStmt>(S))
4660
2
    return RewriteObjCThrowStmt(StmtThrow);
4661
1.87k
4662
1.87k
  
if (ObjCProtocolExpr *1.87k
ProtocolExp1.87k
= dyn_cast<ObjCProtocolExpr>(S))
4663
0
    return RewriteObjCProtocolExpr(ProtocolExp);
4664
1.87k
4665
1.87k
  
if (ObjCForCollectionStmt *1.87k
StmtForCollection1.87k
=
4666
1.87k
        dyn_cast<ObjCForCollectionStmt>(S))
4667
18
    return RewriteObjCForCollectionStmt(StmtForCollection,
4668
18
                                        OrigStmtRange.getEnd());
4669
1.85k
  
if (BreakStmt *1.85k
StmtBreakStmt1.85k
=
4670
1.85k
      dyn_cast<BreakStmt>(S))
4671
6
    return RewriteBreakStmt(StmtBreakStmt);
4672
1.84k
  
if (ContinueStmt *1.84k
StmtContinueStmt1.84k
=
4673
1.84k
      dyn_cast<ContinueStmt>(S))
4674
2
    return RewriteContinueStmt(StmtContinueStmt);
4675
1.84k
4676
1.84k
  // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4677
1.84k
  // and cast exprs.
4678
1.84k
  
if (DeclStmt *1.84k
DS1.84k
= dyn_cast<DeclStmt>(S)) {
4679
141
    // FIXME: What we're doing here is modifying the type-specifier that
4680
141
    // precedes the first Decl.  In the future the DeclGroup should have
4681
141
    // a separate type-specifier that we can rewrite.
4682
141
    // NOTE: We need to avoid rewriting the DeclStmt if it is within
4683
141
    // the context of an ObjCForCollectionStmt. For example:
4684
141
    //   NSArray *someArray;
4685
141
    //   for (id <FooProtocol> index in someArray) ;
4686
141
    // This is because RewriteObjCForCollectionStmt() does textual rewriting 
4687
141
    // and it depends on the original text locations/positions.
4688
141
    if (
Stmts.empty() || 141
!IsDeclStmtInForeachHeader(DS)13
)
4689
132
      RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4690
141
4691
141
    // Blocks rewrite rules.
4692
144
    for (auto *SD : DS->decls()) {
4693
144
      if (ValueDecl *
ND144
= dyn_cast<ValueDecl>(SD)) {
4694
144
        if (isTopLevelBlockPointerType(ND->getType()))
4695
21
          RewriteBlockPointerDecl(ND);
4696
123
        else 
if (123
ND->getType()->isFunctionPointerType()123
)
4697
1
          CheckFunctionPointerDecl(ND->getType(), ND);
4698
144
        if (VarDecl *
VD144
= dyn_cast<VarDecl>(SD)) {
4699
144
          if (
VD->hasAttr<BlocksAttr>()144
) {
4700
25
            static unsigned uniqueByrefDeclCount = 0;
4701
25
            assert(!BlockByRefDeclNo.count(ND) &&
4702
25
              "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4703
25
            BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
4704
25
            RewriteByRefVar(VD);
4705
25
          }
4706
144
          else           
4707
119
            RewriteTypeOfDecl(VD);
4708
144
        }
4709
144
      }
4710
144
      if (TypedefNameDecl *
TD144
= dyn_cast<TypedefNameDecl>(SD)) {
4711
0
        if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4712
0
          RewriteBlockPointerDecl(TD);
4713
0
        else 
if (0
TD->getUnderlyingType()->isFunctionPointerType()0
)
4714
0
          CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4715
0
      }
4716
144
    }
4717
141
  }
4718
1.84k
4719
1.84k
  if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4720
31
    RewriteObjCQualifiedInterfaceTypes(CE);
4721
1.84k
4722
1.84k
  if (
isa<SwitchStmt>(S) || 1.84k
isa<WhileStmt>(S)1.84k
||
4723
1.84k
      
isa<DoStmt>(S)1.84k
||
isa<ForStmt>(S)1.84k
) {
4724
7
    assert(!Stmts.empty() && "Statement stack is empty");
4725
7
    assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4726
7
             isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4727
7
            && "Statement stack mismatch");
4728
7
    Stmts.pop_back();
4729
7
  }
4730
1.84k
  // Handle blocks rewriting.
4731
1.84k
  if (DeclRefExpr *
DRE1.84k
= dyn_cast<DeclRefExpr>(S)) {
4732
369
    ValueDecl *VD = DRE->getDecl(); 
4733
369
    if (VD->hasAttr<BlocksAttr>())
4734
35
      return RewriteBlockDeclRefExpr(DRE);
4735
334
    
if (334
HasLocalVariableExternalStorage(VD)334
)
4736
15
      return RewriteLocalVariableExternalStorage(DRE);
4737
1.79k
  }
4738
1.79k
  
4739
1.79k
  
if (CallExpr *1.79k
CE1.79k
= dyn_cast<CallExpr>(S)) {
4740
119
    if (
CE->getCallee()->getType()->isBlockPointerType()119
) {
4741
14
      Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
4742
14
      ReplaceStmt(S, BlockCall);
4743
14
      return BlockCall;
4744
14
    }
4745
1.78k
  }
4746
1.78k
  
if (CStyleCastExpr *1.78k
CE1.78k
= dyn_cast<CStyleCastExpr>(S)) {
4747
31
    RewriteCastExpr(CE);
4748
31
  }
4749
#if 0
4750
  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4751
    CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4752
                                                   ICE->getSubExpr(),
4753
                                                   SourceLocation());
4754
    // Get the new text.
4755
    std::string SStr;
4756
    llvm::raw_string_ostream Buf(SStr);
4757
    Replacement->printPretty(Buf);
4758
    const std::string &Str = Buf.str();
4759
4760
    printf("CAST = %s\n", &Str[0]);
4761
    InsertText(ICE->getSubExpr()->getLocStart(), Str);
4762
    delete S;
4763
    return Replacement;
4764
  }
4765
#endif
4766
  // Return this stmt unmodified.
4767
2.13k
  return S;
4768
2.13k
}
4769
4770
11
void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
4771
18
  for (auto *FD : RD->fields()) {
4772
18
    if (isTopLevelBlockPointerType(FD->getType()))
4773
0
      RewriteBlockPointerDecl(FD);
4774
18
    if (FD->getType()->isObjCQualifiedIdType() ||
4775
17
        FD->getType()->isObjCQualifiedInterfaceType())
4776
1
      RewriteObjCQualifiedInterfaceTypes(FD);
4777
18
  }
4778
11
}
4779
4780
/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4781
/// main file of the input.
4782
522
void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4783
522
  switch (D->getKind()) {
4784
136
    case Decl::Function: {
4785
136
      FunctionDecl *FD = cast<FunctionDecl>(D);
4786
136
      if (FD->isOverloadedOperator())
4787
0
        return;
4788
136
4789
136
      // Since function prototypes don't have ParmDecl's, we check the function
4790
136
      // prototype. This enables us to rewrite function declarations and
4791
136
      // definitions using the same code.
4792
136
      RewriteBlocksInFunctionProtoType(FD->getType(), FD);
4793
136
4794
136
      if (!FD->isThisDeclarationADefinition())
4795
72
        break;
4796
64
4797
64
      // FIXME: If this should support Obj-C++, support CXXTryStmt
4798
64
      
if (CompoundStmt *64
Body64
= dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4799
64
        CurFunctionDef = FD;
4800
64
        CurFunctionDeclToDeclareForBlock = FD;
4801
64
        CurrentBody = Body;
4802
64
        Body =
4803
64
        cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4804
64
        FD->setBody(Body);
4805
64
        CurrentBody = nullptr;
4806
64
        if (
PropParentMap64
) {
4807
0
          delete PropParentMap;
4808
0
          PropParentMap = nullptr;
4809
0
        }
4810
64
        // This synthesizes and inserts the block "impl" struct, invoke function,
4811
64
        // and any copy/dispose helper functions.
4812
64
        InsertBlockLiteralsWithinFunction(FD);
4813
64
        CurFunctionDef = nullptr;
4814
64
        CurFunctionDeclToDeclareForBlock = nullptr;
4815
64
      }
4816
64
      break;
4817
64
    }
4818
77
    case Decl::ObjCMethod: {
4819
77
      ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
4820
77
      if (CompoundStmt *
Body77
= MD->getCompoundBody()) {
4821
77
        CurMethodDef = MD;
4822
77
        CurrentBody = Body;
4823
77
        Body =
4824
77
          cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4825
77
        MD->setBody(Body);
4826
77
        CurrentBody = nullptr;
4827
77
        if (
PropParentMap77
) {
4828
0
          delete PropParentMap;
4829
0
          PropParentMap = nullptr;
4830
0
        }
4831
77
        InsertBlockLiteralsWithinMethod(MD);
4832
77
        CurMethodDef = nullptr;
4833
77
      }
4834
77
      break;
4835
64
    }
4836
64
    case Decl::ObjCImplementation: {
4837
64
      ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
4838
64
      ClassImplementation.push_back(CI);
4839
64
      break;
4840
64
    }
4841
6
    case Decl::ObjCCategoryImpl: {
4842
6
      ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
4843
6
      CategoryImplementation.push_back(CI);
4844
6
      break;
4845
64
    }
4846
17
    case Decl::Var: {
4847
17
      VarDecl *VD = cast<VarDecl>(D);
4848
17
      RewriteObjCQualifiedInterfaceTypes(VD);
4849
17
      if (isTopLevelBlockPointerType(VD->getType()))
4850
4
        RewriteBlockPointerDecl(VD);
4851
13
      else 
if (13
VD->getType()->isFunctionPointerType()13
) {
4852
0
        CheckFunctionPointerDecl(VD->getType(), VD);
4853
0
        if (
VD->getInit()0
) {
4854
0
          if (CStyleCastExpr *
CE0
= dyn_cast<CStyleCastExpr>(VD->getInit())) {
4855
0
            RewriteCastExpr(CE);
4856
0
          }
4857
0
        }
4858
13
      } else 
if (13
VD->getType()->isRecordType()13
) {
4859
0
        RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4860
0
        if (RD->isCompleteDefinition())
4861
0
          RewriteRecordBody(RD);
4862
13
      }
4863
17
      if (
VD->getInit()17
) {
4864
9
        GlobalVarDecl = VD;
4865
9
        CurrentBody = VD->getInit();
4866
9
        RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
4867
9
        CurrentBody = nullptr;
4868
9
        if (
PropParentMap9
) {
4869
0
          delete PropParentMap;
4870
0
          PropParentMap = nullptr;
4871
0
        }
4872
9
        SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
4873
9
        GlobalVarDecl = nullptr;
4874
9
4875
9
        // This is needed for blocks.
4876
9
        if (CStyleCastExpr *
CE9
= dyn_cast<CStyleCastExpr>(VD->getInit())) {
4877
0
            RewriteCastExpr(CE);
4878
0
        }
4879
9
      }
4880
17
      break;
4881
64
    }
4882
50
    case Decl::TypeAlias:
4883
50
    case Decl::Typedef: {
4884
50
      if (TypedefNameDecl *
TD50
= dyn_cast<TypedefNameDecl>(D)) {
4885
50
        if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4886
20
          RewriteBlockPointerDecl(TD);
4887
30
        else 
if (30
TD->getUnderlyingType()->isFunctionPointerType()30
)
4888
0
          CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4889
50
      }
4890
50
      break;
4891
50
    }
4892
14
    case Decl::CXXRecord:
4893
14
    case Decl::Record: {
4894
14
      RecordDecl *RD = cast<RecordDecl>(D);
4895
14
      if (RD->isCompleteDefinition()) 
4896
11
        RewriteRecordBody(RD);
4897
14
      break;
4898
14
    }
4899
158
    default:
4900
158
      break;
4901
522
  }
4902
522
  // Nothing yet.
4903
522
}
4904
4905
86
void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
4906
86
  if (Diags.hasErrorOccurred())
4907
0
    return;
4908
86
4909
86
  RewriteInclude();
4910
86
4911
86
  // Here's a great place to add any extra declarations that may be needed.
4912
86
  // Write out meta data for each @protocol(<expr>).
4913
86
  for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls)
4914
0
    RewriteObjCProtocolMetaData(ProtDecl, "", "", Preamble);
4915
86
4916
86
  InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
4917
86
  if (
ClassImplementation.size() || 86
CategoryImplementation.size()33
)
4918
53
    RewriteImplementations();
4919
86
4920
86
  // Get the buffer corresponding to MainFileID.  If we haven't changed it, then
4921
86
  // we are done.
4922
86
  if (const RewriteBuffer *RewriteBuf =
4923
86
      Rewrite.getRewriteBufferFor(MainFileID)) {
4924
86
    //printf("Changed:\n");
4925
86
    *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4926
86
  } else {
4927
0
    llvm::errs() << "No changes\n";
4928
0
  }
4929
86
4930
86
  if (
ClassImplementation.size() || 86
CategoryImplementation.size()33
||
4931
86
      
ProtocolExprDecls.size()33
) {
4932
53
    // Rewrite Objective-c meta data*
4933
53
    std::string ResultStr;
4934
53
    RewriteMetaDataIntoBuffer(ResultStr);
4935
53
    // Emit metadata.
4936
53
    *OutFile << ResultStr;
4937
53
  }
4938
86
  OutFile->flush();
4939
86
}
4940
4941
86
void RewriteObjCFragileABI::Initialize(ASTContext &context) {
4942
86
  InitializeCommon(context);
4943
86
  
4944
86
  // declaring objc_selector outside the parameter list removes a silly
4945
86
  // scope related warning...
4946
86
  if (IsHeader)
4947
0
    Preamble = "#pragma once\n";
4948
86
  Preamble += "struct objc_selector; struct objc_class;\n";
4949
86
  Preamble += "struct __rw_objc_super { struct objc_object *object; ";
4950
86
  Preamble += "struct objc_object *superClass; ";
4951
86
  if (
LangOpts.MicrosoftExt86
) {
4952
51
    // Add a constructor for creating temporary objects.
4953
51
    Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
4954
51
    ": ";
4955
51
    Preamble += "object(o), superClass(s) {} ";
4956
51
  }
4957
86
  Preamble += "};\n";
4958
86
  Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
4959
86
  Preamble += "typedef struct objc_object Protocol;\n";
4960
86
  Preamble += "#define _REWRITER_typedef_Protocol\n";
4961
86
  Preamble += "#endif\n";
4962
86
  if (
LangOpts.MicrosoftExt86
) {
4963
51
    Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
4964
51
    Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
4965
51
  } else
4966
35
    Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
4967
86
  Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
4968
86
  Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
4969
86
  Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
4970
86
  Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
4971
86
  Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
4972
86
  Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
4973
86
  Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
4974
86
  Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
4975
86
  Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
4976
86
  Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
4977
86
  Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
4978
86
  Preamble += "(const char *);\n";
4979
86
  Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
4980
86
  Preamble += "(struct objc_class *);\n";
4981
86
  Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
4982
86
  Preamble += "(const char *);\n";
4983
86
  Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
4984
86
  Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
4985
86
  Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
4986
86
  Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
4987
86
  Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
4988
86
  Preamble += "(struct objc_class *, struct objc_object *);\n";
4989
86
  // @synchronized hooks.
4990
86
  Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter(struct objc_object *);\n";
4991
86
  Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit(struct objc_object *);\n";
4992
86
  Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
4993
86
  Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
4994
86
  Preamble += "struct __objcFastEnumerationState {\n\t";
4995
86
  Preamble += "unsigned long state;\n\t";
4996
86
  Preamble += "void **itemsPtr;\n\t";
4997
86
  Preamble += "unsigned long *mutationsPtr;\n\t";
4998
86
  Preamble += "unsigned long extra[5];\n};\n";
4999
86
  Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5000
86
  Preamble += "#define __FASTENUMERATIONSTATE\n";
5001
86
  Preamble += "#endif\n";
5002
86
  Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5003
86
  Preamble += "struct __NSConstantStringImpl {\n";
5004
86
  Preamble += "  int *isa;\n";
5005
86
  Preamble += "  int flags;\n";
5006
86
  Preamble += "  char *str;\n";
5007
86
  Preamble += "  long length;\n";
5008
86
  Preamble += "};\n";
5009
86
  Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5010
86
  Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5011
86
  Preamble += "#else\n";
5012
86
  Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5013
86
  Preamble += "#endif\n";
5014
86
  Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5015
86
  Preamble += "#endif\n";
5016
86
  // Blocks preamble.
5017
86
  Preamble += "#ifndef BLOCK_IMPL\n";
5018
86
  Preamble += "#define BLOCK_IMPL\n";
5019
86
  Preamble += "struct __block_impl {\n";
5020
86
  Preamble += "  void *isa;\n";
5021
86
  Preamble += "  int Flags;\n";
5022
86
  Preamble += "  int Reserved;\n";
5023
86
  Preamble += "  void *FuncPtr;\n";
5024
86
  Preamble += "};\n";
5025
86
  Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5026
86
  Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5027
86
  Preamble += "extern \"C\" __declspec(dllexport) "
5028
86
  "void _Block_object_assign(void *, const void *, const int);\n";
5029
86
  Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5030
86
  Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5031
86
  Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5032
86
  Preamble += "#else\n";
5033
86
  Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5034
86
  Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5035
86
  Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5036
86
  Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5037
86
  Preamble += "#endif\n";
5038
86
  Preamble += "#endif\n";
5039
86
  if (
LangOpts.MicrosoftExt86
) {
5040
51
    Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5041
51
    Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5042
51
    Preamble += "#ifndef KEEP_ATTRIBUTES\n";  // We use this for clang tests.
5043
51
    Preamble += "#define __attribute__(X)\n";
5044
51
    Preamble += "#endif\n";
5045
51
    Preamble += "#define __weak\n";
5046
51
  }
5047
35
  else {
5048
35
    Preamble += "#define __block\n";
5049
35
    Preamble += "#define __weak\n";
5050
35
  }
5051
86
  // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5052
86
  // as this avoids warning in any 64bit/32bit compilation model.
5053
86
  Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5054
86
}
5055
5056
/// RewriteIvarOffsetComputation - This routine synthesizes computation of
5057
/// ivar offset.
5058
void RewriteObjCFragileABI::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5059
57
                                                         std::string &Result) {
5060
57
  if (
ivar->isBitField()57
) {
5061
0
    // FIXME: The hack below doesn't work for bitfields. For now, we simply
5062
0
    // place all bitfields at offset 0.
5063
0
    Result += "0";
5064
57
  } else {
5065
57
    Result += "__OFFSETOFIVAR__(struct ";
5066
57
    Result += ivar->getContainingInterface()->getNameAsString();
5067
57
    if (LangOpts.MicrosoftExt)
5068
42
      Result += "_IMPL";
5069
57
    Result += ", ";
5070
57
    Result += ivar->getNameAsString();
5071
57
    Result += ")";
5072
57
  }
5073
57
}
5074
5075
/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
5076
void RewriteObjCFragileABI::RewriteObjCProtocolMetaData(
5077
                            ObjCProtocolDecl *PDecl, StringRef prefix,
5078
3
                            StringRef ClassName, std::string &Result) {
5079
3
  static bool objc_protocol_methods = false;
5080
3
  
5081
3
  // Output struct protocol_methods holder of method selector and type.
5082
3
  if (
!objc_protocol_methods && 3
PDecl->hasDefinition()3
) {
5083
3
    /* struct protocol_methods {
5084
3
     SEL _cmd;
5085
3
     char *method_types;
5086
3
     }
5087
3
     */
5088
3
    Result += "\nstruct _protocol_methods {\n";
5089
3
    Result += "\tstruct objc_selector *_cmd;\n";
5090
3
    Result += "\tchar *method_types;\n";
5091
3
    Result += "};\n";
5092
3
    
5093
3
    objc_protocol_methods = true;
5094
3
  }
5095
3
  // Do not synthesize the protocol more than once.
5096
3
  if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
5097
0
    return;
5098
3
  
5099
3
  
if (ObjCProtocolDecl *3
Def3
= PDecl->getDefinition())
5100
3
    PDecl = Def;
5101
3
  
5102
3
  if (
PDecl->instmeth_begin() != PDecl->instmeth_end()3
) {
5103
3
    unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
5104
3
                                        PDecl->instmeth_end());
5105
3
    /* struct _objc_protocol_method_list {
5106
3
     int protocol_method_count;
5107
3
     struct protocol_methods protocols[];
5108
3
     }
5109
3
     */
5110
3
    Result += "\nstatic struct {\n";
5111
3
    Result += "\tint protocol_method_count;\n";
5112
3
    Result += "\tstruct _protocol_methods protocol_methods[";
5113
3
    Result += utostr(NumMethods);
5114
3
    Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
5115
3
    Result += PDecl->getNameAsString();
5116
3
    Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
5117
3
    "{\n\t" + utostr(NumMethods) + "\n";
5118
3
    
5119
3
    // Output instance methods declared in this protocol.
5120
3
    for (ObjCProtocolDecl::instmeth_iterator
5121
3
         I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
5122
7
         
I != E7
;
++I4
) {
5123
4
      if (I == PDecl->instmeth_begin())
5124
3
        Result += "\t  ,{{(struct objc_selector *)\"";
5125
4
      else
5126
1
        Result += "\t  ,{(struct objc_selector *)\"";
5127
4
      Result += (*I)->getSelector().getAsString();
5128
4
      std::string MethodTypeString = Context->getObjCEncodingForMethodDecl(*I);
5129
4
      Result += "\", \"";
5130
4
      Result += MethodTypeString;
5131
4
      Result += "\"}\n";
5132
4
    }
5133
3
    Result += "\t }\n};\n";
5134
3
  }
5135
3
  
5136
3
  // Output class methods declared in this protocol.
5137
3
  unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
5138
3
                                      PDecl->classmeth_end());
5139
3
  if (
NumMethods > 03
) {
5140
1
    /* struct _objc_protocol_method_list {
5141
1
     int protocol_method_count;
5142
1
     struct protocol_methods protocols[];
5143
1
     }
5144
1
     */
5145
1
    Result += "\nstatic struct {\n";
5146
1
    Result += "\tint protocol_method_count;\n";
5147
1
    Result += "\tstruct _protocol_methods protocol_methods[";
5148
1
    Result += utostr(NumMethods);
5149
1
    Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
5150
1
    Result += PDecl->getNameAsString();
5151
1
    Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5152
1
    "{\n\t";
5153
1
    Result += utostr(NumMethods);
5154
1
    Result += "\n";
5155
1
    
5156
1
    // Output instance methods declared in this protocol.
5157
1
    for (ObjCProtocolDecl::classmeth_iterator
5158
1
         I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
5159
2
         
I != E2
;
++I1
) {
5160
1
      if (I == PDecl->classmeth_begin())
5161
1
        Result += "\t  ,{{(struct objc_selector *)\"";
5162
1
      else
5163
0
        Result += "\t  ,{(struct objc_selector *)\"";
5164
1
      Result += (*I)->getSelector().getAsString();
5165
1
      std::string MethodTypeString = Context->getObjCEncodingForMethodDecl(*I);
5166
1
      Result += "\", \"";
5167
1
      Result += MethodTypeString;
5168
1
      Result += "\"}\n";
5169
1
    }
5170
1
    Result += "\t }\n};\n";
5171
1
  }
5172
3
  
5173
3
  // Output:
5174
3
  /* struct _objc_protocol {
5175
3
   // Objective-C 1.0 extensions
5176
3
   struct _objc_protocol_extension *isa;
5177
3
   char *protocol_name;
5178
3
   struct _objc_protocol **protocol_list;
5179
3
   struct _objc_protocol_method_list *instance_methods;
5180
3
   struct _objc_protocol_method_list *class_methods;
5181
3
   };
5182
3
   */
5183
3
  static bool objc_protocol = false;
5184
3
  if (
!objc_protocol3
) {
5185
3
    Result += "\nstruct _objc_protocol {\n";
5186
3
    Result += "\tstruct _objc_protocol_extension *isa;\n";
5187
3
    Result += "\tchar *protocol_name;\n";
5188
3
    Result += "\tstruct _objc_protocol **protocol_list;\n";
5189
3
    Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
5190
3
    Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
5191
3
    Result += "};\n";
5192
3
    
5193
3
    objc_protocol = true;
5194
3
  }
5195
3
  
5196
3
  Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
5197
3
  Result += PDecl->getNameAsString();
5198
3
  Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
5199
3
  "{\n\t0, \"";
5200
3
  Result += PDecl->getNameAsString();
5201
3
  Result += "\", 0, ";
5202
3
  if (
PDecl->instmeth_begin() != PDecl->instmeth_end()3
) {
5203
3
    Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
5204
3
    Result += PDecl->getNameAsString();
5205
3
    Result += ", ";
5206
3
  }
5207
3
  else
5208
0
    Result += "0, ";
5209
3
  if (
PDecl->classmeth_begin() != PDecl->classmeth_end()3
) {
5210
1
    Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
5211
1
    Result += PDecl->getNameAsString();
5212
1
    Result += "\n";
5213
1
  }
5214
3
  else
5215
2
    Result += "0\n";
5216
3
  Result += "};\n";
5217
3
  
5218
3
  // Mark this protocol as having been generated.
5219
3
  if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()).second)
5220
0
    llvm_unreachable("protocol already synthesized");
5221
3
}
5222
5223
void RewriteObjCFragileABI::RewriteObjCProtocolListMetaData(
5224
                                const ObjCList<ObjCProtocolDecl> &Protocols,
5225
                                StringRef prefix, StringRef ClassName,
5226
70
                                std::string &Result) {
5227
70
  if (
Protocols.empty()70
)
return67
;
5228
3
  
5229
6
  
for (unsigned i = 0; 3
i != Protocols.size()6
;
i++3
)
5230
3
    RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
5231
3
  
5232
3
  // Output the top lovel protocol meta-data for the class.
5233
3
  /* struct _objc_protocol_list {
5234
3
   struct _objc_protocol_list *next;
5235
3
   int    protocol_count;
5236
3
   struct _objc_protocol *class_protocols[];
5237
3
   }
5238
3
   */
5239
3
  Result += "\nstatic struct {\n";
5240
3
  Result += "\tstruct _objc_protocol_list *next;\n";
5241
3
  Result += "\tint    protocol_count;\n";
5242
3
  Result += "\tstruct _objc_protocol *class_protocols[";
5243
3
  Result += utostr(Protocols.size());
5244
3
  Result += "];\n} _OBJC_";
5245
3
  Result += prefix;
5246
3
  Result += "_PROTOCOLS_";
5247
3
  Result += ClassName;
5248
3
  Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5249
3
  "{\n\t0, ";
5250
3
  Result += utostr(Protocols.size());
5251
3
  Result += "\n";
5252
3
  
5253
3
  Result += "\t,{&_OBJC_PROTOCOL_";
5254
3
  Result += Protocols[0]->getNameAsString();
5255
3
  Result += " \n";
5256
3
  
5257
3
  for (unsigned i = 1; 
i != Protocols.size()3
;
i++0
) {
5258
0
    Result += "\t ,&_OBJC_PROTOCOL_";
5259
0
    Result += Protocols[i]->getNameAsString();
5260
0
    Result += "\n";
5261
0
  }
5262
70
  Result += "\t }\n};\n";
5263
70
}
5264
5265
void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
5266
64
                                           std::string &Result) {
5267
64
  ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
5268
64
  
5269
64
  // Explicitly declared @interface's are already synthesized.
5270
64
  if (
CDecl->isImplicitInterfaceDecl()64
) {
5271
2
    // FIXME: Implementation of a class with no @interface (legacy) does not
5272
2
    // produce correct synthesis as yet.
5273
2
    RewriteObjCInternalStruct(CDecl, Result);
5274
2
  }
5275
64
  
5276
64
  // Build _objc_ivar_list metadata for classes ivars if needed
5277
64
  unsigned NumIvars = !IDecl->ivar_empty()
5278
1
  ? IDecl->ivar_size()
5279
63
  : 
(CDecl ? 63
CDecl->ivar_size()63
:
00
);
5280
64
  if (
NumIvars > 064
) {
5281
31
    static bool objc_ivar = false;
5282
31
    if (
!objc_ivar31
) {
5283
28
      /* struct _objc_ivar {
5284
28
       char *ivar_name;
5285
28
       char *ivar_type;
5286
28
       int ivar_offset;
5287
28
       };
5288
28
       */
5289
28
      Result += "\nstruct _objc_ivar {\n";
5290
28
      Result += "\tchar *ivar_name;\n";
5291
28
      Result += "\tchar *ivar_type;\n";
5292
28
      Result += "\tint ivar_offset;\n";
5293
28
      Result += "};\n";
5294
28
      
5295
28
      objc_ivar = true;
5296
28
    }
5297
31
    
5298
31
    /* struct {
5299
31
     int ivar_count;
5300
31
     struct _objc_ivar ivar_list[nIvars];
5301
31
     };
5302
31
     */
5303
31
    Result += "\nstatic struct {\n";
5304
31
    Result += "\tint ivar_count;\n";
5305
31
    Result += "\tstruct _objc_ivar ivar_list[";
5306
31
    Result += utostr(NumIvars);
5307
31
    Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
5308
31
    Result += IDecl->getNameAsString();
5309
31
    Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
5310
31
    "{\n\t";
5311
31
    Result += utostr(NumIvars);
5312
31
    Result += "\n";
5313
31
    
5314
31
    ObjCInterfaceDecl::ivar_iterator IVI, IVE;
5315
31
    SmallVector<ObjCIvarDecl *, 8> IVars;
5316
31
    if (
!IDecl->ivar_empty()31
) {
5317
1
      for (auto *IV : IDecl->ivars())
5318
4
        IVars.push_back(IV);
5319
1
      IVI = IDecl->ivar_begin();
5320
1
      IVE = IDecl->ivar_end();
5321
31
    } else {
5322
30
      IVI = CDecl->ivar_begin();
5323
30
      IVE = CDecl->ivar_end();
5324
30
    }
5325
31
    Result += "\t,{{\"";
5326
31
    Result += IVI->getNameAsString();
5327
31
    Result += "\", \"";
5328
31
    std::string TmpString, StrEncoding;
5329
31
    Context->getObjCEncodingForType(IVI->getType(), TmpString, *IVI);
5330
31
    QuoteDoublequotes(TmpString, StrEncoding);
5331
31
    Result += StrEncoding;
5332
31
    Result += "\", ";
5333
31
    RewriteIvarOffsetComputation(*IVI, Result);
5334
31
    Result += "}\n";
5335
43
    for (++IVI; 
IVI != IVE43
;
++IVI12
) {
5336
12
      Result += "\t  ,{\"";
5337
12
      Result += IVI->getNameAsString();
5338
12
      Result += "\", \"";
5339
12
      std::string TmpString, StrEncoding;
5340
12
      Context->getObjCEncodingForType(IVI->getType(), TmpString, *IVI);
5341
12
      QuoteDoublequotes(TmpString, StrEncoding);
5342
12
      Result += StrEncoding;
5343
12
      Result += "\", ";
5344
12
      RewriteIvarOffsetComputation(*IVI, Result);
5345
12
      Result += "}\n";
5346
12
    }
5347
31
    
5348
31
    Result += "\t }\n};\n";
5349
31
  }
5350
64
  
5351
64
  // Build _objc_method_list for class's instance methods if needed
5352
64
  SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
5353
64
  
5354
64
  // If any of our property implementations have associated getters or
5355
64
  // setters, produce metadata for them as well.
5356
12
  for (const auto *Prop : IDecl->property_impls()) {
5357
12
    if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5358
2
      continue;
5359
10
    
if (10
!Prop->getPropertyIvarDecl()10
)
5360
0
      continue;
5361
10
    ObjCPropertyDecl *PD = Prop->getPropertyDecl();
5362
10
    if (!PD)
5363
0
      continue;
5364
10
    
if (ObjCMethodDecl *10
Getter10
= PD->getGetterMethodDecl())
5365
10
      
if (10
!Getter->isDefined()10
)
5366
9
        InstanceMethods.push_back(Getter);
5367
10
    if (PD->isReadOnly())
5368
1
      continue;
5369
9
    
if (ObjCMethodDecl *9
Setter9
= PD->getSetterMethodDecl())
5370
9
      
if (9
!Setter->isDefined()9
)
5371
8
        InstanceMethods.push_back(Setter);
5372
12
  }
5373
64
  RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5374
64
                             true, "", IDecl->getName(), Result);
5375
64
  
5376
64
  // Build _objc_method_list for class's class methods if needed
5377
64
  RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5378
64
                             false, "", IDecl->getName(), Result);
5379
64
  
5380
64
  // Protocols referenced in class declaration?
5381
64
  RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
5382
64
                                  "CLASS", CDecl->getName(), Result);
5383
64
  
5384
64
  // Declaration of class/meta-class metadata
5385
64
  /* struct _objc_class {
5386
64
   struct _objc_class *isa; // or const char *root_class_name when metadata
5387
64
   const char *super_class_name;
5388
64
   char *name;
5389
64
   long version;
5390
64
   long info;
5391
64
   long instance_size;
5392
64
   struct _objc_ivar_list *ivars;
5393
64
   struct _objc_method_list *methods;
5394
64
   struct objc_cache *cache;
5395
64
   struct objc_protocol_list *protocols;
5396
64
   const char *ivar_layout;
5397
64
   struct _objc_class_ext  *ext;
5398
64
   };
5399
64
   */
5400
64
  static bool objc_class = false;
5401
64
  if (
!objc_class64
) {
5402
53
    Result += "\nstruct _objc_class {\n";
5403
53
    Result += "\tstruct _objc_class *isa;\n";
5404
53
    Result += "\tconst char *super_class_name;\n";
5405
53
    Result += "\tchar *name;\n";
5406
53
    Result += "\tlong version;\n";
5407
53
    Result += "\tlong info;\n";
5408
53
    Result += "\tlong instance_size;\n";
5409
53
    Result += "\tstruct _objc_ivar_list *ivars;\n";
5410
53
    Result += "\tstruct _objc_method_list *methods;\n";
5411
53
    Result += "\tstruct objc_cache *cache;\n";
5412
53
    Result += "\tstruct _objc_protocol_list *protocols;\n";
5413
53
    Result += "\tconst char *ivar_layout;\n";
5414
53
    Result += "\tstruct _objc_class_ext  *ext;\n";
5415
53
    Result += "};\n";
5416
53
    objc_class = true;
5417
53
  }
5418
64
  
5419
64
  // Meta-class metadata generation.
5420
64
  ObjCInterfaceDecl *RootClass = nullptr;
5421
64
  ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
5422
76
  while (
SuperClass76
) {
5423
12
    RootClass = SuperClass;
5424
12
    SuperClass = SuperClass->getSuperClass();
5425
12
  }
5426
64
  SuperClass = CDecl->getSuperClass();
5427
64
  
5428
64
  Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
5429
64
  Result += CDecl->getNameAsString();
5430
64
  Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
5431
64
  "{\n\t(struct _objc_class *)\"";
5432
64
  Result += (RootClass ? 
RootClass->getNameAsString()12
:
CDecl->getNameAsString()52
);
5433
64
  Result += "\"";
5434
64
  
5435
64
  if (
SuperClass64
) {
5436
12
    Result += ", \"";
5437
12
    Result += SuperClass->getNameAsString();
5438
12
    Result += "\", \"";
5439
12
    Result += CDecl->getNameAsString();
5440
12
    Result += "\"";
5441
12
  }
5442
52
  else {
5443
52
    Result += ", 0, \"";
5444
52
    Result += CDecl->getNameAsString();
5445
52
    Result += "\"";
5446
52
  }
5447
64
  // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
5448
64
  // 'info' field is initialized to CLS_META(2) for metaclass
5449
64
  Result += ", 0,2, sizeof(struct _objc_class), 0";
5450
64
  if (
IDecl->classmeth_begin() != IDecl->classmeth_end()64
) {
5451
6
    Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
5452
6
    Result += IDecl->getNameAsString();
5453
6
    Result += "\n";
5454
6
  }
5455
64
  else
5456
58
    Result += ", 0\n";
5457
64
  if (
CDecl->protocol_begin() != CDecl->protocol_end()64
) {
5458
3
    Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
5459
3
    Result += CDecl->getNameAsString();
5460
3
    Result += ",0,0\n";
5461
3
  }
5462
64
  else
5463
61
    Result += "\t,0,0,0,0\n";
5464
64
  Result += "};\n";
5465
64
  
5466
64
  // class metadata generation.
5467
64
  Result += "\nstatic struct _objc_class _OBJC_CLASS_";
5468
64
  Result += CDecl->getNameAsString();
5469
64
  Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
5470
64
  "{\n\t&_OBJC_METACLASS_";
5471
64
  Result += CDecl->getNameAsString();
5472
64
  if (
SuperClass64
) {
5473
12
    Result += ", \"";
5474
12
    Result += SuperClass->getNameAsString();
5475
12
    Result += "\", \"";
5476
12
    Result += CDecl->getNameAsString();
5477
12
    Result += "\"";
5478
12
  }
5479
52
  else {
5480
52
    Result += ", 0, \"";
5481
52
    Result += CDecl->getNameAsString();
5482
52
    Result += "\"";
5483
52
  }
5484
64
  // 'info' field is initialized to CLS_CLASS(1) for class
5485
64
  Result += ", 0,1";
5486
64
  if (!ObjCSynthesizedStructs.count(CDecl))
5487
33
    Result += ",0";
5488
31
  else {
5489
31
    // class has size. Must synthesize its size.
5490
31
    Result += ",sizeof(struct ";
5491
31
    Result += CDecl->getNameAsString();
5492
31
    if (LangOpts.MicrosoftExt)
5493
23
      Result += "_IMPL";
5494
31
    Result += ")";
5495
31
  }
5496
64
  if (
NumIvars > 064
) {
5497
31
    Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
5498
31
    Result += CDecl->getNameAsString();
5499
31
    Result += "\n\t";
5500
31
  }
5501
64
  else
5502
33
    Result += ",0";
5503
64
  if (
IDecl->instmeth_begin() != IDecl->instmeth_end()64
) {
5504
48
    Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
5505
48
    Result += CDecl->getNameAsString();
5506
48
    Result += ", 0\n\t";
5507
48
  }
5508
64
  else
5509
16
    Result += ",0,0";
5510
64
  if (
CDecl->protocol_begin() != CDecl->protocol_end()64
) {
5511
3
    Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
5512
3
    Result += CDecl->getNameAsString();
5513
3
    Result += ", 0,0\n";
5514
3
  }
5515
64
  else
5516
61
    Result += ",0,0,0\n";
5517
64
  Result += "};\n";
5518
64
}
5519
5520
53
void RewriteObjCFragileABI::RewriteMetaDataIntoBuffer(std::string &Result) {
5521
53
  int ClsDefCount = ClassImplementation.size();
5522
53
  int CatDefCount = CategoryImplementation.size();
5523
53
  
5524
53
  // For each implemented class, write out all its meta data.
5525
117
  for (int i = 0; 
i < ClsDefCount117
;
i++64
)
5526
64
    RewriteObjCClassMetaData(ClassImplementation[i], Result);
5527
53
  
5528
53
  // For each implemented category, write out all its meta data.
5529
59
  for (int i = 0; 
i < CatDefCount59
;
i++6
)
5530
6
    RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
5531
53
  
5532
53
  // Write objc_symtab metadata
5533
53
  /*
5534
53
   struct _objc_symtab
5535
53
   {
5536
53
   long sel_ref_cnt;
5537
53
   SEL *refs;
5538
53
   short cls_def_cnt;
5539
53
   short cat_def_cnt;
5540
53
   void *defs[cls_def_cnt + cat_def_cnt];
5541
53
   };
5542
53
   */
5543
53
  
5544
53
  Result += "\nstruct _objc_symtab {\n";
5545
53
  Result += "\tlong sel_ref_cnt;\n";
5546
53
  Result += "\tSEL *refs;\n";
5547
53
  Result += "\tshort cls_def_cnt;\n";
5548
53
  Result += "\tshort cat_def_cnt;\n";
5549
53
  Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
5550
53
  Result += "};\n\n";
5551
53
  
5552
53
  Result += "static struct _objc_symtab "
5553
53
  "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
5554
53
  Result += "\t0, 0, " + utostr(ClsDefCount)
5555
53
  + ", " + utostr(CatDefCount) + "\n";
5556
117
  for (int i = 0; 
i < ClsDefCount117
;
i++64
) {
5557
64
    Result += "\t,&_OBJC_CLASS_";
5558
64
    Result += ClassImplementation[i]->getNameAsString();
5559
64
    Result += "\n";
5560
64
  }
5561
53
  
5562
59
  for (int i = 0; 
i < CatDefCount59
;
i++6
) {
5563
6
    Result += "\t,&_OBJC_CATEGORY_";
5564
6
    Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
5565
6
    Result += "_";
5566
6
    Result += CategoryImplementation[i]->getNameAsString();
5567
6
    Result += "\n";
5568
6
  }
5569
53
  
5570
53
  Result += "};\n\n";
5571
53
  
5572
53
  // Write objc_module metadata
5573
53
  
5574
53
  /*
5575
53
   struct _objc_module {
5576
53
   long version;
5577
53
   long size;
5578
53
   const char *name;
5579
53
   struct _objc_symtab *symtab;
5580
53
   }
5581
53
   */
5582
53
  
5583
53
  Result += "\nstruct _objc_module {\n";
5584
53
  Result += "\tlong version;\n";
5585
53
  Result += "\tlong size;\n";
5586
53
  Result += "\tconst char *name;\n";
5587
53
  Result += "\tstruct _objc_symtab *symtab;\n";
5588
53
  Result += "};\n\n";
5589
53
  Result += "static struct _objc_module "
5590
53
  "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
5591
53
  Result += "\t" + utostr(OBJC_ABI_VERSION) +
5592
53
  ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
5593
53
  Result += "};\n\n";
5594
53
  
5595
53
  if (
LangOpts.MicrosoftExt53
) {
5596
30
    if (
ProtocolExprDecls.size()30
) {
5597
0
      Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
5598
0
      Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
5599
0
      for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls) {
5600
0
        Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
5601
0
        Result += ProtDecl->getNameAsString();
5602
0
        Result += " = &_OBJC_PROTOCOL_";
5603
0
        Result += ProtDecl->getNameAsString();
5604
0
        Result += ";\n";
5605
0
      }
5606
0
      Result += "#pragma data_seg(pop)\n\n";
5607
0
    }
5608
30
    Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
5609
30
    Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
5610
30
    Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
5611
30
    Result += "&_OBJC_MODULES;\n";
5612
30
    Result += "#pragma data_seg(pop)\n\n";
5613
30
  }
5614
53
}
5615
5616
/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
5617
/// implementation.
5618
void RewriteObjCFragileABI::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
5619
6
                                              std::string &Result) {
5620
6
  ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
5621
6
  // Find category declaration for this implementation.
5622
6
  ObjCCategoryDecl *CDecl
5623
6
    = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
5624
6
  
5625
6
  std::string FullCategoryName = ClassDecl->getNameAsString();
5626
6
  FullCategoryName += '_';
5627
6
  FullCategoryName += IDecl->getNameAsString();
5628
6
  
5629
6
  // Build _objc_method_list for class's instance methods if needed
5630
6
  SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
5631
6
  
5632
6
  // If any of our property implementations have associated getters or
5633
6
  // setters, produce metadata for them as well.
5634
0
  for (const auto *Prop : IDecl->property_impls()) {
5635
0
    if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5636
0
      continue;
5637
0
    
if (0
!Prop->getPropertyIvarDecl()0
)
5638
0
      continue;
5639
0
    ObjCPropertyDecl *PD = Prop->getPropertyDecl();
5640
0
    if (!PD)
5641
0
      continue;
5642
0
    
if (ObjCMethodDecl *0
Getter0
= PD->getGetterMethodDecl())
5643
0
      InstanceMethods.push_back(Getter);
5644
0
    if (PD->isReadOnly())
5645
0
      continue;
5646
0
    
if (ObjCMethodDecl *0
Setter0
= PD->getSetterMethodDecl())
5647
0
      InstanceMethods.push_back(Setter);
5648
0
  }
5649
6
  RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5650
6
                             true, "CATEGORY_", FullCategoryName, Result);
5651
6
5652
6
  // Build _objc_method_list for class's class methods if needed
5653
6
  RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5654
6
                             false, "CATEGORY_", FullCategoryName, Result);
5655
6
5656
6
  // Protocols referenced in class declaration?
5657
6
  // Null CDecl is case of a category implementation with no category interface
5658
6
  if (CDecl)
5659
6
    RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
5660
6
                                    FullCategoryName, Result);
5661
6
  /* struct _objc_category {
5662
6
   char *category_name;
5663
6
   char *class_name;
5664
6
   struct _objc_method_list *instance_methods;
5665
6
   struct _objc_method_list *class_methods;
5666
6
   struct _objc_protocol_list *protocols;
5667
6
   // Objective-C 1.0 extensions
5668
6
   uint32_t size;     // sizeof (struct _objc_category)
5669
6
   struct _objc_property_list *instance_properties;  // category's own
5670
6
   // @property decl.
5671
6
   };
5672
6
   */
5673
6
  
5674
6
  static bool objc_category = false;
5675
6
  if (
!objc_category6
) {
5676
6
    Result += "\nstruct _objc_category {\n";
5677
6
    Result += "\tchar *category_name;\n";
5678
6
    Result += "\tchar *class_name;\n";
5679
6
    Result += "\tstruct _objc_method_list *instance_methods;\n";
5680
6
    Result += "\tstruct _objc_method_list *class_methods;\n";
5681
6
    Result += "\tstruct _objc_protocol_list *protocols;\n";
5682
6
    Result += "\tunsigned int size;\n";
5683
6
    Result += "\tstruct _objc_property_list *instance_properties;\n";
5684
6
    Result += "};\n";
5685
6
    objc_category = true;
5686
6
  }
5687
6
  Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
5688
6
  Result += FullCategoryName;
5689
6
  Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
5690
6
  Result += IDecl->getNameAsString();
5691
6
  Result += "\"\n\t, \"";
5692
6
  Result += ClassDecl->getNameAsString();
5693
6
  Result += "\"\n";
5694
6
  
5695
6
  if (
IDecl->instmeth_begin() != IDecl->instmeth_end()6
) {
5696
6
    Result += "\t, (struct _objc_method_list *)"
5697
6
    "&_OBJC_CATEGORY_INSTANCE_METHODS_";
5698
6
    Result += FullCategoryName;
5699
6
    Result += "\n";
5700
6
  }
5701
6
  else
5702
0
    Result += "\t, 0\n";
5703
6
  if (
IDecl->classmeth_begin() != IDecl->classmeth_end()6
) {
5704
0
    Result += "\t, (struct _objc_method_list *)"
5705
0
    "&_OBJC_CATEGORY_CLASS_METHODS_";
5706
0
    Result += FullCategoryName;
5707
0
    Result += "\n";
5708
0
  }
5709
6
  else
5710
6
    Result += "\t, 0\n";
5711
6
  
5712
6
  if (
CDecl && 6
CDecl->protocol_begin() != CDecl->protocol_end()6
) {
5713
0
    Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
5714
0
    Result += FullCategoryName;
5715
0
    Result += "\n";
5716
0
  }
5717
6
  else
5718
6
    Result += "\t, 0\n";
5719
6
  Result += "\t, sizeof(struct _objc_category), 0\n};\n";
5720
6
}
5721
5722
// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
5723
/// class methods.
5724
template<typename MethodIterator>
5725
void RewriteObjCFragileABI::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
5726
                                             MethodIterator MethodEnd,
5727
                                             bool IsInstanceMethod,
5728
                                             StringRef prefix,
5729
                                             StringRef ClassName,
5730
140
                                             std::string &Result) {
5731
140
  if (
MethodBegin == MethodEnd140
)
return77
;
5732
63
  
5733
63
  
if (63
!objc_impl_method63
) {
5734
49
    /* struct _objc_method {
5735
49
     SEL _cmd;
5736
49
     char *method_types;
5737
49
     void *_imp;
5738
49
     }
5739
49
     */
5740
49
    Result += "\nstruct _objc_method {\n";
5741
49
    Result += "\tSEL _cmd;\n";
5742
49
    Result += "\tchar *method_types;\n";
5743
49
    Result += "\tvoid *_imp;\n";
5744
49
    Result += "};\n";
5745
49
    
5746
49
    objc_impl_method = true;
5747
49
  }
5748
63
  
5749
63
  // Build _objc_method_list for class's methods if needed
5750
63
  
5751
63
  /* struct  {
5752
63
   struct _objc_method_list *next_method;
5753
63
   int method_count;
5754
63
   struct _objc_method method_list[];
5755
63
   }
5756
63
   */
5757
63
  unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
5758
63
  Result += "\nstatic struct {\n";
5759
63
  Result += "\tstruct _objc_method_list *next_method;\n";
5760
63
  Result += "\tint method_count;\n";
5761
63
  Result += "\tstruct _objc_method method_list[";
5762
63
  Result += utostr(NumMethods);
5763
63
  Result += "];\n} _OBJC_";
5764
63
  Result += prefix;
5765
63
  Result += IsInstanceMethod ? 
"INSTANCE"57
:
"CLASS"6
;
5766
63
  Result += "_METHODS_";
5767
63
  Result += ClassName;
5768
63
  Result += " __attribute__ ((used, section (\"__OBJC, __";
5769
63
  Result += IsInstanceMethod ? 
"inst"57
:
"cls"6
;
5770
63
  Result += "_meth\")))= ";
5771
63
  Result += "{\n\t0, " + utostr(NumMethods) + "\n";
5772
63
  
5773
63
  Result += "\t,{{(SEL)\"";
5774
63
  Result += (*MethodBegin)->getSelector().getAsString();
5775
63
  std::string MethodTypeString =
5776
63
    Context->getObjCEncodingForMethodDecl(*MethodBegin);
5777
63
  Result += "\", \"";
5778
63
  Result += MethodTypeString;
5779
63
  Result += "\", (void *)";
5780
63
  Result += MethodInternalNames[*MethodBegin];
5781
63
  Result += "}\n";
5782
94
  for (++MethodBegin; 
MethodBegin != MethodEnd94
;
++MethodBegin31
) {
5783
31
    Result += "\t  ,{(SEL)\"";
5784
31
    Result += (*MethodBegin)->getSelector().getAsString();
5785
31
    std::string MethodTypeString =
5786
31
      Context->getObjCEncodingForMethodDecl(*MethodBegin);
5787
31
    Result += "\", \"";
5788
31
    Result += MethodTypeString;
5789
31
    Result += "\", (void *)";
5790
31
    Result += MethodInternalNames[*MethodBegin];
5791
31
    Result += "}\n";
5792
31
  }
5793
140
  Result += "\t }\n};\n";
5794
140
}
RewriteObjC.cpp:void (anonymous namespace)::RewriteObjCFragileABI::RewriteObjCMethodsMetaData<clang::ObjCMethodDecl**>(clang::ObjCMethodDecl**, clang::ObjCMethodDecl**, bool, llvm::StringRef, llvm::StringRef, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >&)
Line
Count
Source
5730
70
                                             std::string &Result) {
5731
70
  if (
MethodBegin == MethodEnd70
)
return13
;
5732
57
  
5733
57
  
if (57
!objc_impl_method57
) {
5734
46
    /* struct _objc_method {
5735
46
     SEL _cmd;
5736
46
     char *method_types;
5737
46
     void *_imp;
5738
46
     }
5739
46
     */
5740
46
    Result += "\nstruct _objc_method {\n";
5741
46
    Result += "\tSEL _cmd;\n";
5742
46
    Result += "\tchar *method_types;\n";
5743
46
    Result += "\tvoid *_imp;\n";
5744
46
    Result += "};\n";
5745
46
    
5746
46
    objc_impl_method = true;
5747
46
  }
5748
57
  
5749
57
  // Build _objc_method_list for class's methods if needed
5750
57
  
5751
57
  /* struct  {
5752
57
   struct _objc_method_list *next_method;
5753
57
   int method_count;
5754
57
   struct _objc_method method_list[];
5755
57
   }
5756
57
   */
5757
57
  unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
5758
57
  Result += "\nstatic struct {\n";
5759
57
  Result += "\tstruct _objc_method_list *next_method;\n";
5760
57
  Result += "\tint method_count;\n";
5761
57
  Result += "\tstruct _objc_method method_list[";
5762
57
  Result += utostr(NumMethods);
5763
57
  Result += "];\n} _OBJC_";
5764
57
  Result += prefix;
5765
57
  Result += IsInstanceMethod ? 
"INSTANCE"57
:
"CLASS"0
;
5766
57
  Result += "_METHODS_";
5767
57
  Result += ClassName;
5768
57
  Result += " __attribute__ ((used, section (\"__OBJC, __";
5769
57
  Result += IsInstanceMethod ? 
"inst"57
:
"cls"0
;
5770
57
  Result += "_meth\")))= ";
5771
57
  Result += "{\n\t0, " + utostr(NumMethods) + "\n";
5772
57
  
5773
57
  Result += "\t,{{(SEL)\"";
5774
57
  Result += (*MethodBegin)->getSelector().getAsString();
5775
57
  std::string MethodTypeString =
5776
57
    Context->getObjCEncodingForMethodDecl(*MethodBegin);
5777
57
  Result += "\", \"";
5778
57
  Result += MethodTypeString;
5779
57
  Result += "\", (void *)";
5780
57
  Result += MethodInternalNames[*MethodBegin];
5781
57
  Result += "}\n";
5782
88
  for (++MethodBegin; 
MethodBegin != MethodEnd88
;
++MethodBegin31
) {
5783
31
    Result += "\t  ,{(SEL)\"";
5784
31
    Result += (*MethodBegin)->getSelector().getAsString();
5785
31
    std::string MethodTypeString =
5786
31
      Context->getObjCEncodingForMethodDecl(*MethodBegin);
5787
31
    Result += "\", \"";
5788
31
    Result += MethodTypeString;
5789
31
    Result += "\", (void *)";
5790
31
    Result += MethodInternalNames[*MethodBegin];
5791
31
    Result += "}\n";
5792
31
  }
5793
70
  Result += "\t }\n};\n";
5794
70
}
RewriteObjC.cpp:void (anonymous namespace)::RewriteObjCFragileABI::RewriteObjCMethodsMetaData<clang::DeclContext::filtered_decl_iterator<clang::ObjCMethodDecl, &(clang::ObjCMethodDecl::isClassMethod() const)> >(clang::DeclContext::filtered_decl_iterator<clang::ObjCMethodDecl, &(clang::ObjCMethodDecl::isClassMethod() const)>, clang::DeclContext::filtered_decl_iterator<clang::ObjCMethodDecl, &(clang::ObjCMethodDecl::isClassMethod() const)>, bool, llvm::StringRef, llvm::StringRef, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >&)
Line
Count
Source
5730
70
                                             std::string &Result) {
5731
70
  if (
MethodBegin == MethodEnd70
)
return64
;
5732
6
  
5733
6
  
if (6
!objc_impl_method6
) {
5734
3
    /* struct _objc_method {
5735
3
     SEL _cmd;
5736
3
     char *method_types;
5737
3
     void *_imp;
5738
3
     }
5739
3
     */
5740
3
    Result += "\nstruct _objc_method {\n";
5741
3
    Result += "\tSEL _cmd;\n";
5742
3
    Result += "\tchar *method_types;\n";
5743
3
    Result += "\tvoid *_imp;\n";
5744
3
    Result += "};\n";
5745
3
    
5746
3
    objc_impl_method = true;
5747
3
  }
5748
6
  
5749
6
  // Build _objc_method_list for class's methods if needed
5750
6
  
5751
6
  /* struct  {
5752
6
   struct _objc_method_list *next_method;
5753
6
   int method_count;
5754
6
   struct _objc_method method_list[];
5755
6
   }
5756
6
   */
5757
6
  unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
5758
6
  Result += "\nstatic struct {\n";
5759
6
  Result += "\tstruct _objc_method_list *next_method;\n";
5760
6
  Result += "\tint method_count;\n";
5761
6
  Result += "\tstruct _objc_method method_list[";
5762
6
  Result += utostr(NumMethods);
5763
6
  Result += "];\n} _OBJC_";
5764
6
  Result += prefix;
5765
6
  Result += IsInstanceMethod ? 
"INSTANCE"0
:
"CLASS"6
;
5766
6
  Result += "_METHODS_";
5767
6
  Result += ClassName;
5768
6
  Result += " __attribute__ ((used, section (\"__OBJC, __";
5769
6
  Result += IsInstanceMethod ? 
"inst"0
:
"cls"6
;
5770
6
  Result += "_meth\")))= ";
5771
6
  Result += "{\n\t0, " + utostr(NumMethods) + "\n";
5772
6
  
5773
6
  Result += "\t,{{(SEL)\"";
5774
6
  Result += (*MethodBegin)->getSelector().getAsString();
5775
6
  std::string MethodTypeString =
5776
6
    Context->getObjCEncodingForMethodDecl(*MethodBegin);
5777
6
  Result += "\", \"";
5778
6
  Result += MethodTypeString;
5779
6
  Result += "\", (void *)";
5780
6
  Result += MethodInternalNames[*MethodBegin];
5781
6
  Result += "}\n";
5782
6
  for (++MethodBegin; 
MethodBegin != MethodEnd6
;
++MethodBegin0
) {
5783
0
    Result += "\t  ,{(SEL)\"";
5784
0
    Result += (*MethodBegin)->getSelector().getAsString();
5785
0
    std::string MethodTypeString =
5786
0
      Context->getObjCEncodingForMethodDecl(*MethodBegin);
5787
0
    Result += "\", \"";
5788
0
    Result += MethodTypeString;
5789
0
    Result += "\", (void *)";
5790
0
    Result += MethodInternalNames[*MethodBegin];
5791
0
    Result += "}\n";
5792
0
  }
5793
70
  Result += "\t }\n};\n";
5794
70
}
5795
5796
43
Stmt *RewriteObjCFragileABI::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
5797
43
  SourceRange OldRange = IV->getSourceRange();
5798
43
  Expr *BaseExpr = IV->getBase();
5799
43
  
5800
43
  // Rewrite the base, but without actually doing replaces.
5801
43
  {
5802
43
    DisableReplaceStmtScope S(*this);
5803
43
    BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
5804
43
    IV->setBase(BaseExpr);
5805
43
  }
5806
43
  
5807
43
  ObjCIvarDecl *D = IV->getDecl();
5808
43
  
5809
43
  Expr *Replacement = IV;
5810
43
  if (
CurMethodDef43
) {
5811
37
    if (
BaseExpr->getType()->isObjCObjectPointerType()37
) {
5812
37
      const ObjCInterfaceType *iFaceDecl =
5813
37
      dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5814
37
      assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
5815
37
      // lookup which class implements the instance variable.
5816
37
      ObjCInterfaceDecl *clsDeclared = nullptr;
5817
37
      iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5818
37
                                                   clsDeclared);
5819
37
      assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5820
37
      
5821
37
      // Synthesize an explicit cast to gain access to the ivar.
5822
37
      std::string RecName = clsDeclared->getIdentifier()->getName();
5823
37
      RecName += "_IMPL";
5824
37
      IdentifierInfo *II = &Context->Idents.get(RecName);
5825
37
      RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5826
37
                                          SourceLocation(), SourceLocation(),
5827
37
                                          II);
5828
37
      assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5829
37
      QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5830
37
      CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
5831
37
                                                    CK_BitCast,
5832
37
                                                    IV->getBase());
5833
37
      // Don't forget the parens to enforce the proper binding.
5834
37
      ParenExpr *PE = new (Context) ParenExpr(OldRange.getBegin(),
5835
37
                                              OldRange.getEnd(),
5836
37
                                              castExpr);
5837
37
      if (IV->isFreeIvar() &&
5838
37
          
declaresSameEntity(CurMethodDef->getClassInterface(), iFaceDecl->getDecl())26
) {
5839
26
        MemberExpr *ME = new (Context)
5840
26
            MemberExpr(PE, true, SourceLocation(), D, IV->getLocation(),
5841
26
                       D->getType(), VK_LValue, OK_Ordinary);
5842
26
        Replacement = ME;
5843
37
      } else {
5844
11
        IV->setBase(PE);
5845
11
      }
5846
37
    }
5847
43
  } else { // we are outside a method.
5848
6
    assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
5849
6
    
5850
6
    // Explicit ivar refs need to have a cast inserted.
5851
6
    // FIXME: consider sharing some of this code with the code above.
5852
6
    if (
BaseExpr->getType()->isObjCObjectPointerType()6
) {
5853
6
      const ObjCInterfaceType *iFaceDecl =
5854
6
      dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5855
6
      // lookup which class implements the instance variable.
5856
6
      ObjCInterfaceDecl *clsDeclared = nullptr;
5857
6
      iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5858
6
                                                   clsDeclared);
5859
6
      assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5860
6
      
5861
6
      // Synthesize an explicit cast to gain access to the ivar.
5862
6
      std::string RecName = clsDeclared->getIdentifier()->getName();
5863
6
      RecName += "_IMPL";
5864
6
      IdentifierInfo *II = &Context->Idents.get(RecName);
5865
6
      RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5866
6
                                          SourceLocation(), SourceLocation(),
5867
6
                                          II);
5868
6
      assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5869
6
      QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5870
6
      CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
5871
6
                                                    CK_BitCast,
5872
6
                                                    IV->getBase());
5873
6
      // Don't forget the parens to enforce the proper binding.
5874
6
      ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
5875
6
                                              IV->getBase()->getLocEnd(), castExpr);
5876
6
      // Cannot delete IV->getBase(), since PE points to it.
5877
6
      // Replace the old base with the cast. This is important when doing
5878
6
      // embedded rewrites. For example, [newInv->_container addObject:0].
5879
6
      IV->setBase(PE);
5880
6
    }
5881
6
  }
5882
43
  
5883
43
  ReplaceStmtWithRange(IV, Replacement, OldRange);
5884
43
  return Replacement;  
5885
43
}
5886
5887
#endif // CLANG_ENABLE_OBJC_REWRITER