implementation-visitor.h 16.5 KB
Newer Older
1 2 3 4 5 6 7 8 9
// Copyright 2017 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef V8_TORQUE_IMPLEMENTATION_VISITOR_H_
#define V8_TORQUE_IMPLEMENTATION_VISITOR_H_

#include <string>

10
#include "src/base/macros.h"
11
#include "src/torque/ast.h"
12
#include "src/torque/cfg.h"
13 14 15 16 17 18 19 20 21
#include "src/torque/file-visitor.h"
#include "src/torque/global-context.h"
#include "src/torque/types.h"
#include "src/torque/utils.h"

namespace v8 {
namespace internal {
namespace torque {

22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
// LocationReference is the representation of an l-value, so a value that might
// allow for assignment. For uniformity, this class can also represent
// unassignable temporaries. Assignable values fall in two categories:
//   - stack ranges that represent mutable variables, including structs.
//   - field or element access expressions that generate operator calls.
class LocationReference {
 public:
  // An assignable stack range.
  static LocationReference VariableAccess(VisitResult variable) {
    DCHECK(variable.IsOnStack());
    LocationReference result;
    result.variable_ = std::move(variable);
    return result;
  }
  // An unassignable value. {description} is only used for error messages.
  static LocationReference Temporary(VisitResult temporary,
                                     std::string description) {
    LocationReference result;
    result.temporary_ = std::move(temporary);
    result.temporary_description_ = std::move(description);
    return result;
  }
  static LocationReference ArrayAccess(VisitResult base, VisitResult offset) {
    LocationReference result;
    result.eval_function_ = std::string{"[]"};
    result.assign_function_ = std::string{"[]="};
    result.call_arguments_ = {base, offset};
    return result;
  }
  static LocationReference FieldAccess(VisitResult object,
                                       std::string fieldname) {
    LocationReference result;
    result.eval_function_ = "." + fieldname;
    result.assign_function_ = "." + fieldname + "=";
    result.call_arguments_ = {object};
    return result;
  }

  bool IsConst() const { return temporary_.has_value(); }

  bool IsVariableAccess() const { return variable_.has_value(); }
  const VisitResult& variable() const {
    DCHECK(IsVariableAccess());
    return *variable_;
  }
  bool IsTemporary() const { return temporary_.has_value(); }
  const VisitResult& temporary() const {
    DCHECK(IsTemporary());
    return *temporary_;
  }
  // For error reporting.
  const std::string& temporary_description() const {
    DCHECK(IsTemporary());
    return *temporary_description_;
  }

  bool IsCallAccess() const {
    bool is_call_access = eval_function_.has_value();
    DCHECK_EQ(is_call_access, assign_function_.has_value());
    return is_call_access;
  }
  const VisitResultVector& call_arguments() const {
    DCHECK(IsCallAccess());
    return call_arguments_;
  }
  const std::string& eval_function() const {
    DCHECK(IsCallAccess());
    return *eval_function_;
  }
  const std::string& assign_function() const {
    DCHECK(IsCallAccess());
    return *assign_function_;
  }

 private:
  base::Optional<VisitResult> variable_;
  base::Optional<VisitResult> temporary_;
  base::Optional<std::string> temporary_description_;
  base::Optional<std::string> eval_function_;
  base::Optional<std::string> assign_function_;
  VisitResultVector call_arguments_;

  LocationReference() = default;
105 106
};

107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
template <class T>
class Binding;

template <class T>
class BindingsManager {
 public:
  base::Optional<Binding<T>*> TryLookup(const std::string& name) {
    return current_bindings_[name];
  }

 private:
  friend class Binding<T>;
  std::unordered_map<std::string, base::Optional<Binding<T>*>>
      current_bindings_;
};

template <class T>
class Binding : public T {
 public:
  template <class... Args>
  Binding(BindingsManager<T>* manager, const std::string& name, Args&&... args)
      : T(std::forward<Args>(args)...),
        manager_(manager),
        name_(name),
        previous_binding_(this) {
    std::swap(previous_binding_, manager_->current_bindings_[name]);
  }
  ~Binding() { manager_->current_bindings_[name_] = previous_binding_; }

  const std::string& name() const { return name_; }
  SourcePosition declaration_position() const { return declaration_position_; }

 private:
  BindingsManager<T>* manager_;
  const std::string name_;
  base::Optional<Binding*> previous_binding_;
  SourcePosition declaration_position_ = CurrentSourcePosition::Get();
  DISALLOW_COPY_AND_MOVE_AND_ASSIGN(Binding);
};

template <class T>
class BlockBindings {
 public:
  explicit BlockBindings(BindingsManager<T>* manager) : manager_(manager) {}
  void Add(std::string name, T value) {
    for (const auto& binding : bindings_) {
      if (binding->name() == name) {
        ReportError(
            "redeclaration of name \"", name,
            "\" in the same block is illegal, previous declaration at: ",
            binding->declaration_position());
      }
    }
    bindings_.push_back(base::make_unique<Binding<T>>(manager_, std::move(name),
                                                      std::move(value)));
  }

  std::vector<Binding<T>*> bindings() const {
    std::vector<Binding<T>*> result;
    result.reserve(bindings_.size());
    for (auto& b : bindings_) {
      result.push_back(b.get());
    }
    return result;
  }

 private:
  BindingsManager<T>* manager_;
  std::vector<std::unique_ptr<Binding<T>>> bindings_;
};

struct LocalValue {
  bool is_const;
  VisitResult value;
};

struct LocalLabel {
  Block* block;
  std::vector<const Type*> parameter_types;

  explicit LocalLabel(Block* block,
                      std::vector<const Type*> parameter_types = {})
      : block(block), parameter_types(std::move(parameter_types)) {}
};

struct Arguments {
  VisitResultVector parameters;
  std::vector<Binding<LocalLabel>*> labels;
};

bool IsCompatibleSignature(const Signature& sig, const TypeVector& types,
                           const std::vector<Binding<LocalLabel>*>& labels);

200 201 202
class ImplementationVisitor : public FileVisitor {
 public:
  explicit ImplementationVisitor(GlobalContext& global_context)
203
      : FileVisitor(global_context) {}
204

205
  void Visit(Ast* ast) { Visit(ast->default_module()); }
206 207

  VisitResult Visit(Expression* expr);
208
  const Type* Visit(Statement* stmt);
209 210
  void Visit(Declaration* decl);

211 212
  VisitResult Visit(StructExpression* decl);

213 214
  LocationReference GetLocationReference(Expression* location);
  LocationReference GetLocationReference(IdentifierExpression* expr);
215
  LocationReference GetLocationReference(FieldAccessExpression* expr);
216
  LocationReference GetLocationReference(ElementAccessExpression* expr);
217

218
  VisitResult GenerateFetchFromLocation(const LocationReference& reference);
219

220
  VisitResult GetBuiltinCode(Builtin* builtin);
221

222
  VisitResult Visit(IdentifierExpression* expr);
223
  VisitResult Visit(FieldAccessExpression* expr) {
224 225
    StackScope scope(this);
    return scope.Yield(GenerateFetchFromLocation(GetLocationReference(expr)));
226 227
  }
  VisitResult Visit(ElementAccessExpression* expr) {
228 229
    StackScope scope(this);
    return scope.Yield(GenerateFetchFromLocation(GetLocationReference(expr)));
230 231 232 233
  }

  void Visit(ModuleDeclaration* decl);
  void Visit(DefaultModuleDeclaration* decl) {
234
    Visit(implicit_cast<ModuleDeclaration*>(decl));
235 236
  }
  void Visit(ExplicitModuleDeclaration* decl) {
237
    Visit(implicit_cast<ModuleDeclaration*>(decl));
238 239
  }
  void Visit(TypeDeclaration* decl) {}
240
  void Visit(TypeAliasDeclaration* decl) {}
241
  void Visit(ExternConstDeclaration* decl) {}
242
  void Visit(StructDeclaration* decl);
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
  void Visit(StandardDeclaration* decl);
  void Visit(GenericDeclaration* decl) {}
  void Visit(SpecializationDeclaration* decl);

  void Visit(TorqueMacroDeclaration* decl, const Signature& signature,
             Statement* body);
  void Visit(TorqueBuiltinDeclaration* decl, const Signature& signature,
             Statement* body);
  void Visit(ExternalMacroDeclaration* decl, const Signature& signature,
             Statement* body) {}
  void Visit(ExternalBuiltinDeclaration* decl, const Signature& signature,
             Statement* body) {}
  void Visit(ExternalRuntimeDeclaration* decl, const Signature& signature,
             Statement* body) {}
  void Visit(CallableNode* decl, const Signature& signature, Statement* body);
258
  void Visit(ConstDeclaration* decl);
259 260

  VisitResult Visit(CallExpression* expr, bool is_tail = false);
261
  const Type* Visit(TailCallStatement* stmt);
262 263 264 265 266 267 268 269 270 271

  VisitResult Visit(ConditionalExpression* expr);

  VisitResult Visit(LogicalOrExpression* expr);
  VisitResult Visit(LogicalAndExpression* expr);

  VisitResult Visit(IncrementDecrementExpression* expr);
  VisitResult Visit(AssignmentExpression* expr);
  VisitResult Visit(StringLiteralExpression* expr);
  VisitResult Visit(NumberLiteralExpression* expr);
272
  VisitResult Visit(AssumeTypeImpossibleExpression* expr);
273 274
  VisitResult Visit(TryLabelExpression* expr);
  VisitResult Visit(StatementExpression* expr);
275

276 277 278 279 280 281 282 283
  const Type* Visit(ReturnStatement* stmt);
  const Type* Visit(GotoStatement* stmt);
  const Type* Visit(IfStatement* stmt);
  const Type* Visit(WhileStatement* stmt);
  const Type* Visit(BreakStatement* stmt);
  const Type* Visit(ContinueStatement* stmt);
  const Type* Visit(ForLoopStatement* stmt);
  const Type* Visit(VarDeclarationStatement* stmt);
284 285
  const Type* Visit(VarDeclarationStatement* stmt,
                    BlockBindings<LocalValue>* block_bindings);
286 287 288 289 290
  const Type* Visit(ForOfLoopStatement* stmt);
  const Type* Visit(BlockStatement* block);
  const Type* Visit(ExpressionStatement* stmt);
  const Type* Visit(DebugStatement* stmt);
  const Type* Visit(AssertStatement* stmt);
291

292 293 294
  void BeginModuleFile(Module* module);
  void EndModuleFile(Module* module);

295 296
  void GenerateImplementation(const std::string& dir, Module* module);

297 298 299 300 301 302 303 304 305 306 307 308 309
  DECLARE_CONTEXTUAL_VARIABLE(ValueBindingsManager,
                              BindingsManager<LocalValue>);
  DECLARE_CONTEXTUAL_VARIABLE(LabelBindingsManager,
                              BindingsManager<LocalLabel>);

  // A BindingsManagersScope has to be active for local bindings to be created.
  // Shadowing an existing BindingsManagersScope by creating a new one hides all
  // existing bindings while the additional BindingsManagersScope is active.
  struct BindingsManagersScope {
    ValueBindingsManager::Scope value_bindings_manager;
    LabelBindingsManager::Scope label_bindings_manager;
  };

310 311 312 313 314
 private:
  std::string GetBaseAssemblerName(Module* module);

  std::string GetDSLAssemblerName(Module* module);

315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
  // {StackScope} records the stack height at creation time and reconstructs it
  // when being destructed by emitting a {DeleteRangeInstruction}, except for
  // the slots protected by {StackScope::Yield}. Calling {Yield(v)} deletes all
  // slots above the initial stack height except for the slots of {v}, which are
  // moved to form the only slots above the initial height and marks them to
  // survive destruction of the {StackScope}. A typical pattern is the
  // following:
  //
  // VisitResult result;
  // {
  //   StackScope stack_scope(this);
  //   // ... create temporary slots ...
  //   result = stack_scope.Yield(surviving_slots);
  // }
  class StackScope {
330
   public:
331 332 333 334
    explicit StackScope(ImplementationVisitor* visitor) : visitor_(visitor) {
      base_ = visitor_->assembler().CurrentStack().AboveTop();
    }
    VisitResult Yield(VisitResult result) {
335 336
      DCHECK(!closed_);
      closed_ = true;
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
      if (!result.IsOnStack()) {
        if (!visitor_->assembler().CurrentBlockIsComplete()) {
          visitor_->assembler().DropTo(base_);
        }
        return result;
      }
      DCHECK_LE(base_, result.stack_range().begin());
      DCHECK_LE(result.stack_range().end(),
                visitor_->assembler().CurrentStack().AboveTop());
      visitor_->assembler().DropTo(result.stack_range().end());
      visitor_->assembler().DeleteRange(
          StackRange{base_, result.stack_range().begin()});
      base_ = visitor_->assembler().CurrentStack().AboveTop();
      return VisitResult(result.type(), visitor_->assembler().TopRange(
                                            result.stack_range().Size()));
352
    }
353

354 355 356 357 358 359 360 361
    void Close() {
      DCHECK(!closed_);
      closed_ = true;
      if (!visitor_->assembler().CurrentBlockIsComplete()) {
        visitor_->assembler().DropTo(base_);
      }
    }

362
    ~StackScope() {
363
      if (closed_) {
364 365 366
        DCHECK_IMPLIES(
            !visitor_->assembler().CurrentBlockIsComplete(),
            base_ == visitor_->assembler().CurrentStack().AboveTop());
367 368
      } else {
        Close();
369
      }
370 371 372 373
    }

   private:
    ImplementationVisitor* visitor_;
374
    BottomOffset base_;
375 376 377 378 379 380 381 382 383 384 385 386 387 388
    bool closed_ = false;
  };

  class BreakContinueActivator {
   public:
    BreakContinueActivator(Block* break_block, Block* continue_block)
        : break_binding_{&LabelBindingsManager::Get(), "_break",
                         LocalLabel{break_block}},
          continue_binding_{&LabelBindingsManager::Get(), "_continue",
                            LocalLabel{continue_block}} {}

   private:
    Binding<LocalLabel> break_binding_;
    Binding<LocalLabel> continue_binding_;
389 390
  };

391 392 393 394 395
  base::Optional<Binding<LocalValue>*> TryLookupLocalValue(
      const std::string& name);
  base::Optional<Binding<LocalLabel>*> TryLookupLabel(const std::string& name);
  Binding<LocalLabel>* LookupLabel(const std::string& name);
  Block* LookupSimpleLabel(const std::string& name);
396 397
  Callable* LookupCall(const std::string& name, const Arguments& arguments,
                       const TypeVector& specialization_types);
398

399
  const Type* GetCommonType(const Type* left, const Type* right);
400 401 402

  VisitResult GenerateCopy(const VisitResult& to_copy);

403
  void GenerateAssignToLocation(const LocationReference& reference,
404
                                const VisitResult& assignment_value);
405

406
  VisitResult GenerateCall(const std::string& callable_name,
407 408 409
                           Arguments parameters,
                           const TypeVector& specialization_types = {},
                           bool tail_call = false);
410
  VisitResult GeneratePointerCall(Expression* callee,
411
                                  const Arguments& parameters, bool tail_call);
412

413 414
  void GenerateBranch(const VisitResult& condition, Block* true_block,
                      Block* false_block);
415

416 417
  void GenerateExpressionBranch(Expression* expression, Block* true_block,
                                Block* false_block);
418

419
  void GenerateMacroFunctionDeclaration(std::ostream& o,
420 421
                                        const std::string& macro_prefix,
                                        Macro* macro);
422 423 424 425 426
  void GenerateFunctionDeclaration(std::ostream& o,
                                   const std::string& macro_prefix,
                                   const std::string& name,
                                   const Signature& signature,
                                   const NameVector& parameter_names);
427

428
  VisitResult GenerateImplicitConvert(const Type* destination_type,
429 430
                                      VisitResult source);

431 432 433 434
  void Specialize(const SpecializationKey& key, CallableNode* callable,
                  const CallableNodeSignature* signature,
                  Statement* body) override {
    Declarations::GenericScopeActivator scope(declarations(), key);
435
    Visit(callable, MakeSignature(signature), body);
436 437
  }

438
  StackRange GenerateLabelGoto(LocalLabel* label,
439
                               base::Optional<StackRange> arguments = {});
440

441
  std::vector<Binding<LocalLabel>*> LabelsFromIdentifiers(
442
      const std::vector<std::string>& names);
443

444 445 446
  StackRange LowerParameter(const Type* type, const std::string& parameter_name,
                            Stack<std::string>* lowered_parameters);

447 448 449 450
  std::string ExternalLabelName(const std::string& label_name);
  std::string ExternalLabelParameterName(const std::string& label_name,
                                         size_t i);
  std::string ExternalParameterName(const std::string& name);
451

452 453 454 455
  std::ostream& source_out() { return module_->source_stream(); }

  std::ostream& header_out() { return module_->header_stream(); }

456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
  CfgAssembler& assembler() { return *assembler_; }

  void SetReturnValue(VisitResult return_value) {
    DCHECK_IMPLIES(return_value_, *return_value_ == return_value);
    return_value_ = std::move(return_value);
  }

  VisitResult GetAndClearReturnValue() {
    VisitResult return_value = *return_value_;
    return_value_ = base::nullopt;
    return return_value;
  }

  base::Optional<CfgAssembler> assembler_;
  base::Optional<VisitResult> return_value_;
471 472 473 474 475 476 477
};

}  // namespace torque
}  // namespace internal
}  // namespace v8

#endif  // V8_TORQUE_IMPLEMENTATION_VISITOR_H_