Specialize branched loops

Continuation of PR #469 inside the main repo.