diff --git a/Library/Homebrew/utils.rb b/Library/Homebrew/utils.rb
index b3520a7ecb5ea2721b0f77f0e9bb7aeac48dca44..0c36da2e173d144f1c69865988fc921794dc894c 100644
--- a/Library/Homebrew/utils.rb
+++ b/Library/Homebrew/utils.rb
@@ -625,22 +625,30 @@ def migrate_legacy_keg_symlinks_if_necessary
   legacy_linked_kegs = HOMEBREW_LIBRARY/"LinkedKegs"
   return unless legacy_linked_kegs.directory?
 
-  legacy_linked_kegs.children.each do |f|
-    keg = Keg.new(f.realpath)
-    keg.unlink
-    keg.link
+  legacy_linked_kegs.children.each do |link|
+    name = link.basename
+    src = begin
+      link.realpath
+    rescue Errno::ENOENT
+      begin
+        (HOMEBREW_PREFIX/"opt/#{name}").realpath
+      rescue Errno::ENOENT
+        Formulary.factory(name).installed_prefix
+      end
+    end
+    dst = HOMEBREW_LINKED_KEGS/name
+    FileUtils.ln_sf(src.relative_path_from(dst.parent), dst)
   end
   FileUtils.rm_rf legacy_linked_kegs
 
   legacy_pinned_kegs = HOMEBREW_LIBRARY/"PinnedKegs"
   return unless legacy_pinned_kegs.directory?
 
-  legacy_pinned_kegs.children.each do |f|
-    pin_version = Keg.new(f.realpath).version
-    formula = Formulary.factory(f.basename.to_s)
-    pin = FormulaPin.new(formula)
-    pin.unpin
-    pin.pin_at(pin_version)
+  legacy_pinned_kegs.children.each do |link|
+    name = link.basename
+    src = link.realpath
+    dst = HOMEBREW_PINNED_KEGS/name
+    FileUtils.ln_sf(src.relative_path_from(dst.parent), dst)
   end
   FileUtils.rm_rf legacy_pinned_kegs
 end