Fix corner cases of setting the section address.

This handles all the corner cases if setting a section address:

- If the address is too low, we cannot allocate the program headers.
- If the load address is lowered, we have to do that before finalize

This also shares some code with the linker script since it was already
hitting similar cases.

This is used by the freebsd boot loader. It is not clear if we need to
support this with a non binary output, but it is not as bad as I was
expecting.

llvm-svn: 290136
diff --git a/lld/ELF/LinkerScript.cpp b/lld/ELF/LinkerScript.cpp
index b99ddd7..53daaa6 100644
--- a/lld/ELF/LinkerScript.cpp
+++ b/lld/ELF/LinkerScript.cpp
@@ -748,19 +748,10 @@
   }
 
   uintX_t HeaderSize = getHeaderSize();
-  auto FirstPTLoad =
-      std::find_if(Phdrs.begin(), Phdrs.end(),
-                   [](const PhdrEntry &E) { return E.p_type == PT_LOAD; });
-  if (FirstPTLoad == Phdrs.end())
-    return;
-
   // If the linker script doesn't have PHDRS, add ElfHeader and ProgramHeaders
   // now that we know we have space.
-  if (HeaderSize <= MinVA && !hasPhdrsCommands()) {
-    FirstPTLoad->First = Out<ELFT>::ElfHeader;
-    if (!FirstPTLoad->Last)
-      FirstPTLoad->Last = Out<ELFT>::ProgramHeaders;
-  }
+  if (HeaderSize <= MinVA && !hasPhdrsCommands())
+    allocateHeaders<ELFT>(Phdrs, *OutputSections);
 
   // ELF and Program headers need to be right before the first section in
   // memory. Set their addresses accordingly.