Factor code to copy global value attributes like
[oota-llvm.git] / lib / Linker / LinkModules.cpp
index 0d4479bfd24bf8e31cb95ec1596e55ee08b44534..66c68ca87f907223d75b2bcdf213149926397120 100644 (file)
@@ -2,8 +2,8 @@
 //
 //                     The LLVM Compiler Infrastructure
 //
-// This file was developed by the LLVM research group and is distributed under
-// the University of Illinois Open Source License. See LICENSE.TXT for details.
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
 //
 //===----------------------------------------------------------------------===//
 //
@@ -316,7 +316,7 @@ static Value *RemapOperand(const Value *In,
   
   // Cache the mapping in our local map structure
   if (Result) {
-    ValueMap.insert(std::make_pair(In, Result));
+    ValueMap[In] = Result;
     return Result;
   }
   
@@ -351,22 +351,20 @@ static void ForceRenaming(GlobalValue *GV, const std::string &Name) {
 /// CopyGVAttributes - copy additional attributes (those not needed to construct
 /// a GlobalValue) from the SrcGV to the DestGV. 
 static void CopyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
-  // Propagate alignment, visibility and section info.
-  DestGV->setAlignment(std::max(DestGV->getAlignment(), SrcGV->getAlignment()));
-  DestGV->setSection(SrcGV->getSection());
-  DestGV->setVisibility(SrcGV->getVisibility());
-  if (const Function *SrcF = dyn_cast<Function>(SrcGV)) {
-    Function *DestF = cast<Function>(DestGV);
-    DestF->setCallingConv(SrcF->getCallingConv());
-  }
+  // Use the maximum alignment, rather than just copying the alignment of SrcGV.
+  unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
+  DestGV->copyAttributesFrom(SrcGV);
+  DestGV->setAlignment(Alignment);
 }
 
 /// GetLinkageResult - This analyzes the two global values and determines what
 /// the result will look like in the destination module.  In particular, it
 /// computes the resultant linkage type, computes whether the global in the
 /// source should be copied over to the destination (replacing the existing
-/// one), and computes whether this linkage is an error or not.
-static bool GetLinkageResult(GlobalValue *Dest, GlobalValue *Src,
+/// one), and computes whether this linkage is an error or not. It also performs
+/// visibility checks: we cannot link together two symbols with different
+/// visibilities.
+static bool GetLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
                              GlobalValue::LinkageTypes &LT, bool &LinkFromSrc,
                              std::string *Err) {
   assert((!Dest || !Src->hasInternalLinkage()) &&
@@ -376,7 +374,7 @@ static bool GetLinkageResult(GlobalValue *Dest, GlobalValue *Src,
     LinkFromSrc = true;
     LT = Src->getLinkage();
   } else if (Src->isDeclaration()) {
-    // If Src is external or if both Src & Drc are external..  Just link the
+    // If Src is external or if both Src & Dest are external..  Just link the
     // external globals, we aren't adding anything.
     if (Src->hasDLLImportLinkage()) {
       // If one of GVs has DLLImport linkage, result should be dllimport'ed.
@@ -402,10 +400,12 @@ static bool GetLinkageResult(GlobalValue *Dest, GlobalValue *Src,
             "': can only link appending global with another appending global!");
     LinkFromSrc = true; // Special cased.
     LT = Src->getLinkage();
-  } else if (Src->hasWeakLinkage() || Src->hasLinkOnceLinkage()) {
-    // At this point we know that Dest has LinkOnce, External*, Weak, or
-    // DLL* linkage.
-    if ((Dest->hasLinkOnceLinkage() && Src->hasWeakLinkage()) ||
+  } else if (Src->hasWeakLinkage() || Src->hasLinkOnceLinkage() ||
+             Src->hasCommonLinkage()) {
+    // At this point we know that Dest has LinkOnce, External*, Weak, Common,
+    // or DLL* linkage.
+    if ((Dest->hasLinkOnceLinkage() && 
+          (Src->hasWeakLinkage() || Src->hasCommonLinkage())) ||
         Dest->hasExternalWeakLinkage()) {
       LinkFromSrc = true;
       LT = Src->getLinkage();
@@ -413,7 +413,8 @@ static bool GetLinkageResult(GlobalValue *Dest, GlobalValue *Src,
       LinkFromSrc = false;
       LT = Dest->getLinkage();
     }
-  } else if (Dest->hasWeakLinkage() || Dest->hasLinkOnceLinkage()) {
+  } else if (Dest->hasWeakLinkage() || Dest->hasLinkOnceLinkage() ||
+             Dest->hasCommonLinkage()) {
     // At this point we know that Src has External* or DLL* linkage.
     if (Src->hasExternalWeakLinkage()) {
       LinkFromSrc = false;
@@ -435,21 +436,28 @@ static bool GetLinkageResult(GlobalValue *Dest, GlobalValue *Src,
     return Error(Err, "Linking globals named '" + Src->getName() +
                  "': symbol multiply defined!");
   }
+
+  // Check visibility
+  if (Dest && Src->getVisibility() != Dest->getVisibility())
+    if (!Src->isDeclaration() && !Dest->isDeclaration())
+      return Error(Err, "Linking globals named '" + Src->getName() +
+                   "': symbols have different visibilities!");
   return false;
 }
 
 // LinkGlobals - Loop through the global variables in the src module and merge
 // them into the dest module.
-static bool LinkGlobals(Module *Dest, Module *Src,
+static bool LinkGlobals(Module *Dest, const Module *Src,
                         std::map<const Value*, Value*> &ValueMap,
                     std::multimap<std::string, GlobalVariable *> &AppendingVars,
                         std::string *Err) {
   // Loop over all of the globals in the src module, mapping them over as we go
-  for (Module::global_iterator I = Src->global_begin(), E = Src->global_end();
+  for (Module::const_global_iterator I = Src->global_begin(), E = Src->global_end();
        I != E; ++I) {
-    GlobalVariable *SGV = I;
-    GlobalVariable *DGV = 0;
-    // Check to see if may have to link the global.
+    const GlobalVariable *SGV = I;
+    GlobalValue *DGV = 0;
+
+    // Check to see if may have to link the global with the global
     if (SGV->hasName() && !SGV->hasInternalLinkage()) {
       DGV = Dest->getGlobalVariable(SGV->getName());
       if (DGV && DGV->getType() != SGV->getType())
@@ -458,11 +466,20 @@ static bool LinkGlobals(Module *Dest, Module *Src,
                               &Dest->getTypeSymbolTable(), "");
     }
 
+    // Check to see if may have to link the global with the alias
+    if (!DGV && SGV->hasName() && !SGV->hasInternalLinkage()) {
+      DGV = Dest->getNamedAlias(SGV->getName());
+      if (DGV && DGV->getType() != SGV->getType())
+        // If types don't agree due to opaque types, try to resolve them.
+        RecursiveResolveTypes(SGV->getType(), DGV->getType(), 
+                              &Dest->getTypeSymbolTable(), "");
+    }
+
     if (DGV && DGV->hasInternalLinkage())
       DGV = 0;
 
-    assert(SGV->hasInitializer() || SGV->hasExternalWeakLinkage() ||
-           SGV->hasExternalLinkage() || SGV->hasDLLImportLinkage() &&
+    assert((SGV->hasInitializer() || SGV->hasExternalWeakLinkage() ||
+            SGV->hasExternalLinkage() || SGV->hasDLLImportLinkage()) &&
            "Global must either be external or have an initializer!");
 
     GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
@@ -477,7 +494,7 @@ static bool LinkGlobals(Module *Dest, Module *Src,
       GlobalVariable *NewDGV =
         new GlobalVariable(SGV->getType()->getElementType(),
                            SGV->isConstant(), SGV->getLinkage(), /*init*/0,
-                           SGV->getName(), Dest, SGV->isThreadLocal());
+                           SGV->getName(), Dest);
       // Propagate alignment, visibility and section info.
       CopyGVAttributes(NewDGV, SGV);
 
@@ -488,7 +505,8 @@ static bool LinkGlobals(Module *Dest, Module *Src,
         ForceRenaming(NewDGV, SGV->getName());
 
       // Make sure to remember this mapping...
-      ValueMap.insert(std::make_pair(SGV, NewDGV));
+      ValueMap[SGV] = NewDGV;
+
       if (SGV->hasAppendingLinkage())
         // Keep track that this is an appending variable...
         AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
@@ -500,57 +518,246 @@ static bool LinkGlobals(Module *Dest, Module *Src,
       GlobalVariable *NewDGV =
         new GlobalVariable(SGV->getType()->getElementType(),
                            SGV->isConstant(), SGV->getLinkage(), /*init*/0,
-                           "", Dest, SGV->isThreadLocal());
+                           "", Dest);
 
-      // Propagate alignment, section and visibility  info.
+      // Set alignment allowing CopyGVAttributes merge it with alignment of SGV.
       NewDGV->setAlignment(DGV->getAlignment());
+      // Propagate alignment, section and visibility info.
       CopyGVAttributes(NewDGV, SGV);
 
       // Make sure to remember this mapping...
-      ValueMap.insert(std::make_pair(SGV, NewDGV));
+      ValueMap[SGV] = NewDGV;
 
       // Keep track that this is an appending variable...
       AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
-    } else {
-      // Propagate alignment, section, and visibility info.
-      CopyGVAttributes(DGV, SGV);
-
-      // Otherwise, perform the mapping as instructed by GetLinkageResult.  If
-      // the types don't match, and if we are to link from the source, nuke DGV
-      // and create a new one of the appropriate type.
-      if (SGV->getType() != DGV->getType() && LinkFromSrc) {
-        GlobalVariable *NewDGV =
-          new GlobalVariable(SGV->getType()->getElementType(),
-                             DGV->isConstant(), DGV->getLinkage());
-        NewDGV->setThreadLocal(DGV->isThreadLocal());
-        CopyGVAttributes(NewDGV, DGV);
-        Dest->getGlobalList().insert(DGV, NewDGV);
-        DGV->replaceAllUsesWith(
-            ConstantExpr::getBitCast(NewDGV, DGV->getType()));
-        DGV->eraseFromParent();
-        NewDGV->setName(SGV->getName());
-        DGV = NewDGV;
-      }
-
-      DGV->setLinkage(NewLinkage);
-
+    } else if (GlobalAlias *DGA = dyn_cast<GlobalAlias>(DGV)) {
+      // SGV is global, but DGV is alias. The only valid mapping is when SGV is
+      // external declaration, which is effectively a no-op. Also make sure
+      // linkage calculation was correct.
+      if (SGV->isDeclaration() && !LinkFromSrc) {
+        // Make sure to remember this mapping...
+        ValueMap[SGV] = DGA;
+      } else
+        return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
+                     "': symbol multiple defined");
+    } else if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV)) {
+      // Otherwise, perform the global-global mapping as instructed by
+      // GetLinkageResult.
       if (LinkFromSrc) {
+        // Propagate alignment, section, and visibility info.
+        CopyGVAttributes(DGVar, SGV);
+
+        // If the types don't match, and if we are to link from the source, nuke
+        // DGV and create a new one of the appropriate type.
+        if (SGV->getType() != DGVar->getType()) {
+          GlobalVariable *NewDGV =
+            new GlobalVariable(SGV->getType()->getElementType(),
+                               DGVar->isConstant(), DGVar->getLinkage(),
+                               /*init*/0, DGVar->getName(), Dest);
+          CopyGVAttributes(NewDGV, DGVar);
+          DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV,
+                                                           DGVar->getType()));
+          // DGVar will conflict with NewDGV because they both had the same
+          // name. We must erase this now so ForceRenaming doesn't assert
+          // because DGV might not have internal linkage.
+          DGVar->eraseFromParent();
+
+          // If the symbol table renamed the global, but it is an externally
+          // visible symbol, DGV must be an existing global with internal
+          // linkage. Rename it.
+          if (NewDGV->getName() != SGV->getName() &&
+              !NewDGV->hasInternalLinkage())
+            ForceRenaming(NewDGV, SGV->getName());
+
+          DGVar = NewDGV;
+        }
+
         // Inherit const as appropriate
-        DGV->setConstant(SGV->isConstant());
-        DGV->setInitializer(0);
+        DGVar->setConstant(SGV->isConstant());
+
+        // Set initializer to zero, so we can link the stuff later
+        DGVar->setInitializer(0);
       } else {
-        if (SGV->isConstant() && !DGV->isConstant()) {
-          if (DGV->isDeclaration())
-            DGV->setConstant(true);
-        }
-        SGV->setLinkage(GlobalValue::ExternalLinkage);
-        SGV->setInitializer(0);
+        // Special case for const propagation
+        if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
+          DGVar->setConstant(true);
       }
 
-      ValueMap.insert(
-        std::make_pair(SGV, ConstantExpr::getBitCast(DGV, SGV->getType())));
+      // Set calculated linkage
+      DGVar->setLinkage(NewLinkage);
+
+      // Make sure to remember this mapping...
+      ValueMap[SGV] = ConstantExpr::getBitCast(DGVar, SGV->getType());
+    }
+  }
+  return false;
+}
+
+static GlobalValue::LinkageTypes
+CalculateAliasLinkage(const GlobalValue *SGV, const GlobalValue *DGV) {
+  if (SGV->hasExternalLinkage() || DGV->hasExternalLinkage())
+    return GlobalValue::ExternalLinkage;
+  else if (SGV->hasWeakLinkage() || DGV->hasWeakLinkage())
+    return GlobalValue::WeakLinkage;
+  else {
+    assert(SGV->hasInternalLinkage() && DGV->hasInternalLinkage() &&
+           "Unexpected linkage type");
+    return GlobalValue::InternalLinkage;
+  }
+}
+
+// LinkAlias - Loop through the alias in the src module and link them into the
+// dest module. We're assuming, that all functions/global variables were already
+// linked in.
+static bool LinkAlias(Module *Dest, const Module *Src,
+                      std::map<const Value*, Value*> &ValueMap,
+                      std::string *Err) {
+  // Loop over all alias in the src module
+  for (Module::const_alias_iterator I = Src->alias_begin(),
+         E = Src->alias_end(); I != E; ++I) {
+    const GlobalAlias *SGA = I;
+    const GlobalValue *SAliasee = SGA->getAliasedGlobal();
+    GlobalAlias *NewGA = NULL;
+
+    // Globals were already linked, thus we can just query ValueMap for variant
+    // of SAliasee in Dest.
+    std::map<const Value*,Value*>::const_iterator VMI = ValueMap.find(SAliasee);
+    assert(VMI != ValueMap.end() && "Aliasee not linked");
+    GlobalValue* DAliasee = cast<GlobalValue>(VMI->second);
+    GlobalValue* DGV = NULL;
+
+    // Try to find something 'similar' to SGA in destination module.
+    if (!DGV && !SGA->hasInternalLinkage()) {
+      DGV = Dest->getNamedAlias(SGA->getName());
+
+      // If types don't agree due to opaque types, try to resolve them.
+      if (DGV && DGV->getType() != SGA->getType())
+        if (RecursiveResolveTypes(SGA->getType(), DGV->getType(),
+                                  &Dest->getTypeSymbolTable(), ""))
+          return Error(Err, "Alias Collision on '" + SGA->getName()+
+                       "': aliases have different types");
+    }
+
+    if (!DGV && !SGA->hasInternalLinkage()) {
+      DGV = Dest->getGlobalVariable(SGA->getName());
+
+      // If types don't agree due to opaque types, try to resolve them.
+      if (DGV && DGV->getType() != SGA->getType())
+        if (RecursiveResolveTypes(SGA->getType(), DGV->getType(),
+                                  &Dest->getTypeSymbolTable(), ""))
+          return Error(Err, "Alias Collision on '" + SGA->getName()+
+                       "': aliases have different types");
+    }
+
+    if (!DGV && !SGA->hasInternalLinkage()) {
+      DGV = Dest->getFunction(SGA->getName());
+
+      // If types don't agree due to opaque types, try to resolve them.
+      if (DGV && DGV->getType() != SGA->getType())
+        if (RecursiveResolveTypes(SGA->getType(), DGV->getType(),
+                                  &Dest->getTypeSymbolTable(), ""))
+          return Error(Err, "Alias Collision on '" + SGA->getName()+
+                       "': aliases have different types");
     }
+
+    // No linking to be performed on internal stuff.
+    if (DGV && DGV->hasInternalLinkage())
+      DGV = NULL;
+
+    if (GlobalAlias *DGA = dyn_cast_or_null<GlobalAlias>(DGV)) {
+      // Types are known to be the same, check whether aliasees equal. As
+      // globals are already linked we just need query ValueMap to find the
+      // mapping.
+      if (DAliasee == DGA->getAliasedGlobal()) {
+        // This is just two copies of the same alias. Propagate linkage, if
+        // necessary.
+        DGA->setLinkage(CalculateAliasLinkage(SGA, DGA));
+
+        NewGA = DGA;
+        // Proceed to 'common' steps
+      } else
+        return Error(Err, "Alias Collision on '"  + SGA->getName()+
+                     "': aliases have different aliasees");
+    } else if (GlobalVariable *DGVar = dyn_cast_or_null<GlobalVariable>(DGV)) {
+      // The only allowed way is to link alias with external declaration.
+      if (DGVar->isDeclaration()) {
+        // But only if aliasee is global too...
+        if (!isa<GlobalVariable>(DAliasee))
+          return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
+                       "': aliasee is not global variable");
+
+        NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
+                                SGA->getName(), DAliasee, Dest);
+        CopyGVAttributes(NewGA, SGA);
+
+        // Any uses of DGV need to change to NewGA, with cast, if needed.
+        if (SGA->getType() != DGVar->getType())
+          DGVar->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
+                                                             DGVar->getType()));
+        else
+          DGVar->replaceAllUsesWith(NewGA);
+
+        // DGVar will conflict with NewGA because they both had the same
+        // name. We must erase this now so ForceRenaming doesn't assert
+        // because DGV might not have internal linkage.
+        DGVar->eraseFromParent();
+
+        // Proceed to 'common' steps
+      } else
+        return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
+                     "': symbol multiple defined");
+    } else if (Function *DF = dyn_cast_or_null<Function>(DGV)) {
+      // The only allowed way is to link alias with external declaration.
+      if (DF->isDeclaration()) {
+        // But only if aliasee is function too...
+        if (!isa<Function>(DAliasee))
+          return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
+                       "': aliasee is not function");
+
+        NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
+                                SGA->getName(), DAliasee, Dest);
+        CopyGVAttributes(NewGA, SGA);
+
+        // Any uses of DF need to change to NewGA, with cast, if needed.
+        if (SGA->getType() != DF->getType())
+          DF->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
+                                                          DF->getType()));
+        else
+          DF->replaceAllUsesWith(NewGA);
+
+        // DF will conflict with NewGA because they both had the same
+        // name. We must erase this now so ForceRenaming doesn't assert
+        // because DF might not have internal linkage.
+        DF->eraseFromParent();
+
+        // Proceed to 'common' steps
+      } else
+        return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
+                     "': symbol multiple defined");
+    } else {
+      // No linking to be performed, simply create an identical version of the
+      // alias over in the dest module...
+
+      NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
+                              SGA->getName(), DAliasee, Dest);
+      CopyGVAttributes(NewGA, SGA);
+
+      // Proceed to 'common' steps
+    }
+
+    assert(NewGA && "No alias was created in destination module!");
+
+    // If the symbol table renamed the alias, but it is an externally visible
+    // symbol, DGA must be an global value with internal linkage. Rename it.
+    if (NewGA->getName() != SGA->getName() &&
+        !NewGA->hasInternalLinkage())
+      ForceRenaming(NewGA, SGA->getName());
+
+    // Remember this mapping so uses in the source module get remapped
+    // later by RemapOperand.
+    ValueMap[SGA] = NewGA;
   }
+
   return false;
 }
 
@@ -571,17 +778,19 @@ static bool LinkGlobalInits(Module *Dest, const Module *Src,
       Constant *SInit =
         cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap));
 
-      GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[SGV]);
+      GlobalVariable *DGV =
+        cast<GlobalVariable>(ValueMap[SGV]->stripPointerCasts());
       if (DGV->hasInitializer()) {
         if (SGV->hasExternalLinkage()) {
           if (DGV->getInitializer() != SInit)
-            return Error(Err, "Global Variable Collision on '" +
-                         ToStr(SGV->getType(), Src) +"':%"+SGV->getName()+
-                         " - Global variables have different initializers");
-        } else if (DGV->hasLinkOnceLinkage() || DGV->hasWeakLinkage()) {
+            return Error(Err, "Global Variable Collision on '" + SGV->getName() +
+                         "': global variables have different initializers");
+        } else if (DGV->hasLinkOnceLinkage() || DGV->hasWeakLinkage() ||
+                   DGV->hasCommonLinkage()) {
           // Nothing is required, mapped values will take the new global
           // automatically.
-        } else if (SGV->hasLinkOnceLinkage() || SGV->hasWeakLinkage()) {
+        } else if (SGV->hasLinkOnceLinkage() || SGV->hasWeakLinkage() ||
+                   SGV->hasCommonLinkage()) {
           // Nothing is required, mapped values will take the new global
           // automatically.
         } else if (DGV->hasAppendingLinkage()) {
@@ -617,14 +826,28 @@ static bool LinkFunctionProtos(Module *Dest, const Module *Src,
         RecursiveResolveTypes(SF->getType(), DF->getType(), 
                               &Dest->getTypeSymbolTable(), "");
     }
+
+    // Check visibility
+    if (DF && !DF->hasInternalLinkage() &&
+        SF->getVisibility() != DF->getVisibility()) {
+      // If one is a prototype, ignore its visibility.  Prototypes are always
+      // overridden by the definition.
+      if (!SF->isDeclaration() && !DF->isDeclaration())
+        return Error(Err, "Linking functions named '" + SF->getName() +
+                     "': symbols have different visibilities!");
+    }
     
+    if (DF && DF->hasInternalLinkage())
+      DF = NULL;
+
     if (DF && DF->getType() != SF->getType()) {
       if (DF->isDeclaration() && !SF->isDeclaration()) {
         // We have a definition of the same name but different type in the
         // source module. Copy the prototype to the destination and replace
         // uses of the destination's prototype with the new prototype.
-        Function *NewDF = new Function(SF->getFunctionType(), SF->getLinkage(),
-                                       SF->getName(), Dest);
+        Function *NewDF = Function::Create(SF->getFunctionType(),
+                                           SF->getLinkage(),
+                                           SF->getName(), Dest);
         CopyGVAttributes(NewDF, SF);
 
         // Any uses of DF need to change to NewDF, with cast
@@ -658,9 +881,10 @@ static bool LinkFunctionProtos(Module *Dest, const Module *Src,
       }
     } else if (!DF || SF->hasInternalLinkage() || DF->hasInternalLinkage()) {
       // Function does not already exist, simply insert an function signature
-      // identical to SF into the dest module...
-      Function *NewDF = new Function(SF->getFunctionType(), SF->getLinkage(),
-                                     SF->getName(), Dest);
+      // identical to SF into the dest module.
+      Function *NewDF = Function::Create(SF->getFunctionType(),
+                                         SF->getLinkage(),
+                                         SF->getName(), Dest);
       CopyGVAttributes(NewDF, SF);
 
       // If the LLVM runtime renamed the function, but it is an externally
@@ -670,7 +894,7 @@ static bool LinkFunctionProtos(Module *Dest, const Module *Src,
         ForceRenaming(NewDF, SF->getName());
 
       // ... and remember this mapping...
-      ValueMap.insert(std::make_pair(SF, NewDF));
+      ValueMap[SF] = NewDF;
     } else if (SF->isDeclaration()) {
       // If SF is a declaration or if both SF & DF are declarations, just link 
       // the declarations, we aren't adding anything.
@@ -680,25 +904,30 @@ static bool LinkFunctionProtos(Module *Dest, const Module *Src,
           DF->setLinkage(SF->getLinkage());          
         }        
       } else {
-        ValueMap.insert(std::make_pair(SF, DF));
+        ValueMap[SF] = DF;
       }      
     } else if (DF->isDeclaration() && !DF->hasDLLImportLinkage()) {
       // If DF is external but SF is not...
       // Link the external functions, update linkage qualifiers
       ValueMap.insert(std::make_pair(SF, DF));
       DF->setLinkage(SF->getLinkage());
-    } else if (SF->hasWeakLinkage() || SF->hasLinkOnceLinkage()) {
+      // Visibility of prototype is overridden by vis of definition.
+      DF->setVisibility(SF->getVisibility());
+    } else if (SF->hasWeakLinkage() || SF->hasLinkOnceLinkage() ||
+               SF->hasCommonLinkage()) {
       // At this point we know that DF has LinkOnce, Weak, or External* linkage.
-      ValueMap.insert(std::make_pair(SF, DF));
+      ValueMap[SF] = DF;
 
       // Linkonce+Weak = Weak
       // *+External Weak = *
-      if ((DF->hasLinkOnceLinkage() && SF->hasWeakLinkage()) ||
+      if ((DF->hasLinkOnceLinkage() && 
+              (SF->hasWeakLinkage() || SF->hasCommonLinkage())) ||
           DF->hasExternalWeakLinkage())
         DF->setLinkage(SF->getLinkage());
-    } else if (DF->hasWeakLinkage() || DF->hasLinkOnceLinkage()) {
+    } else if (DF->hasWeakLinkage() || DF->hasLinkOnceLinkage() ||
+               DF->hasCommonLinkage()) {
       // At this point we know that SF has LinkOnce or External* linkage.
-      ValueMap.insert(std::make_pair(SF, DF));
+      ValueMap[SF] = DF;
       if (!SF->hasLinkOnceLinkage() && !SF->hasExternalWeakLinkage())
         // Don't inherit linkonce & external weak linkage
         DF->setLinkage(SF->getLinkage());
@@ -732,7 +961,7 @@ static bool LinkFunctionBody(Function *Dest, Function *Src,
     DI->setName(I->getName());  // Copy the name information over...
 
     // Add a mapping to our local map
-    ValueMap.insert(std::make_pair(I, DI));
+    ValueMap[I] = DI;
   }
 
   // Splice the body of the source function into the dest function.
@@ -814,6 +1043,18 @@ static bool LinkAppendingVars(Module *M,
         return Error(ErrorMsg,
                      "Appending variables linked with different const'ness!");
 
+      if (G1->getAlignment() != G2->getAlignment())
+        return Error(ErrorMsg,
+         "Appending variables with different alignment need to be linked!");
+
+      if (G1->getVisibility() != G2->getVisibility())
+        return Error(ErrorMsg,
+         "Appending variables with different visibility need to be linked!");
+
+      if (G1->getSection() != G2->getSection())
+        return Error(ErrorMsg,
+         "Appending variables with different section name need to be linked!");
+      
       unsigned NewSize = T1->getNumElements() + T2->getNumElements();
       ArrayType *NewType = ArrayType::get(T1->getElementType(), NewSize);
 
@@ -824,6 +1065,9 @@ static bool LinkAppendingVars(Module *M,
         new GlobalVariable(NewType, G1->isConstant(), G1->getLinkage(),
                            /*init*/0, First->first, M, G1->isThreadLocal());
 
+      // Propagate alignment, visibility and section info.
+      CopyGVAttributes(NG, G1);
+
       // Merge the initializer...
       Inits.reserve(NewSize);
       if (ConstantArray *I = dyn_cast<ConstantArray>(G1->getInitializer())) {
@@ -869,6 +1113,15 @@ static bool LinkAppendingVars(Module *M,
   return false;
 }
 
+static bool ResolveAliases(Module *Dest) {
+  for (Module::alias_iterator I = Dest->alias_begin(), E = Dest->alias_end();
+       I != E; ++I)
+    if (const GlobalValue *GV = I->resolveAliasedGlobal())
+      if (!GV->isDeclaration())
+        I->replaceAllUsesWith(const_cast<GlobalValue*>(GV));
+
+  return false;
+}
 
 // LinkModules - This function links two modules together, with the resulting
 // left module modified to be the composite of the two input modules.  If an
@@ -886,21 +1139,24 @@ Linker::LinkModules(Module *Dest, Module *Src, std::string *ErrorMsg) {
     } else {
       std::string DataLayout;
 
-      if (Dest->getEndianness() == Module::AnyEndianness)
+      if (Dest->getEndianness() == Module::AnyEndianness) {
         if (Src->getEndianness() == Module::BigEndian)
           DataLayout.append("E");
         else if (Src->getEndianness() == Module::LittleEndian)
           DataLayout.append("e");
-      if (Dest->getPointerSize() == Module::AnyPointerSize)
+      }
+
+      if (Dest->getPointerSize() == Module::AnyPointerSize) {
         if (Src->getPointerSize() == Module::Pointer64)
           DataLayout.append(DataLayout.length() == 0 ? "p:64:64" : "-p:64:64");
         else if (Src->getPointerSize() == Module::Pointer32)
           DataLayout.append(DataLayout.length() == 0 ? "p:32:32" : "-p:32:32");
+      }
       Dest->setDataLayout(DataLayout);
     }
   }
 
-  // COpy the target triple from the source to dest if the dest's is empty
+  // Copy the target triple from the source to dest if the dest's is empty.
   if (Dest->getTargetTriple().empty() && !Src->getTargetTriple().empty())
     Dest->setTargetTriple(Src->getTargetTriple());
       
@@ -911,7 +1167,7 @@ Linker::LinkModules(Module *Dest, Module *Src, std::string *ErrorMsg) {
       Dest->getTargetTriple() != Src->getTargetTriple())
     cerr << "WARNING: Linking two modules of different target triples!\n";
 
-  // Append the module inline asm string
+  // Append the module inline asm string.
   if (!Src->getModuleInlineAsm().empty()) {
     if (Dest->getModuleInlineAsm().empty())
       Dest->setModuleInlineAsm(Src->getModuleInlineAsm());
@@ -923,12 +1179,9 @@ Linker::LinkModules(Module *Dest, Module *Src, std::string *ErrorMsg) {
   // Update the destination module's dependent libraries list with the libraries
   // from the source module. There's no opportunity for duplicates here as the
   // Module ensures that duplicate insertions are discarded.
-  Module::lib_iterator SI = Src->lib_begin();
-  Module::lib_iterator SE = Src->lib_end();
-  while ( SI != SE ) {
+  for (Module::lib_iterator SI = Src->lib_begin(), SE = Src->lib_end();
+       SI != SE; ++SI) 
     Dest->addLibrary(*SI);
-    ++SI;
-  }
 
   // LinkTypes - Go through the symbol table of the Src module and see if any
   // types are named in the src module that are not named in the Dst module.
@@ -965,6 +1218,11 @@ Linker::LinkModules(Module *Dest, Module *Src, std::string *ErrorMsg) {
   if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg))
     return true;
 
+  // If there were any alias, link them now. We really need to do this now,
+  // because all of the aliases that may be referenced need to be available in
+  // ValueMap
+  if (LinkAlias(Dest, Src, ValueMap, ErrorMsg)) return true;
+
   // Update the initializers in the Dest module now that all globals that may
   // be referenced are in Dest.
   if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
@@ -977,6 +1235,9 @@ Linker::LinkModules(Module *Dest, Module *Src, std::string *ErrorMsg) {
   // If there were any appending global variables, link them together now.
   if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
 
+  // Resolve all uses of aliases with aliasees
+  if (ResolveAliases(Dest)) return true;
+
   // If the source library's module id is in the dependent library list of the
   // destination library, remove it since that module is now linked in.
   sys::Path modId;