1 /*
   2  * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 
  24 
  25 package org.graalvm.compiler.graph;
  26 
  27 import java.util.function.Consumer;
  28 
  29 import jdk.internal.vm.compiler.collections.UnmodifiableEconomicMap;
  30 
  31 /**
  32  * This class is a container of a graph that needs to be readonly and optionally a lazily created
  33  * mutable copy of the graph.
  34  */
  35 public final class CachedGraph<G extends Graph> {
  36 
  37     private final G readonlyCopy;
  38     private G mutableCopy;
  39 
  40     private CachedGraph(G readonlyCopy, G mutableCopy) {
  41         this.readonlyCopy = readonlyCopy;
  42         this.mutableCopy = mutableCopy;
  43     }
  44 
  45     public static <G extends Graph> CachedGraph<G> fromReadonlyCopy(G graph) {
  46         return new CachedGraph<>(graph, null);
  47     }
  48 
  49     public static <G extends Graph> CachedGraph<G> fromMutableCopy(G graph) {
  50         return new CachedGraph<>(graph, graph);
  51     }
  52 
  53     public G getReadonlyCopy() {
  54         if (hasMutableCopy()) {
  55             return mutableCopy;
  56         }
  57         return readonlyCopy;
  58     }
  59 
  60     public boolean hasMutableCopy() {
  61         return mutableCopy != null;
  62     }
  63 
  64     @SuppressWarnings("unchecked")
  65     public G getMutableCopy(Consumer<UnmodifiableEconomicMap<Node, Node>> duplicationMapCallback) {
  66         if (!hasMutableCopy()) {
  67             // Sharing the debug context with the copy is safe since both graphs are
  68             // only used in the current thread.
  69             mutableCopy = (G) readonlyCopy.copy(duplicationMapCallback, readonlyCopy.getDebug());
  70         }
  71         return mutableCopy;
  72     }
  73 }